feat(etcd): add cluster operations and access control

This commit is contained in:
二丫讲梵 authored and GitHub committed 2026-07-31 01:06:02 +08:00
1 parent 774b1612dc
commit 99b1b73967
55 files changed
+7502 -750

No files matched your search

@@ -0,0 +1,768 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { KeyRound, Loader2, LockKeyhole, Pencil, Plus, RefreshCw, ShieldCheck, Trash2, UserPlus, UsersRound } from "@lucide/vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import * as api from "@/lib/backend/api";
import { useConnectionStore } from "@/stores/connectionStore";
type AccessView = "users" | "roles";
type PermissionAccess = "read" | "write" | "readwrite";
type PermissionResource = "all" | "key" | "prefix";
const props = defineProps<{ connectionId: string }>();
const { t } = useI18n();
const connectionStore = useConnectionStore();
const view = ref<AccessView>("users");
const loading = ref(false);
const busy = ref(false);
const error = ref("");
const notice = ref("");
const users = ref<string[]>([]);
const roles = ref<string[]>([]);
const selectedUser = ref("");
const selectedRole = ref("");
const userDetail = ref<api.EtcdAuthUserDetail | null>(null);
const roleDetail = ref<api.EtcdAuthRoleDetail | null>(null);
const detailLoading = ref(false);
const createUserOpen = ref(false);
const createRoleOpen = ref(false);
const passwordOpen = ref(false);
const permissionOpen = ref(false);
const approvalOpen = ref(false);
const newUser = ref("");
const newUserPassword = ref("");
const newUserRoles = ref<string[]>([]);
const newRole = ref("");
const newRolePermissionKey = ref("");
const newRolePermissionResource = ref<PermissionResource>("prefix");
const newRolePermissionAccess = ref<PermissionAccess>("readwrite");
const newPassword = ref("");
const selectedGrantRole = ref("");
const permissionKey = ref("");
const permissionResource = ref<PermissionResource>("prefix");
const permissionAccess = ref<PermissionAccess>("readwrite");
const editingPermission = ref<api.EtcdAuthPermission | null>(null);
const permissionError = ref("");
const approvalText = ref("");
const approvalExpected = ref("");
let pendingApproval: (() => Promise<void>) | null = null;
let detailRequest = 0;
const readOnly = computed(() => Boolean(connectionStore.getConfig(props.connectionId)?.read_only));
const selectedUserRoles = computed(() => userDetail.value?.roles ?? []);
const grantableRoles = computed(() => roles.value.filter((role) => !selectedUserRoles.value.includes(role)));
const initialUserRoleLabel = computed(() => (newUserRoles.value.length ? t("etcd.access.createAndAssignRoles", { count: newUserRoles.value.length }) : t("etcd.access.createUserAction")));
const hasInitialRolePermission = computed(() => newRolePermissionResource.value === "all" || !!newRolePermissionKey.value);
const hasPermissionTarget = computed(() => permissionResource.value === "all" || !!permissionKey.value);
function reset(message = "") {
error.value = "";
notice.value = message;
}
function displayValue(value: api.KvValue): string {
if (value.encoding === "utf8") return value.data;
try {
const bytes = Uint8Array.from(atob(value.data), (character) => character.charCodeAt(0));
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
} catch {
return `base64:${value.data}`;
}
}
function permissionResourceOf(permission: api.EtcdAuthPermission): PermissionResource {
if (permission.resource) return permission.resource;
if (permission.key.data === "" && permission.rangeEnd.encoding === "base64" && permission.rangeEnd.data === "AA==") return "all";
return permission.rangeEnd.data ? "prefix" : "key";
}
function permissionLabel(access: PermissionAccess): string {
return access === "readwrite" ? t("etcd.access.readWrite") : access === "read" ? t("etcd.access.read") : t("etcd.access.write");
}
function permissionParams(permission: api.EtcdAuthPermission) {
return {
role: selectedRole.value,
key: displayValue(permission.key),
keyBytes: permission.key,
resource: permissionResourceOf(permission),
access: permission.access,
};
}
function errorMessage(caught: unknown): string {
const message = caught instanceof Error ? caught.message : String(caught);
if (message.includes("ETCD_PREFLIGHT_REQUIRED")) return t("etcd.access.preflightRequired");
if (message.includes("ETCD_PREFLIGHT_EXPIRED")) return t("etcd.access.preflightExpired");
if (message.includes("ETCD_PREFLIGHT_MISMATCH")) return t("etcd.access.preflightMismatch");
return message;
}
async function run(action: () => Promise<void>) {
busy.value = true;
reset();
try {
await action();
} catch (caught) {
error.value = caught instanceof Error ? caught.message : String(caught);
} finally {
busy.value = false;
}
}
async function requestApproval(action: string, params: Record<string, unknown>, execute: (approval: api.EtcdDangerousApproval) => Promise<void>) {
if (readOnly.value) return;
try {
const preflight = await api.etcdPreflight(props.connectionId, action, params);
approvalExpected.value = preflight.confirmationText;
approvalText.value = "";
pendingApproval = () => execute({ preflightToken: preflight.token, confirmationText: preflight.confirmationText });
approvalOpen.value = true;
} catch (caught) {
error.value = caught instanceof Error ? caught.message : String(caught);
}
}
async function confirmApproval() {
if (approvalText.value !== approvalExpected.value || !pendingApproval) return;
const execute = pendingApproval;
pendingApproval = null;
approvalOpen.value = false;
await run(execute);
}
function closeApproval() {
approvalOpen.value = false;
pendingApproval = null;
approvalText.value = "";
}
async function loadDirectory() {
loading.value = true;
reset();
try {
const [userResponse, roleResponse] = await Promise.all([api.etcdAuthCall<api.EtcdAuthUserListResponse>(props.connectionId, "user_list", {}), api.etcdAuthCall<api.EtcdAuthRoleListResponse>(props.connectionId, "role_list", {})]);
users.value = userResponse.users ?? [];
roles.value = roleResponse.roles ?? [];
if (selectedUser.value && !users.value.includes(selectedUser.value)) {
selectedUser.value = "";
userDetail.value = null;
}
if (selectedRole.value && !roles.value.includes(selectedRole.value)) {
selectedRole.value = "";
roleDetail.value = null;
}
await ensureSelectedForView();
} catch (caught) {
error.value = caught instanceof Error ? caught.message : String(caught);
} finally {
loading.value = false;
}
}
async function selectUser(user: string) {
const request = ++detailRequest;
selectedUser.value = user;
userDetail.value = null;
detailLoading.value = true;
try {
const detail = await api.etcdAuthCall<api.EtcdAuthUserDetail>(props.connectionId, "user_get", { user });
if (request !== detailRequest || view.value !== "users" || selectedUser.value !== user) return;
userDetail.value = detail;
} catch (caught) {
if (request !== detailRequest || view.value !== "users" || selectedUser.value !== user) return;
error.value = caught instanceof Error ? caught.message : String(caught);
} finally {
if (request === detailRequest) detailLoading.value = false;
}
}
async function selectRole(role: string) {
const request = ++detailRequest;
selectedRole.value = role;
roleDetail.value = null;
detailLoading.value = true;
try {
const detail = await api.etcdAuthCall<api.EtcdAuthRoleDetail>(props.connectionId, "role_get", { role });
if (request !== detailRequest || view.value !== "roles" || selectedRole.value !== role) return;
roleDetail.value = detail;
} catch (caught) {
if (request !== detailRequest || view.value !== "roles" || selectedRole.value !== role) return;
error.value = caught instanceof Error ? caught.message : String(caught);
} finally {
if (request === detailRequest) detailLoading.value = false;
}
}
async function ensureSelectedForView(targetView = view.value) {
if (targetView === "users") {
if (selectedUser.value && users.value.includes(selectedUser.value)) {
if (userDetail.value?.user === selectedUser.value) return;
await selectUser(selectedUser.value);
return;
}
const firstUser = users.value[0];
if (firstUser) await selectUser(firstUser);
return;
}
if (selectedRole.value && roles.value.includes(selectedRole.value)) {
if (roleDetail.value?.role === selectedRole.value) return;
await selectRole(selectedRole.value);
return;
}
const firstRole = roles.value[0];
if (firstRole) await selectRole(firstRole);
}
async function selectView(targetView: AccessView) {
if (view.value !== targetView) {
detailRequest++;
detailLoading.value = false;
}
view.value = targetView;
await ensureSelectedForView(targetView);
}
async function createUser() {
if (!newUser.value.trim() || !newUserPassword.value || readOnly.value) return;
const user = newUser.value.trim();
const password = newUserPassword.value;
const initialRoles = [...newUserRoles.value];
const create = async (approvals: api.EtcdDangerousApproval[]) => {
await api.etcdAuthCall(props.connectionId, "user_add", { user, password }, approvals[0]);
try {
for (const [index, role] of initialRoles.entries()) {
await api.etcdAuthCall(props.connectionId, "user_grant_role", { user, role }, approvals[index + 1]);
}
} catch (caught) {
await loadDirectory();
await selectUser(user);
createUserOpen.value = false;
throw new Error(t("etcd.access.createdUserRolesFailed", { error: errorMessage(caught) }));
}
newUser.value = "";
newUserPassword.value = "";
newUserRoles.value = [];
createUserOpen.value = false;
await loadDirectory();
await selectUser(user);
notice.value = initialRoles.length ? t("etcd.access.createdUserWithRoles", { user, count: initialRoles.length }) : t("etcd.access.createdUser", { user });
};
busy.value = true;
reset();
try {
const preflights = await Promise.all([api.etcdPreflight(props.connectionId, "auth_user_add", { user, password }), ...initialRoles.map((role) => api.etcdPreflight(props.connectionId, "auth_user_grant_role", { user, role }))]);
if (preflights.some((preflight) => preflight.confirmationText !== preflights[0].confirmationText)) {
throw new Error(t("etcd.access.confirmationMismatch"));
}
approvalExpected.value = preflights[0].confirmationText;
approvalText.value = "";
pendingApproval = () => create(preflights.map((preflight) => ({ preflightToken: preflight.token, confirmationText: preflight.confirmationText })));
approvalOpen.value = true;
} catch (caught) {
error.value = errorMessage(caught);
} finally {
busy.value = false;
}
}
function openCreateUser() {
newUser.value = "";
newUserPassword.value = "";
newUserRoles.value = [];
createUserOpen.value = true;
}
async function createRole() {
if (!newRole.value.trim() || readOnly.value) return;
const role = newRole.value.trim();
const initialPermission = hasInitialRolePermission.value ? { role, key: newRolePermissionResource.value === "all" ? "" : newRolePermissionKey.value, resource: newRolePermissionResource.value, access: newRolePermissionAccess.value } : null;
const create = async (approvals: api.EtcdDangerousApproval[]) => {
await api.etcdAuthCall(props.connectionId, "role_add", { role }, approvals[0]);
if (initialPermission) {
try {
await api.etcdAuthCall(props.connectionId, "role_grant_permission", initialPermission, approvals[1]);
} catch (caught) {
await loadDirectory();
await selectRole(role);
createRoleOpen.value = false;
throw new Error(t("etcd.access.createdRolePermissionFailed", { error: errorMessage(caught) }));
}
}
newRole.value = "";
newRolePermissionKey.value = "";
newRolePermissionResource.value = "prefix";
newRolePermissionAccess.value = "readwrite";
createRoleOpen.value = false;
await loadDirectory();
await selectRole(role);
notice.value = initialPermission ? t("etcd.access.createdRoleWithPermission", { role }) : t("etcd.access.createdRole", { role });
};
busy.value = true;
reset();
try {
const preflights = await Promise.all([api.etcdPreflight(props.connectionId, "auth_role_add", { role }), ...(initialPermission ? [api.etcdPreflight(props.connectionId, "auth_role_grant_permission", initialPermission)] : [])]);
if (preflights.some((preflight) => preflight.confirmationText !== preflights[0].confirmationText)) {
throw new Error(t("etcd.access.confirmationMismatch"));
}
approvalExpected.value = preflights[0].confirmationText;
approvalText.value = "";
pendingApproval = () => create(preflights.map((preflight) => ({ preflightToken: preflight.token, confirmationText: preflight.confirmationText })));
approvalOpen.value = true;
} catch (caught) {
error.value = errorMessage(caught);
} finally {
busy.value = false;
}
}
function deleteUser(user: string) {
const params = { user };
void requestApproval("auth_user_delete", params, async (approval) => {
await api.etcdAuthCall(props.connectionId, "user_delete", params, approval);
await loadDirectory();
notice.value = t("etcd.access.deletedUser", { user });
});
}
function deleteRole(role: string) {
const params = { role };
void requestApproval("auth_role_delete", params, async (approval) => {
await api.etcdAuthCall(props.connectionId, "role_delete", params, approval);
await loadDirectory();
notice.value = t("etcd.access.deletedRole", { role });
});
}
function changePassword() {
if (!selectedUser.value || !newPassword.value || readOnly.value) return;
const params = { user: selectedUser.value, password: newPassword.value };
void requestApproval("auth_user_change_password", params, async (approval) => {
await api.etcdAuthCall(props.connectionId, "user_change_password", params, approval);
newPassword.value = "";
passwordOpen.value = false;
notice.value = t("etcd.access.passwordUpdated", { user: selectedUser.value });
});
}
function updateUserRole(grant: boolean, role: string) {
if (!selectedUser.value || !role || readOnly.value) return;
const params = { user: selectedUser.value, role };
const operation = grant ? "user_grant_role" : "user_revoke_role";
const action = grant ? "auth_user_grant_role" : "auth_user_revoke_role";
void requestApproval(action, params, async (approval) => {
await api.etcdAuthCall(props.connectionId, operation, params, approval);
await selectUser(selectedUser.value);
selectedGrantRole.value = "";
notice.value = grant ? t("etcd.access.roleGranted", { role, user: params.user }) : t("etcd.access.roleRevoked", { role, user: params.user });
});
}
function openGrantPermission() {
editingPermission.value = null;
permissionError.value = "";
permissionKey.value = "";
permissionResource.value = "prefix";
permissionAccess.value = "readwrite";
permissionOpen.value = true;
}
function openEditPermission(permission: api.EtcdAuthPermission) {
editingPermission.value = permission;
permissionError.value = "";
permissionResource.value = permissionResourceOf(permission);
permissionKey.value = permissionResource.value === "all" ? "" : displayValue(permission.key);
permissionAccess.value = permission.access;
permissionOpen.value = true;
}
function grantPermission() {
if (!selectedRole.value || !hasPermissionTarget.value || readOnly.value) return;
const params = { role: selectedRole.value, key: permissionResource.value === "all" ? "" : permissionKey.value, resource: permissionResource.value, access: permissionAccess.value };
void requestApproval("auth_role_grant_permission", params, async (approval) => {
await api.etcdAuthCall(props.connectionId, "role_grant_permission", params, approval);
permissionKey.value = "";
permissionOpen.value = false;
await selectRole(selectedRole.value);
notice.value = t("etcd.access.permissionGranted");
});
}
function editPermission() {
const previous = editingPermission.value;
if (!previous || !selectedRole.value || !hasPermissionTarget.value || readOnly.value) return;
const oldParams = permissionParams(previous);
const newParams = { role: selectedRole.value, key: permissionResource.value === "all" ? "" : permissionKey.value, resource: permissionResource.value, access: permissionAccess.value };
if (oldParams.key === newParams.key && oldParams.resource === newParams.resource && oldParams.access === newParams.access) {
permissionOpen.value = false;
return;
}
void requestPermissionReplacementApproval(oldParams, newParams);
}
async function requestPermissionReplacementApproval(oldParams: Record<string, unknown>, newParams: Record<string, unknown>) {
permissionError.value = "";
busy.value = true;
try {
const [revokePreflight, grantPreflight] = await Promise.all([api.etcdPreflight(props.connectionId, "auth_role_revoke_permission", oldParams), api.etcdPreflight(props.connectionId, "auth_role_grant_permission", newParams)]);
if (revokePreflight.confirmationText !== grantPreflight.confirmationText) {
throw new Error(t("etcd.access.confirmationMismatch"));
}
approvalExpected.value = revokePreflight.confirmationText;
approvalText.value = "";
pendingApproval = async () => {
let revoked = false;
try {
await api.etcdAuthCall(props.connectionId, "role_revoke_permission", oldParams, {
preflightToken: revokePreflight.token,
confirmationText: revokePreflight.confirmationText,
});
revoked = true;
await api.etcdAuthCall(props.connectionId, "role_grant_permission", newParams, {
preflightToken: grantPreflight.token,
confirmationText: grantPreflight.confirmationText,
});
} catch (caught) {
permissionError.value = errorMessage(caught);
if (revoked) {
try {
const restorePreflight = await api.etcdPreflight(props.connectionId, "auth_role_grant_permission", oldParams);
await api.etcdAuthCall(props.connectionId, "role_grant_permission", oldParams, {
preflightToken: restorePreflight.token,
confirmationText: restorePreflight.confirmationText,
});
} catch {
// Keep the actionable error. The next refresh exposes the actual
// etcd permission state if a best-effort recovery also fails.
}
}
throw caught;
}
editingPermission.value = null;
permissionOpen.value = false;
await selectRole(selectedRole.value);
notice.value = t("etcd.access.permissionUpdated");
};
approvalOpen.value = true;
} catch (caught) {
permissionError.value = errorMessage(caught);
} finally {
busy.value = false;
}
}
function savePermission() {
if (editingPermission.value) editPermission();
else grantPermission();
}
function revokePermission(permission: api.EtcdAuthPermission) {
if (!selectedRole.value || readOnly.value) return;
const params = permissionParams(permission);
void requestApproval("auth_role_revoke_permission", params, async (approval) => {
await api.etcdAuthCall(props.connectionId, "role_revoke_permission", params, approval);
await selectRole(selectedRole.value);
notice.value = t("etcd.access.permissionRevoked");
});
}
watch(
() => props.connectionId,
() => {
detailRequest++;
detailLoading.value = false;
selectedUser.value = "";
selectedRole.value = "";
userDetail.value = null;
roleDetail.value = null;
void loadDirectory();
},
);
watch(permissionResource, (resource) => {
if (resource === "all") permissionKey.value = "";
});
watch(newRolePermissionResource, (resource) => {
if (resource === "all") newRolePermissionKey.value = "";
});
onMounted(() => void loadDirectory());
</script>
<template>
<div class="flex h-full min-h-0 flex-col bg-background">
<header class="flex h-14 shrink-0 flex-wrap items-center gap-3 border-b px-4">
<div class="flex rounded-md border p-0.5 shadow-sm">
<Button size="sm" class="h-8 gap-1.5 px-3 text-sm" :variant="view === 'users' ? 'secondary' : 'ghost'" @click="void selectView('users')"><UsersRound class="h-4 w-4" />{{ t("etcd.access.users") }}</Button>
<Button size="sm" class="h-8 gap-1.5 px-3 text-sm" :variant="view === 'roles' ? 'secondary' : 'ghost'" @click="void selectView('roles')"><KeyRound class="h-4 w-4" />{{ t("etcd.access.roles") }}</Button>
</div>
<div class="hidden h-5 w-px bg-border sm:block" />
<div class="flex items-center gap-1.5 text-xs text-muted-foreground">
<ShieldCheck class="h-3.5 w-3.5 text-sky-600" />
<span class="font-medium text-foreground/75">{{ t("etcd.access.title") }}</span>
<span>{{ t("etcd.access.description") }}</span>
</div>
<div class="flex-1" />
<Badge v-if="readOnly" variant="outline">{{ t("etcd.access.readOnly") }}</Badge>
<Button size="sm" variant="outline" class="h-8 gap-1.5" :disabled="loading" @click="loadDirectory"><RefreshCw class="h-3.5 w-3.5" :class="loading ? 'animate-spin' : ''" />{{ t("etcd.access.refresh") }}</Button>
</header>
<div v-if="error" class="mx-4 mt-3 rounded border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">{{ error }}</div>
<div v-if="notice" class="mx-4 mt-3 rounded border bg-muted/40 px-3 py-2 text-sm">{{ notice }}</div>
<div v-if="view === 'users'" class="grid min-h-0 flex-1 md:grid-cols-[16rem_minmax(0,1fr)]">
<aside class="min-h-0 border-b md:border-b-0 md:border-r">
<div class="flex items-center justify-between border-b px-3 py-2">
<span class="text-sm font-medium">{{ t("etcd.access.userCount", { count: users.length }) }}</span>
<Button size="icon-xs" :disabled="readOnly" :title="t('etcd.access.createUser')" @click="openCreateUser"><UserPlus class="h-3.5 w-3.5" /></Button>
</div>
<div class="max-h-52 overflow-auto p-1 md:max-h-none md:h-[calc(100%-41px)]">
<button v-for="user in users" :key="user" type="button" class="flex w-full items-center rounded px-2 py-2 text-left text-sm hover:bg-accent" :class="selectedUser === user ? 'bg-accent font-medium text-foreground' : 'text-muted-foreground'" @click="selectUser(user)">{{ user }}</button>
<p v-if="!loading && users.length === 0" class="p-3 text-xs text-muted-foreground">{{ t("etcd.access.noUsers") }}</p>
</div>
</aside>
<main class="min-h-0 overflow-auto p-4">
<div v-if="!selectedUser" class="flex h-full min-h-48 items-center justify-center text-sm text-muted-foreground">{{ t("etcd.access.selectUser") }}</div>
<div v-else-if="detailLoading" class="flex h-32 items-center justify-center text-sm text-muted-foreground"><Loader2 class="mr-2 h-4 w-4 animate-spin" />{{ t("etcd.access.loadingUser") }}</div>
<template v-else-if="userDetail">
<div class="mb-5 flex flex-wrap items-center gap-2 border-b pb-4">
<div class="mr-auto">
<h3 class="font-mono text-base font-semibold">{{ userDetail.user }}</h3>
<p class="mt-1 text-xs text-muted-foreground">{{ t("etcd.access.userRolesSummary", { count: userDetail.roles.length }) }}</p>
</div>
<Button size="sm" variant="outline" class="gap-1.5" :disabled="readOnly" @click="passwordOpen = true"><LockKeyhole class="h-3.5 w-3.5" />{{ t("etcd.access.changePassword") }}</Button>
<Button size="sm" variant="destructive" class="gap-1.5" :disabled="readOnly" @click="deleteUser(userDetail.user)"><Trash2 class="h-3.5 w-3.5" />{{ t("etcd.access.deleteUser") }}</Button>
</div>
<section class="max-w-3xl space-y-5">
<div>
<div class="mb-3 flex items-center gap-2">
<h4 class="text-sm font-medium">{{ t("etcd.access.roleAssignments") }}</h4>
<Badge variant="secondary">{{ userDetail.roles.length }}</Badge>
</div>
<p class="mb-3 text-xs text-muted-foreground">{{ t("etcd.access.roleAssignmentHint") }}</p>
<div v-if="userDetail.roles.length" class="divide-y rounded border">
<div v-for="role in userDetail.roles" :key="role" class="flex items-center gap-3 px-3 py-2.5">
<KeyRound class="h-4 w-4 text-muted-foreground" /><code class="flex-1 text-sm">{{ role }}</code
><Button size="sm" variant="ghost" class="text-destructive hover:text-destructive" :disabled="readOnly || busy" @click="updateUserRole(false, role)">{{ t("etcd.access.revokeAssociation") }}</Button>
</div>
</div>
<p v-else class="rounded border border-dashed px-3 py-5 text-sm text-muted-foreground">{{ t("etcd.access.noAssignedRoles") }}</p>
</div>
<div class="border-t pt-4">
<h5 class="text-sm font-medium">{{ t("etcd.access.assignRole") }}</h5>
<p class="mt-1 text-xs text-muted-foreground">{{ t("etcd.access.assignRoleHint") }}</p>
<div class="mt-3 flex max-w-xl flex-wrap gap-2">
<select v-model="selectedGrantRole" class="h-9 min-w-52 rounded-md border bg-background px-3 text-sm" :disabled="readOnly || grantableRoles.length === 0">
<option value="">{{ grantableRoles.length ? t("etcd.access.selectRoleOption") : t("etcd.access.noAssignableRoles") }}</option>
<option v-for="role in grantableRoles" :key="role" :value="role">{{ role }}</option>
</select>
<Button size="sm" class="h-9 gap-1.5" :disabled="readOnly || busy || !selectedGrantRole" @click="updateUserRole(true, selectedGrantRole)"><Plus class="h-3.5 w-3.5" />{{ t("etcd.access.grantRole") }}</Button>
</div>
</div>
</section>
</template>
</main>
</div>
<div v-else class="grid min-h-0 flex-1 md:grid-cols-[16rem_minmax(0,1fr)]">
<aside class="min-h-0 border-b md:border-b-0 md:border-r">
<div class="flex items-center justify-between border-b px-3 py-2">
<span class="text-sm font-medium">{{ t("etcd.access.roleCount", { count: roles.length }) }}</span>
<Button size="icon-xs" :disabled="readOnly" :title="t('etcd.access.createRole')" @click="createRoleOpen = true"><Plus class="h-3.5 w-3.5" /></Button>
</div>
<div class="max-h-52 overflow-auto p-1 md:max-h-none md:h-[calc(100%-41px)]">
<button v-for="role in roles" :key="role" type="button" class="flex w-full items-center rounded px-2 py-2 text-left text-sm hover:bg-accent" :class="selectedRole === role ? 'bg-accent font-medium text-foreground' : 'text-muted-foreground'" @click="selectRole(role)">{{ role }}</button>
<p v-if="!loading && roles.length === 0" class="p-3 text-xs text-muted-foreground">{{ t("etcd.access.noRoles") }}</p>
</div>
</aside>
<main class="min-h-0 overflow-auto p-4">
<div v-if="!selectedRole" class="flex h-full min-h-48 items-center justify-center text-sm text-muted-foreground">{{ t("etcd.access.selectRole") }}</div>
<div v-else-if="detailLoading" class="flex h-32 items-center justify-center text-sm text-muted-foreground"><Loader2 class="mr-2 h-4 w-4 animate-spin" />{{ t("etcd.access.loadingRole") }}</div>
<template v-else-if="roleDetail">
<div class="mb-5 flex flex-wrap items-center gap-2 border-b pb-4">
<div class="mr-auto">
<h3 class="font-mono text-base font-semibold">{{ roleDetail.role }}</h3>
<p class="mt-1 text-xs text-muted-foreground">{{ t("etcd.access.rolePermissionHint") }}</p>
</div>
<Button size="sm" class="gap-1.5" :disabled="readOnly" @click="openGrantPermission"><Plus class="h-3.5 w-3.5" />{{ t("etcd.access.grantPermission") }}</Button>
<Button size="sm" variant="destructive" class="gap-1.5" :disabled="readOnly" @click="deleteRole(roleDetail.role)"><Trash2 class="h-3.5 w-3.5" />{{ t("etcd.access.deleteRole") }}</Button>
</div>
<div class="overflow-auto rounded border">
<table class="w-full min-w-[580px] text-left text-sm">
<thead class="bg-muted/60 text-xs text-muted-foreground">
<tr>
<th class="px-3 py-2 font-medium">{{ t("etcd.access.resource") }}</th>
<th class="px-3 py-2 font-medium">Key / Prefix</th>
<th class="px-3 py-2 font-medium">{{ t("etcd.access.permission") }}</th>
<th class="w-32 px-3 py-2"></th>
</tr>
</thead>
<tbody>
<tr v-for="permission in roleDetail.permissions" :key="`${permission.key.encoding}:${permission.key.data}:${permission.rangeEnd.data}`" class="border-t">
<td class="px-3 py-2">
<Badge variant="outline">{{ permissionResourceOf(permission) === "all" ? t("etcd.access.allKeys") : permissionResourceOf(permission) === "prefix" ? t("etcd.admin.prefix") : t("etcd.access.exactKey") }}</Badge>
</td>
<td class="max-w-md truncate px-3 py-2 font-mono text-xs">{{ permissionResourceOf(permission) === "all" ? t("etcd.access.allKeyspace") : displayValue(permission.key) }}</td>
<td class="px-3 py-2">
<Badge variant="secondary">{{ permissionLabel(permission.access) }}</Badge>
</td>
<td class="px-3 py-2">
<div class="flex justify-end gap-1">
<Button size="sm" variant="ghost" class="gap-1" :disabled="readOnly || busy" @click="openEditPermission(permission)"><Pencil class="h-3.5 w-3.5" />{{ t("etcd.access.edit") }}</Button
><Button size="sm" variant="ghost" class="text-destructive hover:text-destructive" :disabled="readOnly || busy" @click="revokePermission(permission)">{{ t("etcd.access.revoke") }}</Button>
</div>
</td>
</tr>
<tr v-if="roleDetail.permissions.length === 0">
<td colspan="4" class="px-3 py-8 text-center text-sm text-muted-foreground">{{ t("etcd.access.noPermissions") }}</td>
</tr>
</tbody>
</table>
</div>
</template>
</main>
</div>
<Dialog v-model:open="createUserOpen"
><DialogContent class="sm:max-w-lg"
><DialogHeader
><DialogTitle>{{ t("etcd.access.createEtcdUser") }}</DialogTitle></DialogHeader
>
<div class="space-y-5 py-2">
<div class="grid gap-3 sm:grid-cols-2">
<label class="space-y-1.5"
><span class="text-sm font-medium">{{ t("etcd.access.username") }}</span
><Input v-model="newUser" :placeholder="t('etcd.access.username')" autocomplete="off" /></label
><label class="space-y-1.5"
><span class="text-sm font-medium">{{ t("etcd.access.password") }}</span
><Input v-model="newUserPassword" type="password" :placeholder="t('etcd.access.password')" autocomplete="new-password"
/></label>
</div>
<div class="border-t pt-4">
<div class="flex items-baseline justify-between gap-3">
<div>
<h4 class="text-sm font-medium">
{{ t("etcd.access.initialRoles") }} <span class="text-xs font-normal text-muted-foreground">{{ t("etcd.access.optional") }}</span>
</h4>
<p class="mt-1 text-xs text-muted-foreground">{{ t("etcd.access.initialRolesHint") }}</p>
</div>
<Badge v-if="newUserRoles.length" variant="secondary">{{ t("etcd.access.selectedCount", { count: newUserRoles.length }) }}</Badge>
</div>
<div v-if="roles.length" class="mt-3 max-h-44 divide-y overflow-auto rounded border">
<label v-for="role in roles" :key="role" class="flex cursor-pointer items-center gap-3 px-3 py-2.5 hover:bg-muted/40"
><input v-model="newUserRoles" type="checkbox" :value="role" class="h-4 w-4 accent-primary" /><KeyRound class="h-4 w-4 text-muted-foreground" /><code class="text-sm">{{ role }}</code></label
>
</div>
<p v-else class="mt-3 rounded border border-dashed px-3 py-4 text-sm text-muted-foreground">{{ t("etcd.access.noRolesForNewUser") }}</p>
</div>
</div>
<DialogFooter
><Button variant="outline" @click="createUserOpen = false">{{ t("etcd.access.cancel") }}</Button
><Button :disabled="busy || readOnly || !newUser.trim() || !newUserPassword" @click="createUser">{{ initialUserRoleLabel }}</Button></DialogFooter
></DialogContent
></Dialog
>
<Dialog v-model:open="createRoleOpen"
><DialogContent class="sm:max-w-lg"
><DialogHeader
><DialogTitle>{{ t("etcd.access.createEtcdRole") }}</DialogTitle></DialogHeader
>
<div class="space-y-4 py-2">
<Input v-model="newRole" :placeholder="t('etcd.access.roleName')" autocomplete="off" />
<div class="space-y-3 rounded-md border bg-muted/20 p-3">
<div>
<div class="text-sm font-medium">
{{ t("etcd.access.initialPermission") }} <span class="text-xs font-normal text-muted-foreground">{{ t("etcd.access.optional") }}</span>
</div>
<p class="mt-1 text-xs text-muted-foreground">{{ t("etcd.access.initialPermissionHint") }}</p>
</div>
<Input v-if="newRolePermissionResource !== 'all'" v-model="newRolePermissionKey" :placeholder="t('etcd.access.keyOrPrefixPlaceholder')" autocomplete="off" />
<p v-else class="rounded border border-dashed bg-background px-3 py-2 text-xs text-muted-foreground">{{ t("etcd.access.allKeysHint") }}</p>
<div class="grid grid-cols-2 gap-3">
<select v-model="newRolePermissionResource" class="h-9 rounded-md border bg-background px-3 text-sm">
<option value="all">{{ t("etcd.access.allKeys") }}</option>
<option value="prefix">{{ t("etcd.admin.prefix") }}</option>
<option value="key">{{ t("etcd.access.exactKey") }}</option></select
><select v-model="newRolePermissionAccess" class="h-9 rounded-md border bg-background px-3 text-sm">
<option value="read">{{ t("etcd.access.read") }}</option>
<option value="write">{{ t("etcd.access.write") }}</option>
<option value="readwrite">{{ t("etcd.access.readWrite") }}</option>
</select>
</div>
</div>
</div>
<DialogFooter
><Button variant="outline" @click="createRoleOpen = false">{{ t("etcd.access.cancel") }}</Button
><Button :disabled="busy || readOnly || !newRole.trim()" @click="createRole">{{ hasInitialRolePermission ? t("etcd.access.createAndGrantPermission") : t("etcd.access.createRole") }}</Button></DialogFooter
></DialogContent
></Dialog
>
<Dialog v-model:open="passwordOpen"
><DialogContent class="sm:max-w-md"
><DialogHeader
><DialogTitle>{{ t("etcd.access.changePassword") }}</DialogTitle></DialogHeader
>
<div class="space-y-2 py-2">
<p class="text-sm text-muted-foreground">{{ t("etcd.access.passwordHint") }}</p>
<Input v-model="newPassword" type="password" :placeholder="t('etcd.access.newPassword')" autocomplete="new-password" />
</div>
<DialogFooter
><Button variant="outline" @click="passwordOpen = false">{{ t("etcd.access.cancel") }}</Button
><Button :disabled="busy || readOnly || !newPassword" @click="changePassword">{{ t("etcd.access.continue") }}</Button></DialogFooter
></DialogContent
></Dialog
>
<Dialog v-model:open="permissionOpen"
><DialogContent class="sm:max-w-lg"
><DialogHeader
><DialogTitle>{{ editingPermission ? t("etcd.access.editPermission") : t("etcd.access.grantPermission") }}</DialogTitle></DialogHeader
>
<div class="space-y-3 py-2">
<p v-if="editingPermission" class="text-xs leading-5 text-muted-foreground">{{ t("etcd.access.permissionUpdateHint") }}</p>
<div v-if="permissionError" class="rounded border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">{{ permissionError }}</div>
<Input v-if="permissionResource !== 'all'" v-model="permissionKey" :placeholder="t('etcd.access.keyOrPrefixPlaceholder')" autocomplete="off" />
<p v-else class="rounded border border-dashed bg-muted/20 px-3 py-2 text-xs text-muted-foreground">{{ t("etcd.access.allKeysHint") }}</p>
<div class="grid grid-cols-2 gap-3">
<select v-model="permissionResource" class="h-9 rounded-md border bg-background px-3 text-sm">
<option value="all">{{ t("etcd.access.allKeys") }}</option>
<option value="prefix">{{ t("etcd.admin.prefix") }}</option>
<option value="key">{{ t("etcd.access.exactKey") }}</option></select
><select v-model="permissionAccess" class="h-9 rounded-md border bg-background px-3 text-sm">
<option value="read">{{ t("etcd.access.read") }}</option>
<option value="write">{{ t("etcd.access.write") }}</option>
<option value="readwrite">{{ t("etcd.access.readWrite") }}</option>
</select>
</div>
</div>
<DialogFooter
><Button variant="outline" @click="permissionOpen = false">{{ t("etcd.access.cancel") }}</Button
><Button :disabled="busy || readOnly || !hasPermissionTarget" @click="savePermission">{{ editingPermission ? t("etcd.access.saveChanges") : t("etcd.access.continue") }}</Button></DialogFooter
></DialogContent
></Dialog
>
<Dialog :open="approvalOpen" @update:open="(open) => !open && closeApproval()"
><DialogContent class="sm:max-w-md"
><DialogHeader
><DialogTitle class="text-destructive">{{ t("etcd.access.dangerousTitle") }}</DialogTitle></DialogHeader
>
<div class="space-y-3 py-2">
<p class="text-sm text-muted-foreground">{{ t("etcd.access.dangerousHint") }}</p>
<code class="block rounded border bg-muted px-3 py-2 text-xs break-all">{{ approvalExpected }}</code
><Input v-model="approvalText" :placeholder="t('etcd.access.confirmationPlaceholder')" autocomplete="off" />
</div>
<DialogFooter
><Button variant="outline" :disabled="busy" @click="closeApproval">{{ t("etcd.access.cancel") }}</Button
><Button variant="destructive" :disabled="busy || approvalText !== approvalExpected" @click="confirmApproval">{{ t("etcd.access.confirmExecute") }}</Button></DialogFooter
></DialogContent
></Dialog
>
</div>
</template>
@@ -0,0 +1,915 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { Activity, HardDrive, History, KeyRound, Loader2, Pencil, Play, Plus, Search, Server, Square, Trash2, Wrench } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import * as api from "@/lib/backend/api";
import { releaseEtcdWatch, releaseEtcdWatchBestEffort, releaseEtcdWatchesBestEffort, replaceEtcdWatch } from "@/lib/etcd/watchLifecycle";
type EtcdAdminSection = "maintenance" | "watch" | "lease";
type WatchEventCategory = "create" | "update" | "delete";
interface WatchEventDisplay {
revision: string;
eventType: "put" | "delete";
category: WatchEventCategory;
key: string;
value?: api.KvValue | null;
previousValue?: api.KvValue | null;
}
interface WatchMonitor {
id: string;
key: string;
keyBytes: api.KvValue | null;
scope: "key" | "prefix";
startedRevision: string | null;
status: "running" | "stopped" | "error";
events: WatchEventDisplay[];
error?: string;
}
const props = withDefaults(
defineProps<{
connectionId: string;
status?: api.KvStatusResponse | null;
sections?: EtcdAdminSection[];
initialSection?: EtcdAdminSection;
watchPreset?: { key: string; keyBytes?: api.KvValue | null; scope: "key" | "prefix" } | null;
watchKeySuggestions?: Array<{ key: string; keyBytes: api.KvValue }>;
}>(),
{
status: null,
sections: () => ["maintenance", "watch", "lease"],
initialSection: "maintenance",
watchPreset: null,
watchKeySuggestions: () => [],
},
);
const emit = defineEmits<{
refresh: [];
watchCreated: [];
watchDialogDismissed: [];
}>();
const { t } = useI18n();
const active = ref<EtcdAdminSection>(props.initialSection);
const busy = ref(false);
const error = ref("");
const notice = ref("");
const revision = ref(String(props.status?.revision || ""));
const watchDialogOpen = ref(false);
const watchEditingId = ref<string | null>(null);
const watchFormKey = ref("");
const watchFormKeyBytes = ref<api.KvValue | null>(null);
const watchFormScope = ref<"key" | "prefix">("prefix");
const watchSuggestionOpen = ref(false);
const watchSuggestionIndex = ref(-1);
const watchMonitors = ref<WatchMonitor[]>([]);
const selectedWatchId = ref<string | null>(null);
const watchSearch = ref("");
const watchPolling = ref(false);
const watchEventFilters = ref<Record<WatchEventCategory, boolean>>({ create: true, update: true, delete: true });
const watchEventFilterOptions: Array<{ value: WatchEventCategory; label: string }> = [
{ value: "create", label: t("etcd.admin.create") },
{ value: "update", label: t("etcd.admin.update") },
{ value: "delete", label: t("etcd.admin.delete") },
];
const leaseGrantDialogOpen = ref(false);
const leaseGrantTtl = ref("60");
const leaseGrantId = ref("");
const leaseGrantBusy = ref(false);
const leases = ref<api.EtcdLeaseListResponse | null>(null);
const leaseContinuation = ref<string | null>(null);
const leasePreviousContinuations = ref<Array<string | null>>([]);
const selectedLease = ref<api.EtcdLeaseDetail | null>(null);
const leaseDetailLoading = ref(false);
const autoKeepalive = ref(false);
const leaseTtlSnapshots = ref<Record<string, { ttl: number; observedAt: number }>>({});
const leaseClock = ref(Date.now());
const maintenanceApprovalOpen = ref(false);
const maintenanceApprovalLoading = ref(false);
const maintenanceApprovalTitle = ref("");
const maintenanceApprovalDetails = ref("");
const maintenanceApprovalExpected = ref("");
const maintenanceApprovalText = ref("");
let watchPoller: ReturnType<typeof setInterval> | null = null;
let leaseKeepaliveTimer: ReturnType<typeof setTimeout> | null = null;
let leaseCountdownTimer: ReturnType<typeof setInterval> | null = setInterval(() => {
leaseClock.value = Date.now();
}, 1000);
let pendingMaintenanceApproval: (() => Promise<void>) | null = null;
let leaseGrantRequest = 0;
watch(
() => props.initialSection,
(section) => {
active.value = section;
},
);
watch(
() => props.watchPreset,
(preset) => {
if (!preset) return;
openWatchDialog(preset);
},
{ immediate: true },
);
watch(active, (section, previousSection) => {
if (previousSection === "lease" && section !== "lease") stopLeaseKeepalive();
});
watch(autoKeepalive, (enabled) => {
if (enabled) scheduleLeaseKeepalive();
else stopLeaseKeepalive();
});
const endpoints = computed(() => {
const members = props.status?.members.filter((member) => member.reachable) ?? [];
const leader = props.status?.leaderId;
return [...members.filter((member) => member.memberId !== leader), ...members.filter((member) => member.memberId === leader)].map((member) => member.endpoint);
});
const currentRevision = computed(() => (props.status?.revision == null ? null : String(props.status.revision)));
const reachableMemberCount = computed(() => props.status?.members.filter((member) => member.reachable).length ?? 0);
const memberCount = computed(() => props.status?.members.length ?? 0);
const leaderEndpoint = computed(() => {
const leaderId = props.status?.leaderId;
return props.status?.members.find((member) => member.memberId != null && member.memberId === leaderId)?.endpoint ?? null;
});
const filteredWatchMonitors = computed(() => {
const query = watchSearch.value.trim().toLocaleLowerCase();
return query ? watchMonitors.value.filter((monitor) => monitor.key.toLocaleLowerCase().includes(query)) : watchMonitors.value;
});
const selectedWatchMonitor = computed(() => watchMonitors.value.find((monitor) => monitor.id === selectedWatchId.value) ?? null);
const visibleWatchEvents = computed(() => (selectedWatchMonitor.value?.events ?? []).filter((event) => watchEventFilters.value[event.category]));
const runningWatchCount = computed(() => watchMonitors.value.filter((monitor) => monitor.status === "running").length);
const filteredWatchKeySuggestions = computed(() => {
const query = watchFormKey.value.trim();
if (!query) return [];
const seen = new Set<string>();
const matches: Array<{ key: string; keyBytes: api.KvValue }> = [];
for (const suggestion of props.watchKeySuggestions) {
const identity = `${suggestion.keyBytes.encoding}:${suggestion.keyBytes.data}`;
if (suggestion.key === query || !suggestion.key.startsWith(query) || seen.has(identity)) continue;
seen.add(identity);
matches.push(suggestion);
if (matches.length === 8) break;
}
return matches;
});
const showWatchKeySuggestions = computed(() => watchSuggestionOpen.value && filteredWatchKeySuggestions.value.length > 0);
function reset(message = "") {
error.value = "";
notice.value = message;
}
async function dangerousApproval(action: string, params: Record<string, unknown>) {
const preflight = await api.etcdPreflight(props.connectionId, action, params);
const entered = window.prompt(t("etcd.admin.confirmationPrompt", { confirmationText: preflight.confirmationText }), "");
if (entered !== preflight.confirmationText) return null;
return { preflightToken: preflight.token, confirmationText: entered };
}
async function run(action: () => Promise<void>) {
busy.value = true;
reset();
try {
await action();
} catch (caught) {
error.value = caught instanceof Error ? caught.message : String(caught);
} finally {
busy.value = false;
}
}
async function requestMaintenanceApproval(action: "compact" | "defrag", params: Record<string, unknown>, title: string, details: string, execute: (approval: api.EtcdDangerousApproval) => Promise<void>) {
maintenanceApprovalLoading.value = true;
reset();
try {
const preflight = await api.etcdPreflight(props.connectionId, action, params);
maintenanceApprovalTitle.value = title;
maintenanceApprovalDetails.value = details;
maintenanceApprovalExpected.value = preflight.confirmationText;
maintenanceApprovalText.value = "";
pendingMaintenanceApproval = () => execute({ preflightToken: preflight.token, confirmationText: preflight.confirmationText });
maintenanceApprovalOpen.value = true;
} catch (caught) {
error.value = caught instanceof Error ? caught.message : String(caught);
} finally {
maintenanceApprovalLoading.value = false;
}
}
function closeMaintenanceApproval() {
if (maintenanceApprovalLoading.value) return;
maintenanceApprovalOpen.value = false;
maintenanceApprovalText.value = "";
pendingMaintenanceApproval = null;
}
async function confirmMaintenanceApproval() {
if (maintenanceApprovalText.value !== maintenanceApprovalExpected.value || !pendingMaintenanceApproval) return;
const execute = pendingMaintenanceApproval;
pendingMaintenanceApproval = null;
maintenanceApprovalOpen.value = false;
maintenanceApprovalText.value = "";
await run(execute);
}
function compact() {
if (!/^\d+$/.test(revision.value)) {
error.value = t("etcd.admin.compactRequired");
return;
}
const targetRevision = revision.value;
void requestMaintenanceApproval("compact", { revision: targetRevision }, t("etcd.admin.compactTitle"), t("etcd.admin.compactDescription"), async (approval) => {
await api.etcdCompact(props.connectionId, targetRevision, approval);
emit("refresh");
reset(t("etcd.admin.compactDone"));
});
}
function defrag() {
if (!endpoints.value.length) {
error.value = t("etcd.admin.noReachableMembers");
return;
}
const targetEndpoints = [...endpoints.value];
void requestMaintenanceApproval("defrag", { endpoints: targetEndpoints }, t("etcd.admin.defragTitle"), t("etcd.admin.defragDescription"), async (approval) => {
const result = await api.etcdDefrag(props.connectionId, targetEndpoints, approval);
emit("refresh");
const succeeded = result.members.filter((item) => item.status === "succeeded").length;
const failed = result.members.filter((item) => item.status === "failed").length;
const notExecuted = result.members.filter((item) => item.status === "not_executed").length;
reset(failed ? t("etcd.admin.defragStopped", { succeeded, failed, notExecuted }) : t("etcd.admin.defragCompleted", { succeeded, total: result.members.length }));
});
}
function openWatchDialog(preset?: { key: string; keyBytes?: api.KvValue | null; scope: "key" | "prefix" }) {
watchEditingId.value = null;
watchFormKey.value = preset?.key ?? "";
watchFormKeyBytes.value = preset?.keyBytes ?? null;
watchFormScope.value = preset?.scope ?? "prefix";
closeWatchKeySuggestions();
watchDialogOpen.value = true;
}
function closeWatchDialog() {
watchDialogOpen.value = false;
closeWatchKeySuggestions();
emit("watchDialogDismissed");
}
function updateWatchDialog(open: boolean) {
if (open) {
watchDialogOpen.value = true;
return;
}
closeWatchDialog();
}
function editWatchMonitor(monitor: WatchMonitor) {
watchEditingId.value = monitor.id;
watchFormKey.value = monitor.key;
watchFormKeyBytes.value = monitor.keyBytes;
watchFormScope.value = monitor.scope;
closeWatchKeySuggestions();
watchDialogOpen.value = true;
}
function closeWatchKeySuggestions() {
watchSuggestionOpen.value = false;
watchSuggestionIndex.value = -1;
}
function onWatchKeyInput(value: string | number) {
const key = String(value);
watchFormKeyBytes.value = null;
watchSuggestionOpen.value = Boolean(key.trim());
watchSuggestionIndex.value = -1;
}
function acceptWatchKeySuggestion(index: number) {
const suggestion = filteredWatchKeySuggestions.value[index];
if (!suggestion) return;
watchFormKey.value = suggestion.key;
watchFormKeyBytes.value = suggestion.keyBytes;
closeWatchKeySuggestions();
}
function moveWatchKeySuggestion(delta: number) {
if (!filteredWatchKeySuggestions.value.length) return;
watchSuggestionOpen.value = true;
watchSuggestionIndex.value = (watchSuggestionIndex.value + delta + filteredWatchKeySuggestions.value.length) % filteredWatchKeySuggestions.value.length;
}
function onWatchKeyKeydown(event: KeyboardEvent) {
if (event.isComposing) return;
if (event.key === "Escape") {
closeWatchKeySuggestions();
return;
}
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
if (!filteredWatchKeySuggestions.value.length) return;
event.preventDefault();
moveWatchKeySuggestion(event.key === "ArrowDown" ? 1 : -1);
return;
}
if (event.key === "Enter" && showWatchKeySuggestions.value && watchSuggestionIndex.value >= 0) {
event.preventDefault();
acceptWatchKeySuggestion(watchSuggestionIndex.value);
}
}
function watchEventCategory(event: { eventType: "put" | "delete"; previousValue?: api.KvValue | null }): WatchEventCategory {
if (event.eventType === "delete") return "delete";
return event.previousValue ? "update" : "create";
}
function watchEventCategoryLabel(category: WatchEventCategory): string {
return category === "create" ? t("etcd.admin.create") : category === "update" ? t("etcd.admin.update") : t("etcd.admin.delete");
}
function startWatchPoller() {
if (watchPoller || runningWatchCount.value === 0) return;
watchPoller = setInterval(() => void pollWatchMonitors(), 500);
}
function stopWatchPollerIfIdle() {
if (!watchPoller || runningWatchCount.value > 0) return;
clearInterval(watchPoller);
watchPoller = null;
}
async function startWatchMonitor(monitor: WatchMonitor) {
const result = await api.etcdWatchStart(props.connectionId, {
key: monitor.key,
keyBytes: monitor.keyBytes,
scope: monitor.scope,
includePrevKv: true,
});
monitor.id = result.watchId;
monitor.startedRevision = String(result.startedRevision);
monitor.status = "running";
monitor.error = undefined;
monitor.events = [];
selectedWatchId.value = monitor.id;
startWatchPoller();
}
async function saveWatchMonitor() {
if (!watchFormKey.value) return;
const editing = watchEditingId.value ? (watchMonitors.value.find((monitor) => monitor.id === watchEditingId.value) ?? null) : null;
await run(async () => {
if (editing) {
const shouldRestart = editing.status === "running";
if (editing.id) await stopWatchMonitor(editing, false);
editing.key = watchFormKey.value;
editing.keyBytes = watchFormKeyBytes.value;
editing.scope = watchFormScope.value;
editing.events = [];
editing.error = undefined;
if (!shouldRestart) editing.status = "stopped";
if (shouldRestart) await startWatchMonitor(editing);
selectedWatchId.value = editing.id;
watchDialogOpen.value = false;
reset(shouldRestart ? t("etcd.admin.saveWatch") : t("etcd.admin.saveWatch"));
return;
}
if (runningWatchCount.value >= 4) throw new Error(t("etcd.admin.watchSessionHint"));
const monitor: WatchMonitor = {
id: "",
key: watchFormKey.value,
keyBytes: watchFormKeyBytes.value,
scope: watchFormScope.value,
startedRevision: null,
status: "stopped",
events: [],
};
await startWatchMonitor(monitor);
watchMonitors.value.unshift(monitor);
startWatchPoller();
watchDialogOpen.value = false;
reset(t("etcd.admin.running"));
emit("watchCreated");
});
}
async function pollWatchMonitors() {
if (watchPolling.value) return;
const running = watchMonitors.value.filter((monitor) => monitor.status === "running");
if (!running.length) {
stopWatchPollerIfIdle();
return;
}
watchPolling.value = true;
try {
for (const monitor of running) {
try {
const response = await api.etcdWatchPoll(props.connectionId, monitor.id);
for (const batch of response.batches) {
for (const event of batch.events) {
monitor.events.unshift({
revision: String(event.revision),
eventType: event.eventType,
category: watchEventCategory(event),
key: event.key,
value: event.value,
previousValue: event.previousValue,
});
}
}
monitor.events.splice(500);
if (response.terminal) {
// A terminal poll removes the watch from the Agent. This extra stop is
// only a best-effort compatibility cleanup for older Agents.
await releaseEtcdWatchBestEffort(props.connectionId, monitor.id, api.etcdWatchStop);
monitor.status = "error";
monitor.error = response.terminal.message || `Watch ${response.terminal.reason}`;
}
} catch (caught) {
let message = caught instanceof Error ? caught.message : String(caught);
try {
await releaseEtcdWatch(props.connectionId, monitor.id, api.etcdWatchStop);
} catch (stopError) {
const stopMessage = stopError instanceof Error ? stopError.message : String(stopError);
message = `${message}; failed to stop watch: ${stopMessage}`;
}
monitor.status = "error";
monitor.error = message;
}
}
} catch (caught) {
error.value = caught instanceof Error ? caught.message : String(caught);
} finally {
watchPolling.value = false;
stopWatchPollerIfIdle();
}
}
async function stopWatchMonitor(monitor: WatchMonitor, notify = true) {
await releaseEtcdWatch(props.connectionId, monitor.id, api.etcdWatchStop);
monitor.status = "stopped";
monitor.error = undefined;
stopWatchPollerIfIdle();
if (notify) reset(t("etcd.admin.stopped"));
}
function requestStopWatchMonitor(monitor: WatchMonitor) {
void run(() => stopWatchMonitor(monitor));
}
async function resumeWatchMonitor(monitor: WatchMonitor) {
if (runningWatchCount.value >= 4) {
error.value = t("etcd.admin.watchSessionHint");
return;
}
await run(async () => {
await replaceEtcdWatch(props.connectionId, monitor.id, api.etcdWatchStop, () => startWatchMonitor(monitor));
reset(t("etcd.admin.running"));
});
}
async function deleteWatchMonitor(monitor: WatchMonitor) {
await run(async () => {
await stopWatchMonitor(monitor, false);
const index = watchMonitors.value.indexOf(monitor);
if (index >= 0) watchMonitors.value.splice(index, 1);
if (selectedWatchId.value === monitor.id) selectedWatchId.value = watchMonitors.value[0]?.id ?? null;
reset(t("etcd.admin.deleteWatch"));
});
}
async function stopAllWatchMonitors() {
if (watchPoller) {
clearInterval(watchPoller);
watchPoller = null;
}
await releaseEtcdWatchesBestEffort(
props.connectionId,
watchMonitors.value.map((monitor) => monitor.id),
api.etcdWatchStop,
);
}
function rememberLeaseTtl(id: string, ttl: number) {
leaseTtlSnapshots.value = { ...leaseTtlSnapshots.value, [id]: { ttl, observedAt: Date.now() } };
}
function displayedLeaseTtl(id: string, fallbackTtl: number): number {
const snapshot = leaseTtlSnapshots.value[id];
if (!snapshot) return fallbackTtl;
const elapsedSeconds = Math.floor((leaseClock.value - snapshot.observedAt) / 1000);
return Math.max(0, snapshot.ttl - elapsedSeconds);
}
function applyLeases(response: api.EtcdLeaseListResponse) {
leases.value = response;
for (const lease of response.leases) rememberLeaseTtl(String(lease.id), lease.ttl);
}
async function fetchLeases(continuation = leaseContinuation.value) {
applyLeases(await api.etcdLeaseList(props.connectionId, 100, continuation));
}
async function loadLeases() {
await run(fetchLeases);
}
async function nextLeasePage() {
const next = leases.value?.nextContinuation;
if (!next) return;
const previous = leaseContinuation.value;
await run(async () => {
const response = await api.etcdLeaseList(props.connectionId, 100, next);
leasePreviousContinuations.value.push(previous);
leaseContinuation.value = next;
applyLeases(response);
});
}
async function previousLeasePage() {
if (!leasePreviousContinuations.value.length) return;
const previous = leasePreviousContinuations.value[leasePreviousContinuations.value.length - 1] ?? null;
await run(async () => {
const response = await api.etcdLeaseList(props.connectionId, 100, previous);
leasePreviousContinuations.value.pop();
leaseContinuation.value = previous;
applyLeases(response);
});
}
async function openLease(id: string) {
leaseDetailLoading.value = true;
selectedLease.value = null;
try {
selectedLease.value = await api.etcdLeaseCall<api.EtcdLeaseDetail>(props.connectionId, "get", { id, includeKeys: true });
rememberLeaseTtl(selectedLease.value.id, selectedLease.value.ttl);
if (autoKeepalive.value) scheduleLeaseKeepalive();
} catch (caught) {
error.value = caught instanceof Error ? caught.message : String(caught);
} finally {
leaseDetailLoading.value = false;
}
}
function stopLeaseKeepalive() {
if (leaseKeepaliveTimer) {
clearTimeout(leaseKeepaliveTimer);
leaseKeepaliveTimer = null;
}
}
function scheduleLeaseKeepalive() {
stopLeaseKeepalive();
if (!autoKeepalive.value || !selectedLease.value || selectedLease.value.ttl <= 0) return;
leaseKeepaliveTimer = setTimeout(() => void renewLease(selectedLease.value!.id), Math.max(1000, Math.floor((selectedLease.value.ttl * 1000) / 3)));
}
async function renewLease(id: string) {
await run(async () => {
const result = await api.etcdLeaseCall<{ id: string; ttl: number }>(props.connectionId, "keepalive", { id });
if (selectedLease.value?.id === id) {
selectedLease.value = { ...selectedLease.value, ttl: result.ttl };
rememberLeaseTtl(id, result.ttl);
scheduleLeaseKeepalive();
}
await loadLeases();
reset(t("etcd.admin.leaseRenewed", { id }));
});
}
function openLeaseGrantDialog() {
leaseGrantTtl.value = "60";
leaseGrantId.value = "";
leaseGrantDialogOpen.value = true;
}
function closeLeaseGrantDialog() {
// The RPC cannot be aborted through Tauri today. Ignore its late response so
// closing the dialog immediately restores control to the user.
const wasPending = leaseGrantBusy.value;
leaseGrantRequest++;
leaseGrantBusy.value = false;
leaseGrantDialogOpen.value = false;
if (wasPending) reset(t("etcd.admin.leaseGrantCancelled"));
}
function updateLeaseGrantDialog(open: boolean) {
if (open) {
leaseGrantDialogOpen.value = true;
} else {
closeLeaseGrantDialog();
}
}
async function grantLease() {
const ttl = leaseGrantTtl.value.trim();
const id = leaseGrantId.value.trim();
if (!/^\d+$/.test(ttl) || Number(ttl) <= 0) {
error.value = t("etcd.admin.ttlHint");
return;
}
if (id && !/^\d+$/.test(id)) {
error.value = t("etcd.admin.customLeaseHint");
return;
}
const request = ++leaseGrantRequest;
leaseGrantBusy.value = true;
reset();
try {
const result = await api.etcdLeaseCall<{ id: string; ttl?: number }>(props.connectionId, "grant", { ttl, id: id || undefined });
if (request !== leaseGrantRequest) return;
// The grant has succeeded. Close first so list/detail follow-up failures
// do not leave a modal that appears to be frozen.
leaseGrantDialogOpen.value = false;
await fetchLeases();
if (request !== leaseGrantRequest) return;
await openLease(result.id);
if (request !== leaseGrantRequest) return;
reset(t("etcd.admin.leaseCreated", { id: result.id }));
} catch (caught) {
if (request === leaseGrantRequest) error.value = caught instanceof Error ? caught.message : String(caught);
} finally {
if (request === leaseGrantRequest) leaseGrantBusy.value = false;
}
}
async function revokeLease(id: string) {
await run(async () => {
const params = { id };
const approval = await dangerousApproval("lease_revoke", params);
if (!approval) return;
await api.etcdLeaseCall(props.connectionId, "revoke", params, approval);
if (selectedLease.value?.id === id) {
selectedLease.value = null;
autoKeepalive.value = false;
stopLeaseKeepalive();
}
await loadLeases();
});
}
onBeforeUnmount(() => {
void stopAllWatchMonitors();
stopLeaseKeepalive();
if (leaseCountdownTimer) clearInterval(leaseCountdownTimer);
leaseCountdownTimer = null;
});
</script>
<template>
<section class="overflow-hidden rounded-lg border">
<div v-if="sections.length > 1" class="flex flex-wrap items-center gap-1 border-b p-2">
<Button v-if="sections.includes('maintenance')" size="sm" :variant="active === 'maintenance' ? 'secondary' : 'ghost'" @click="active = 'maintenance'"><Wrench class="mr-1 h-3.5 w-3.5" />{{ t("etcd.admin.maintenance") }}</Button>
<Button v-if="sections.includes('watch')" size="sm" :variant="active === 'watch' ? 'secondary' : 'ghost'" @click="active = 'watch'"><Activity class="mr-1 h-3.5 w-3.5" />{{ t("etcd.admin.watch") }}</Button>
<Button
v-if="sections.includes('lease')"
size="sm"
:variant="active === 'lease' ? 'secondary' : 'ghost'"
@click="
active = 'lease';
void loadLeases();
"
><KeyRound class="mr-1 h-3.5 w-3.5" />{{ t("etcd.admin.lease") }}</Button
>
</div>
<div :class="active === 'maintenance' ? 'text-sm' : 'space-y-3 p-4 text-sm'">
<div v-if="error" :class="active === 'maintenance' ? 'border-b border-destructive/30 bg-destructive/5 px-5 py-3 text-destructive' : 'rounded border border-destructive/30 bg-destructive/5 p-2 text-destructive'">{{ error }}</div>
<div v-if="notice" :class="active === 'maintenance' ? 'border-b bg-muted/40 px-5 py-3' : active === 'watch' ? 'border-b pb-2 text-xs text-muted-foreground' : 'rounded border bg-muted/40 p-2'">{{ notice }}</div>
<template v-if="active === 'maintenance'">
<div class="flex flex-wrap items-start justify-between gap-4 border-b px-5 py-4">
<div class="min-w-0">
<h2 class="text-base font-semibold">{{ t("etcd.admin.maintenanceTitle") }}</h2>
<p class="mt-1 max-w-2xl text-xs leading-5 text-muted-foreground">{{ t("etcd.admin.maintenanceDescription") }}</p>
</div>
<div class="flex flex-wrap gap-2 text-xs text-muted-foreground">
<span class="rounded-md border bg-muted/30 px-2.5 py-1.5">{{ t("etcd.admin.currentRevision", { revision: currentRevision ?? "-" }) }}</span>
<span class="rounded-md border bg-muted/30 px-2.5 py-1.5">{{ t("etcd.admin.reachableMembers", { reachable: reachableMemberCount, total: memberCount }) }}</span>
</div>
</div>
<div class="grid divide-y lg:grid-cols-2 lg:divide-x lg:divide-y-0">
<section class="space-y-4 px-5 py-5">
<div class="flex items-start gap-3">
<History class="mt-0.5 h-5 w-5 shrink-0 text-sky-600" />
<div>
<h3 class="font-medium">{{ t("etcd.admin.compactTitle") }}</h3>
<p class="mt-1 text-xs leading-5 text-muted-foreground">{{ t("etcd.admin.compactDescription") }}</p>
</div>
</div>
<div class="border-l-2 border-amber-500/70 pl-3 text-xs leading-5 text-muted-foreground">{{ t("etcd.admin.compactDiskHint") }}</div>
<label class="block space-y-1.5">
<span class="text-xs font-medium">{{ t("etcd.admin.compactRevision") }}</span>
<Input v-model="revision" inputmode="numeric" :placeholder="t('etcd.admin.compactPlaceholder', { revision: currentRevision ?? '' })" />
<span class="block text-xs leading-5 text-muted-foreground">{{ t("etcd.admin.compactInputHint") }}</span>
</label>
<Button variant="destructive" :disabled="busy || maintenanceApprovalLoading || !/^\d+$/.test(revision)" @click="compact">{{ t("etcd.admin.compactAction") }}</Button>
</section>
<section class="space-y-4 px-5 py-5">
<div class="flex items-start gap-3">
<HardDrive class="mt-0.5 h-5 w-5 shrink-0 text-emerald-600" />
<div>
<h3 class="font-medium">{{ t("etcd.admin.defragTitle") }}</h3>
<p class="mt-1 text-xs leading-5 text-muted-foreground">{{ t("etcd.admin.defragDescription") }}</p>
</div>
</div>
<div class="border-l-2 border-amber-500/70 pl-3 text-xs leading-5 text-muted-foreground">{{ t("etcd.admin.defragWarning") }}</div>
<div class="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
<span class="inline-flex items-center gap-1.5 rounded-md border bg-muted/30 px-2.5 py-1.5"><Server class="h-3.5 w-3.5" />{{ t("etcd.admin.defragReachableMembers", { count: endpoints.length }) }}</span>
<span v-if="leaderEndpoint" class="max-w-full truncate rounded-md border bg-muted/30 px-2.5 py-1.5" :title="leaderEndpoint">{{ t("etcd.admin.leaderLast", { endpoint: leaderEndpoint }) }}</span>
</div>
<Button variant="outline" :disabled="busy || maintenanceApprovalLoading || !endpoints.length" @click="defrag">{{ t("etcd.admin.defragAction", { count: endpoints.length }) }}</Button>
</section>
</div>
</template>
<template v-else-if="active === 'watch'">
<div class="flex flex-wrap items-center justify-between gap-3 border-b pb-3">
<div class="min-w-0">
<div class="flex items-center gap-2">
<h2 class="text-base font-semibold">{{ t("etcd.admin.watch") }}</h2>
<span class="text-xs text-muted-foreground">{{ t("etcd.admin.watchCount", { count: watchMonitors.length }) }}</span
><span v-if="runningWatchCount" class="rounded-full border border-emerald-500/50 px-2 py-0.5 text-xs text-emerald-700 dark:text-emerald-300">{{ t("etcd.admin.runningWatchCount", { count: runningWatchCount }) }}</span>
</div>
<p class="mt-1 text-xs text-muted-foreground">{{ t("etcd.admin.watchSessionHint") }}</p>
</div>
<div class="flex w-full items-center gap-2 sm:w-auto">
<div class="relative min-w-0 flex-1 sm:w-56 sm:flex-none"><Search class="pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" /><Input v-model="watchSearch" class="h-9 pl-8 text-sm" :placeholder="t('etcd.admin.watchSearch')" /></div>
<Button size="sm" class="h-9 shrink-0 gap-1.5" @click="openWatchDialog()"><Plus class="h-3.5 w-3.5" />{{ t("etcd.admin.newWatch") }}</Button>
</div>
</div>
<div class="grid min-h-[22rem] gap-5 xl:grid-cols-[minmax(22rem,0.9fr)_minmax(0,1.1fr)]">
<section class="min-w-0 space-y-2">
<div class="flex items-center justify-between text-xs text-muted-foreground">
<span>{{ t("etcd.admin.watchList") }}</span
><span>{{ t("etcd.admin.itemCount", { count: filteredWatchMonitors.length }) }}</span>
</div>
<div class="overflow-hidden rounded-md border">
<div class="grid grid-cols-[minmax(9rem,1fr)_5rem_6.5rem_auto] gap-2 border-b bg-muted/30 px-3 py-2 text-xs font-medium text-muted-foreground">
<span>Key</span><span>{{ t("etcd.admin.scope") }}</span
><span>{{ t("etcd.admin.status") }}</span
><span class="text-right">{{ t("etcd.admin.actions") }}</span>
</div>
<div v-for="monitor in filteredWatchMonitors" :key="monitor.id" class="grid grid-cols-[minmax(9rem,1fr)_5rem_6.5rem_auto] items-center gap-2 border-b px-3 py-2.5 text-sm last:border-b-0" :class="selectedWatchId === monitor.id ? 'bg-accent/60' : ''">
<button type="button" class="min-w-0 text-left" @click="selectedWatchId = monitor.id">
<code class="block truncate" :title="monitor.key">{{ monitor.key }}</code
><span v-if="monitor.error" class="mt-1 block truncate text-xs text-destructive" :title="monitor.error">{{ monitor.error }}</span>
</button>
<span class="text-xs text-muted-foreground">{{ monitor.scope === "key" ? t("etcd.admin.exact") : t("etcd.admin.prefix") }}</span>
<span :class="monitor.status === 'running' ? 'border-emerald-500/50 text-emerald-700 dark:text-emerald-300' : monitor.status === 'error' ? 'border-destructive/50 text-destructive' : 'text-muted-foreground'" class="inline-flex w-fit rounded-full border px-2 py-0.5 text-xs">{{
monitor.status === "running" ? t("etcd.admin.running") : monitor.status === "error" ? t("etcd.admin.error") : t("etcd.admin.stopped")
}}</span>
<div class="flex justify-end gap-0.5">
<Button size="sm" variant="ghost" class="h-7 w-7 p-0" :title="t('etcd.admin.editWatchTitle')" @click="editWatchMonitor(monitor)"><Pencil class="h-3.5 w-3.5" /></Button
><Button v-if="monitor.status === 'running'" size="sm" variant="ghost" class="h-7 w-7 p-0 text-amber-700 hover:text-amber-700 dark:text-amber-300" :title="t('etcd.admin.stopWatch')" @click="requestStopWatchMonitor(monitor)"><Square class="h-3.5 w-3.5" /></Button
><Button v-else size="sm" variant="ghost" class="h-7 w-7 p-0 text-emerald-700 hover:text-emerald-700 dark:text-emerald-300" :title="t('etcd.admin.startWatch')" @click="void resumeWatchMonitor(monitor)"><Play class="h-3.5 w-3.5" /></Button
><Button size="sm" variant="ghost" class="h-7 w-7 p-0 text-destructive hover:text-destructive" :title="t('etcd.admin.deleteWatch')" @click="void deleteWatchMonitor(monitor)"><Trash2 class="h-3.5 w-3.5" /></Button>
</div>
</div>
<div v-if="filteredWatchMonitors.length === 0" class="px-3 py-12 text-center text-sm text-muted-foreground">{{ watchMonitors.length ? t("etcd.admin.noMatchingWatches") : t("etcd.admin.noWatches") }}</div>
</div>
</section>
<section v-if="selectedWatchMonitor" class="min-w-0 space-y-3 border-t pt-4 xl:border-l xl:border-t-0 xl:pl-5 xl:pt-0">
<div class="flex flex-wrap items-center gap-2">
<div class="min-w-0 flex-1">
<h3 class="text-sm font-semibold">{{ t("etcd.admin.eventStream") }}</h3>
<code class="mt-1 block truncate text-xs text-muted-foreground" :title="selectedWatchMonitor.key">{{ selectedWatchMonitor.key }}</code>
</div>
<span class="text-xs text-muted-foreground">{{ t("etcd.admin.eventCount", { count: selectedWatchMonitor.events.length }) }}</span>
</div>
<div class="flex flex-wrap items-center gap-x-4 gap-y-2">
<span class="mr-1 text-xs font-medium text-muted-foreground">{{ t("etcd.admin.filter") }}</span
><label v-for="item in watchEventFilterOptions" :key="item.value" class="inline-flex cursor-pointer items-center gap-1.5 text-xs text-muted-foreground"><input v-model="watchEventFilters[item.value]" type="checkbox" class="h-3.5 w-3.5 rounded border-input" />{{ item.label }}</label>
</div>
<div class="overflow-hidden rounded-md border">
<div class="grid grid-cols-[7rem_5.5rem_minmax(0,1fr)] gap-3 border-b bg-muted/30 px-3 py-2 text-xs font-medium text-muted-foreground">
<span>Revision</span><span>{{ t("etcd.admin.event") }}</span
><span>Key</span>
</div>
<div class="max-h-72 overflow-auto">
<div v-for="event in visibleWatchEvents" :key="`${event.revision}:${event.key}:${event.eventType}`" class="grid grid-cols-[7rem_5.5rem_minmax(0,1fr)] gap-3 border-b px-3 py-2 text-xs last:border-b-0">
<span class="font-mono text-muted-foreground">{{ event.revision }}</span
><span :class="event.category === 'delete' ? 'text-destructive' : event.category === 'update' ? 'text-amber-700 dark:text-amber-300' : 'text-emerald-700 dark:text-emerald-300'">{{ watchEventCategoryLabel(event.category) }}</span
><code class="truncate" :title="event.key">{{ event.key }}</code>
</div>
<div v-if="!visibleWatchEvents.length" class="p-8 text-center text-xs text-muted-foreground">
{{ selectedWatchMonitor.status === "running" ? (selectedWatchMonitor.events.length ? t("etcd.admin.noFilteredEvents") : t("etcd.admin.waitingEvents")) : t("etcd.admin.watchNotRunning") }}
</div>
</div>
</div>
</section>
<div v-else class="flex items-center justify-center border-t pt-4 text-sm text-muted-foreground xl:border-l xl:border-t-0 xl:pl-5 xl:pt-0">{{ t("etcd.admin.selectWatch") }}</div>
</div>
</template>
<template v-else-if="active === 'lease'">
<div class="flex flex-wrap items-center justify-between gap-3 border-b pb-3">
<div>
<h2 class="text-base font-semibold">{{ t("etcd.admin.lease") }}</h2>
<p class="mt-1 text-xs text-muted-foreground">{{ t("etcd.admin.leaseDescription") }}</p>
</div>
<div class="flex gap-2">
<Button size="sm" @click="openLeaseGrantDialog">{{ t("etcd.admin.grantLease") }}</Button
><Button size="sm" variant="outline" :disabled="busy" @click="loadLeases">{{ t("etcd.admin.refresh") }}</Button>
</div>
</div>
<div class="grid gap-3 lg:grid-cols-[minmax(18rem,0.85fr)_minmax(0,1.15fr)]">
<div class="space-y-2">
<div v-for="lease in leases?.leases || []" :key="lease.id" class="flex w-full cursor-pointer items-center gap-3 rounded border px-3 py-2 text-left hover:bg-accent" :class="selectedLease?.id === lease.id ? 'border-primary bg-accent' : ''" @click="openLease(lease.id)">
<code class="min-w-0 flex-1 truncate">{{ lease.id }}</code
><span class="shrink-0 text-xs text-muted-foreground">TTL {{ displayedLeaseTtl(lease.id, lease.ttl) }}s</span><Button size="sm" variant="ghost" class="shrink-0" :disabled="busy" @click.stop="renewLease(lease.id)">{{ t("etcd.admin.renew") }}</Button
><Button size="sm" variant="ghost" class="shrink-0 text-destructive hover:text-destructive" :disabled="busy" @click.stop="revokeLease(lease.id)">{{ t("etcd.admin.revoke") }}</Button>
</div>
<div v-if="!leases?.leases.length" class="rounded border border-dashed px-3 py-6 text-center text-xs text-muted-foreground">{{ t("etcd.admin.noKnownLeases") }}</div>
<div v-if="leases && (leasePreviousContinuations.length || leases.nextContinuation)" class="flex items-center justify-between gap-2 pt-1">
<Button size="sm" variant="outline" :disabled="busy || !leasePreviousContinuations.length" @click="previousLeasePage">{{ t("etcd.admin.previousPage") }}</Button>
<span class="text-xs text-muted-foreground">{{ t("etcd.admin.leasePageSize", { count: 100 }) }}</span>
<Button size="sm" variant="outline" :disabled="busy || !leases.nextContinuation" @click="nextLeasePage">{{ t("etcd.admin.nextPage") }}</Button>
</div>
</div>
<div class="rounded border p-3">
<div v-if="leaseDetailLoading" class="flex h-32 items-center justify-center text-xs text-muted-foreground">{{ t("etcd.admin.loadingLease") }}</div>
<div v-else-if="selectedLease" class="space-y-3">
<div class="flex flex-wrap items-center gap-2">
<code class="mr-auto text-sm">{{ selectedLease.id }}</code
><span class="text-xs text-muted-foreground">TTL {{ displayedLeaseTtl(selectedLease.id, selectedLease.ttl) }}s / {{ t("etcd.admin.grantedTtl", { ttl: selectedLease.grantedTtl }) }}</span>
</div>
<label class="flex items-center gap-2 rounded border bg-muted/20 px-3 py-2 text-xs"><input v-model="autoKeepalive" type="checkbox" class="h-3.5 w-3.5" />{{ t("etcd.admin.keepalive") }}</label>
<div>
<div class="mb-1 flex items-center justify-between text-xs text-muted-foreground">
<span>{{ t("etcd.admin.attachedKeys") }}</span
><span>{{ selectedLease.keys.length }}{{ selectedLease.truncated ? "+" : "" }}</span>
</div>
<div class="max-h-44 overflow-auto rounded border">
<code v-for="key in selectedLease.keys" :key="`${key.encoding}:${key.data}`" class="block truncate border-b px-2 py-1 text-xs last:border-b-0">{{ key.encoding === "utf8" ? key.data : `base64:${key.data}` }}</code>
<div v-if="selectedLease.keys.length === 0" class="px-2 py-4 text-center text-xs text-muted-foreground">{{ t("etcd.admin.noAttachedKeys") }}</div>
</div>
<p v-if="selectedLease.truncated" class="mt-2 text-xs text-muted-foreground">{{ t("etcd.admin.attachedKeysTruncated") }}</p>
</div>
</div>
<div v-else class="flex h-32 items-center justify-center text-xs text-muted-foreground">{{ t("etcd.admin.selectLease") }}</div>
</div>
</div>
<div v-if="leases?.partial" class="text-xs text-muted-foreground">{{ t("etcd.admin.leasePartial") }}</div>
</template>
</div>
<Dialog :open="leaseGrantDialogOpen" @update:open="updateLeaseGrantDialog">
<DialogContent class="sm:max-w-md">
<DialogHeader
><DialogTitle>{{ t("etcd.admin.grantNewLease") }}</DialogTitle></DialogHeader
>
<form class="space-y-5" @submit.prevent="grantLease">
<label class="grid gap-1.5"
><span class="text-sm font-medium">{{ t("etcd.admin.ttl") }}</span
><Input v-model="leaseGrantTtl" class="h-10" type="number" min="1" step="1" inputmode="numeric" :placeholder="t('etcd.admin.ttlPlaceholder')" /><span class="text-xs text-muted-foreground">{{ t("etcd.admin.ttlHint") }}</span></label
>
<label class="grid gap-1.5"
><span class="text-sm font-medium"
>{{ t("etcd.admin.customLeaseId") }} <span class="font-normal text-muted-foreground">({{ t("etcd.access.optional") }})</span></span
><Input v-model="leaseGrantId" class="h-10 font-mono" inputmode="numeric" :placeholder="t('etcd.admin.customLeasePlaceholder')" /><span class="text-xs text-muted-foreground">{{ t("etcd.admin.customLeaseHint") }}</span></label
>
<DialogFooter class="gap-2 sm:gap-2"
><Button type="button" variant="outline" @click="closeLeaseGrantDialog">{{ t("etcd.admin.cancel") }}</Button
><Button type="submit" :disabled="leaseGrantBusy || !leaseGrantTtl.trim()"><Loader2 v-if="leaseGrantBusy" class="mr-2 h-4 w-4 animate-spin" />{{ t("etcd.admin.grantLease") }}</Button></DialogFooter
>
</form>
</DialogContent>
</Dialog>
<Dialog :open="watchDialogOpen" @update:open="updateWatchDialog">
<DialogContent class="sm:max-w-lg">
<DialogHeader>
<DialogTitle>{{ watchEditingId ? t("etcd.admin.editWatch") : t("etcd.admin.newWatch") }}</DialogTitle>
</DialogHeader>
<form class="space-y-5" @submit.prevent="saveWatchMonitor">
<label class="grid gap-1.5">
<span class="text-sm font-medium">{{ t("etcd.keyOrPrefix") }}</span>
<div class="relative">
<Input
v-model="watchFormKey"
class="h-10 font-mono"
role="combobox"
aria-autocomplete="list"
:aria-expanded="showWatchKeySuggestions"
aria-controls="etcd-watch-key-suggestions"
:aria-activedescendant="watchSuggestionIndex >= 0 ? `etcd-watch-key-suggestion-${watchSuggestionIndex}` : undefined"
:placeholder="t('etcd.admin.watchKeyPlaceholder')"
autofocus
@focus="watchSuggestionOpen = Boolean(watchFormKey.trim())"
@blur="closeWatchKeySuggestions"
@update:model-value="onWatchKeyInput"
@keydown="onWatchKeyKeydown"
/>
<div v-if="showWatchKeySuggestions" id="etcd-watch-key-suggestions" role="listbox" class="absolute z-50 mt-1 max-h-52 w-full overflow-auto rounded-md border bg-popover py-1 text-popover-foreground shadow-lg">
<button
v-for="(suggestion, index) in filteredWatchKeySuggestions"
:id="`etcd-watch-key-suggestion-${index}`"
:key="`${suggestion.keyBytes.encoding}:${suggestion.keyBytes.data}`"
type="button"
role="option"
:aria-selected="watchSuggestionIndex === index"
class="flex w-full items-center gap-2 px-3 py-2 text-left font-mono text-xs"
:class="watchSuggestionIndex === index ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/70'"
@mouseenter="watchSuggestionIndex = index"
@mousedown.prevent="acceptWatchKeySuggestion(index)"
>
<Search class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<span class="truncate">{{ suggestion.key }}</span>
</button>
</div>
</div>
</label>
<fieldset class="grid gap-2">
<legend class="text-sm font-medium">{{ t("etcd.admin.watchScope") }}</legend>
<div class="flex w-fit rounded-md border p-0.5">
<Button type="button" size="sm" :variant="watchFormScope === 'key' ? 'secondary' : 'ghost'" class="h-8 px-3" @click="watchFormScope = 'key'">{{ t("etcd.admin.exact") }}</Button>
<Button type="button" size="sm" :variant="watchFormScope === 'prefix' ? 'secondary' : 'ghost'" class="h-8 px-3" @click="watchFormScope = 'prefix'">{{ t("etcd.admin.prefix") }}</Button>
</div>
<p class="text-xs leading-5 text-muted-foreground">{{ watchFormScope === "key" ? t("etcd.admin.watchKeyHint") : t("etcd.admin.watchPrefixHint") }}</p>
</fieldset>
<div class="rounded-md border bg-muted/30 px-3 py-2 text-xs leading-5 text-muted-foreground">{{ t("etcd.admin.watchSessionHint") }}</div>
<DialogFooter class="gap-2 sm:gap-2">
<Button type="button" variant="outline" @click="closeWatchDialog">{{ t("etcd.admin.cancel") }}</Button>
<Button type="submit" :disabled="busy || !watchFormKey">{{ watchEditingId ? t("etcd.admin.saveWatch") : t("etcd.admin.createWatch") }}</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
<Dialog :open="maintenanceApprovalOpen" @update:open="(open) => !open && closeMaintenanceApproval()">
<DialogContent class="sm:max-w-md">
<DialogHeader>
<DialogTitle class="text-destructive">{{ maintenanceApprovalTitle }}</DialogTitle>
</DialogHeader>
<div class="space-y-4 py-2">
<p class="text-sm text-muted-foreground">{{ t("etcd.admin.confirmationHint") }}</p>
<div class="whitespace-pre-line border-l-2 border-destructive/70 pl-3 text-sm leading-6 text-foreground">{{ maintenanceApprovalDetails }}</div>
<div class="space-y-2 border-t pt-4">
<p class="text-xs leading-5 text-muted-foreground">{{ t("etcd.admin.confirmationCredentialHint") }}</p>
<code class="block break-all rounded border bg-muted px-3 py-2 text-xs">{{ maintenanceApprovalExpected }}</code>
<Input v-model="maintenanceApprovalText" :placeholder="t('etcd.admin.confirmationPlaceholder')" autocomplete="off" :disabled="busy" @keyup.enter="confirmMaintenanceApproval" />
</div>
</div>
<DialogFooter>
<Button variant="outline" :disabled="busy" @click="closeMaintenanceApproval">{{ t("etcd.admin.cancel") }}</Button>
<Button variant="destructive" :disabled="busy || maintenanceApprovalText !== maintenanceApprovalExpected" @click="confirmMaintenanceApproval">{{ t("etcd.admin.confirmExecute") }}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</section>
</template>
+341 -340
View File
@@ -216,12 +216,12 @@ defineExpose({ refresh });
</script>
<template>
<div class="h-full overflow-auto bg-background p-4">
<div class="mb-4 flex items-start justify-between gap-4">
<div>
<h2 class="text-lg font-semibold">{{ t("etcd.dashboard.title") }}</h2>
<p class="mt-1 text-xs text-muted-foreground">{{ t("etcd.dashboard.description") }}</p>
</div>
<div class="flex h-full min-h-0 flex-col bg-background">
<header class="flex h-14 shrink-0 items-center gap-3 border-b px-4">
<h2 class="shrink-0 text-sm font-semibold">{{ t("etcd.dashboard.title") }}</h2>
<div class="hidden h-5 w-px bg-border sm:block" />
<p class="hidden truncate text-xs text-muted-foreground sm:block">{{ t("etcd.dashboard.description") }}</p>
<div class="flex-1" />
<div class="flex items-center gap-2">
<select v-model.number="refreshSeconds" class="h-8 rounded-md border bg-background px-2 text-xs">
<option :value="0">{{ t("etcd.dashboard.autoRefreshOff") }}</option>
@@ -236,349 +236,350 @@ defineExpose({ refresh });
{{ t("etcd.dashboard.refresh") }}
</Button>
</div>
</div>
</header>
<div v-if="unsupported" class="mx-auto mt-[12vh] max-w-2xl rounded-xl border bg-muted/20 p-6 shadow-sm">
<div class="flex items-start gap-4">
<div class="rounded-full bg-amber-500/10 p-2.5 text-amber-600 dark:text-amber-400">
<AlertTriangle class="h-5 w-5" />
</div>
<div class="min-w-0 flex-1">
<h3 class="font-semibold">{{ t("etcd.dashboard.agentUpgradeTitle") }}</h3>
<p class="mt-2 text-sm leading-6 text-muted-foreground">{{ t("etcd.dashboard.agentUpgradeDescription") }}</p>
<div class="mt-4 rounded-md border bg-background px-3 py-2.5 text-xs leading-5 text-muted-foreground">
{{ t("etcd.dashboard.agentUpgradeSteps") }}
<div class="min-h-0 flex-1 overflow-auto p-4">
<div v-if="unsupported" class="mx-auto mt-[12vh] max-w-2xl rounded-xl border bg-muted/20 p-6 shadow-sm">
<div class="flex items-start gap-4">
<div class="rounded-full bg-amber-500/10 p-2.5 text-amber-600 dark:text-amber-400">
<AlertTriangle class="h-5 w-5" />
</div>
<div class="min-w-0 flex-1">
<h3 class="font-semibold">{{ t("etcd.dashboard.agentUpgradeTitle") }}</h3>
<p class="mt-2 text-sm leading-6 text-muted-foreground">{{ t("etcd.dashboard.agentUpgradeDescription") }}</p>
<div class="mt-4 rounded-md border bg-background px-3 py-2.5 text-xs leading-5 text-muted-foreground">
{{ t("etcd.dashboard.agentUpgradeSteps") }}
</div>
<Button class="mt-4" size="sm" variant="outline" :disabled="loading" @click="load">
<Loader2 v-if="loading" class="mr-2 h-3.5 w-3.5 animate-spin" />
<RefreshCw v-else class="mr-2 h-3.5 w-3.5" />
{{ t("etcd.dashboard.retry") }}
</Button>
</div>
<Button class="mt-4" size="sm" variant="outline" :disabled="loading" @click="load">
<Loader2 v-if="loading" class="mr-2 h-3.5 w-3.5 animate-spin" />
<RefreshCw v-else class="mr-2 h-3.5 w-3.5" />
{{ t("etcd.dashboard.retry") }}
</Button>
</div>
</div>
</div>
<div v-else-if="error" class="mb-4 rounded-lg border border-destructive/30 bg-destructive/5 p-4">
<div class="flex items-start gap-3">
<AlertTriangle class="mt-0.5 h-4 w-4 shrink-0 text-destructive" />
<div class="min-w-0">
<div class="text-sm font-medium text-destructive">{{ t("etcd.dashboard.loadFailed") }}</div>
<div class="mt-1 break-words text-xs leading-5 text-muted-foreground">{{ error }}</div>
</div>
</div>
</div>
<div v-if="status" class="grid gap-3">
<div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-5">
<div class="rounded-lg border p-4">
<div class="flex items-center gap-2 text-xs text-muted-foreground"><Gauge class="h-4 w-4" /> {{ t("etcd.dashboard.observedHealth") }}</div>
<div class="mt-3 flex items-center gap-2 text-xl font-semibold">
<CheckCircle2 v-if="health === 'healthy'" class="h-5 w-5 text-emerald-500" />
<AlertTriangle v-else class="h-5 w-5 text-amber-500" />
{{ t(`etcd.dashboard.health.${health}`) }}
</div>
</div>
<div class="rounded-lg border p-4">
<div class="flex items-center gap-2 text-xs text-muted-foreground"><Server class="h-4 w-4" /> {{ t("etcd.dashboard.reachableMembers") }}</div>
<div class="mt-3 text-xl font-semibold">{{ reachable }} / {{ status.members.length }}</div>
</div>
<div class="rounded-lg border p-4">
<div class="flex items-center gap-2 text-xs text-muted-foreground"><KeyRound class="h-4 w-4" /> {{ t("etcd.dashboard.keyCount") }}</div>
<div class="mt-3 text-xl font-semibold">{{ status.keyCount ?? "-" }}</div>
</div>
<div class="rounded-lg border p-4">
<div class="flex items-center gap-2 text-xs text-muted-foreground"><Database class="h-4 w-4" /> {{ t("etcd.dashboard.backendSize") }}</div>
<div class="mt-3 text-xl font-semibold">{{ formatBytes(totalDbSize) }}</div>
</div>
<div class="rounded-lg border p-4">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.fragmentation") }}</div>
<div class="mt-3 text-xl font-semibold">{{ (fragmentation * 100).toFixed(1) }}%</div>
</div>
</div>
<div class="flex flex-wrap gap-2 rounded-lg border p-3 text-xs">
<Badge variant="outline">{{ t("etcd.dashboard.cluster") }} {{ status.clusterId ?? "-" }}</Badge>
<Badge variant="outline">{{ t("etcd.dashboard.revision") }} {{ status.revision ?? "-" }}</Badge>
<Badge variant="outline">{{ t("etcd.dashboard.leader") }} {{ status.leaderId ?? "-" }}</Badge>
<Badge v-for="alarm in status.alarms" :key="alarm" variant="destructive">{{ alarm }}</Badge>
<Badge v-if="status.alarms.length === 0" variant="secondary">{{ t("etcd.dashboard.noAlarms") }}</Badge>
</div>
<section v-if="metrics?.available" class="rounded-lg border">
<div class="flex flex-wrap items-start justify-between gap-3 border-b px-4 py-3">
<div>
<div class="flex items-center gap-2 text-sm font-medium">
<Activity class="h-4 w-4 text-emerald-500" />
{{ t("etcd.dashboard.prometheusMetrics") }}
</div>
<p class="mt-1 text-xs text-muted-foreground">{{ t("etcd.dashboard.prometheusDescription") }}</p>
</div>
<div class="min-w-0 text-right text-xs text-muted-foreground">
<div class="max-w-[420px] truncate font-mono">{{ metrics.sourceUrl }}</div>
<div>{{ t("etcd.dashboard.collectedAt") }} {{ formatCollectedAt(metrics.collectedAtMs) }}</div>
</div>
</div>
<div class="grid gap-px bg-border sm:grid-cols-2 xl:grid-cols-4">
<div class="bg-background p-4">
<div class="flex items-center gap-2 text-xs text-muted-foreground"><Activity class="h-4 w-4" /> {{ t("etcd.dashboard.requests") }}</div>
<div class="mt-2 text-xl font-semibold">{{ formatRate(requestRate) }}</div>
<div class="mt-1 text-xs text-muted-foreground">{{ t("etcd.dashboard.requestFailureRate") }} {{ formatPercent(requestFailurePercent) }}</div>
</div>
<div class="bg-background p-4">
<div class="flex items-center gap-2 text-xs text-muted-foreground"><Gauge class="h-4 w-4" /> {{ t("etcd.dashboard.proposals") }}</div>
<div class="mt-2 text-xl font-semibold">{{ proposalLag ?? "-" }}</div>
<div class="mt-1 text-xs text-muted-foreground">{{ t("etcd.dashboard.proposalLag") }} · {{ t("etcd.dashboard.pending") }} {{ formatCount(metrics.proposalsPending) }}</div>
</div>
<div class="bg-background p-4">
<div class="flex items-center gap-2 text-xs text-muted-foreground"><Database class="h-4 w-4" /> {{ t("etcd.dashboard.storageQuota") }}</div>
<div class="mt-2 text-xl font-semibold">{{ formatPercent(quotaPercent) }}</div>
<div class="mt-1 text-xs text-muted-foreground">{{ formatBytes(metrics.dbSizeMetricBytes ?? Number.NaN) }} / {{ formatBytes(metrics.quotaBackendBytes ?? Number.NaN) }}</div>
</div>
<div class="bg-background p-4">
<div class="flex items-center gap-2 text-xs text-muted-foreground"><Clock3 class="h-4 w-4" /> {{ t("etcd.dashboard.uptime") }}</div>
<div class="mt-2 text-xl font-semibold">{{ formatDuration(uptimeSeconds) }}</div>
<div class="mt-1 text-xs text-muted-foreground">etcd {{ metrics.serverVersion ?? "-" }} · {{ metrics.goVersion ?? "-" }}</div>
</div>
</div>
<div class="border-t px-4 py-3">
<div class="flex items-center gap-2 text-sm font-medium"><Gauge class="h-4 w-4 text-sky-500" /> {{ t("etcd.dashboard.consensusReliability") }}</div>
<div class="mt-3 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
<div class="rounded-md border bg-muted/10 p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.leadership") }}</div>
<div class="mt-2 text-base font-semibold">{{ metrics.isLeader === 1 ? t("etcd.dashboard.leader") : t("etcd.dashboard.follower") }}</div>
<div class="mt-1 text-xs text-muted-foreground">{{ t("etcd.dashboard.leaderChanges") }} {{ formatCount(metrics.leaderChangesTotal) }} · {{ t("etcd.dashboard.knownPeers") }} {{ formatCount(metrics.knownPeers) }}</div>
</div>
<div class="rounded-md border bg-muted/10 p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.proposalState") }}</div>
<div class="mt-2 text-base font-semibold">{{ t("etcd.dashboard.pending") }} {{ formatCount(metrics.proposalsPending) }} · Lag {{ proposalLag ?? "-" }}</div>
<div class="mt-1 text-xs text-muted-foreground">{{ t("etcd.dashboard.failedProposals") }} {{ formatCount(metrics.proposalsFailedTotal) }} · {{ formatRate(proposalFailureRate) }}</div>
</div>
<div class="rounded-md border bg-muted/10 p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.raftFailures") }}</div>
<div class="mt-2 text-base font-semibold">Heartbeat {{ formatCount(metrics.heartbeatSendFailuresTotal) }}</div>
<div class="mt-1 text-xs text-muted-foreground">Read index {{ formatCount(metrics.readIndexesFailedTotal) }} · Slow {{ formatCount(metrics.slowReadIndexesTotal) }}</div>
</div>
<div class="rounded-md border bg-muted/10 p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.revisionState") }}</div>
<div class="mt-2 text-base font-semibold">{{ formatCount(metrics.mvccCurrentRevision) }}</div>
<div class="mt-1 text-xs text-muted-foreground">{{ t("etcd.dashboard.compactRevision") }} {{ formatCount(metrics.mvccCompactRevision) }} · Slow apply {{ formatCount(metrics.slowApplyTotal) }}</div>
</div>
</div>
</div>
<div class="border-t px-4 py-3">
<div class="flex items-center gap-2 text-sm font-medium"><Activity class="h-4 w-4 text-violet-500" /> {{ t("etcd.dashboard.requestLoad") }}</div>
<div class="mt-3 grid gap-3 xl:grid-cols-[minmax(0,2fr)_minmax(300px,1fr)]">
<div class="overflow-auto rounded-md border">
<table class="w-full min-w-[620px] text-left text-xs">
<thead class="bg-muted/60 text-muted-foreground">
<tr>
<th class="px-3 py-2">{{ t("etcd.dashboard.grpcMethod") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.total") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.rate") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.failures") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.avgLatency") }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in grpcMethodRows" :key="row.method" class="border-t">
<td class="px-3 py-2 font-medium">{{ row.method }}</td>
<td class="px-3 py-2 tabular-nums">{{ formatCount(row.total) }}</td>
<td class="px-3 py-2 tabular-nums">{{ formatRate(row.rate) }}</td>
<td class="px-3 py-2 tabular-nums">
{{ formatCount(row.failures) }} <span v-if="row.failureRate != null" class="text-muted-foreground">({{ formatRate(row.failureRate) }})</span>
</td>
<td class="px-3 py-2 tabular-nums">{{ formatMilliseconds(row.latencyMs) }}</td>
</tr>
</tbody>
</table>
</div>
<div class="grid grid-cols-2 gap-2">
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">Range</div>
<div class="mt-1 font-semibold">{{ formatRate(mvccRangeRate) }}</div>
<div class="text-xs text-muted-foreground">{{ formatCount(metrics.mvccRangeTotal) }}</div>
</div>
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">Put</div>
<div class="mt-1 font-semibold">{{ formatRate(mvccPutRate) }}</div>
<div class="text-xs text-muted-foreground">{{ formatCount(metrics.mvccPutTotal) }}</div>
</div>
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">Delete</div>
<div class="mt-1 font-semibold">{{ formatRate(mvccDeleteRate) }}</div>
<div class="text-xs text-muted-foreground">{{ formatCount(metrics.mvccDeleteTotal) }}</div>
</div>
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">Txn</div>
<div class="mt-1 font-semibold">{{ formatRate(mvccTxnRate) }}</div>
<div class="text-xs text-muted-foreground">{{ formatCount(metrics.mvccTxnTotal) }}</div>
</div>
</div>
</div>
</div>
<div class="border-t px-4 py-3">
<div class="flex items-center gap-2 text-sm font-medium"><HardDrive class="h-4 w-4 text-amber-500" /> {{ t("etcd.dashboard.storageDisk") }}</div>
<div class="mt-3 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.diskLatency") }}</div>
<div class="mt-2 font-semibold">WAL fsync {{ formatMilliseconds(walFsyncMs) }}</div>
<div class="mt-1 text-xs text-muted-foreground">WAL write {{ formatMilliseconds(walWriteMs) }} · {{ formatByteRate(walWriteRate) }}</div>
</div>
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">Backend</div>
<div class="mt-2 font-semibold">Commit {{ formatMilliseconds(backendCommitMs) }}</div>
<div class="mt-1 text-xs text-muted-foreground">Snapshot {{ formatMilliseconds(backendSnapshotMs) }} · Defrag {{ formatMilliseconds(backendDefragMs) }}</div>
</div>
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.databaseState") }}</div>
<div class="mt-2 font-semibold">{{ formatBytes(metrics.dbSizeInUseMetricBytes ?? Number.NaN) }} {{ t("etcd.dashboard.inUse") }}</div>
<div class="mt-1 text-xs text-muted-foreground">{{ t("etcd.dashboard.openReadTransactions") }} {{ formatCount(metrics.openReadTransactions) }} · Put bytes {{ formatBytes(metrics.mvccTotalPutSizeBytes ?? Number.NaN) }}</div>
</div>
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.backgroundTasks") }}</div>
<div class="mt-2 font-semibold">Defrag {{ formatCount(metrics.diskDefragInflight) }}</div>
<div class="mt-1 text-xs text-muted-foreground">Snapshot apply {{ formatCount(metrics.snapshotApplyInProgress) }}</div>
</div>
</div>
</div>
<div class="grid border-t xl:grid-cols-2 xl:divide-x">
<div class="px-4 py-3">
<div class="flex items-center gap-2 text-sm font-medium"><Eye class="h-4 w-4 text-cyan-500" /> {{ t("etcd.dashboard.watchState") }}</div>
<div class="mt-3 grid grid-cols-2 gap-2 text-xs sm:grid-cols-4">
<div>
<div class="text-muted-foreground">{{ t("etcd.dashboard.watchers") }}</div>
<div class="mt-1 text-base font-semibold">{{ formatCount(metrics.mvccWatcherTotal) }}</div>
</div>
<div>
<div class="text-muted-foreground">{{ t("etcd.dashboard.watchStreams") }}</div>
<div class="mt-1 text-base font-semibold">{{ formatCount(metrics.mvccWatchStreamTotal) }}</div>
</div>
<div>
<div class="text-muted-foreground">{{ t("etcd.dashboard.events") }}</div>
<div class="mt-1 text-base font-semibold">{{ formatRate(mvccEventRate) }}</div>
</div>
<div>
<div class="text-muted-foreground">{{ t("etcd.dashboard.slowPending") }}</div>
<div class="mt-1 text-base font-semibold">{{ formatCount(metrics.mvccSlowWatcherTotal) }} / {{ formatCount(metrics.mvccPendingEventsTotal) }}</div>
</div>
</div>
</div>
<div class="border-t px-4 py-3 xl:border-t-0">
<div class="flex items-center gap-2 text-sm font-medium"><Radio class="h-4 w-4 text-emerald-500" /> {{ t("etcd.dashboard.leaseState") }}</div>
<div class="mt-3 grid grid-cols-2 gap-2 text-xs sm:grid-cols-4">
<div>
<div class="text-muted-foreground">{{ t("etcd.dashboard.granted") }}</div>
<div class="mt-1 text-base font-semibold">{{ formatRate(leaseGrantedRate) }}</div>
</div>
<div>
<div class="text-muted-foreground">{{ t("etcd.dashboard.renewed") }}</div>
<div class="mt-1 text-base font-semibold">{{ formatRate(leaseRenewedRate) }}</div>
</div>
<div>
<div class="text-muted-foreground">{{ t("etcd.dashboard.revokedExpired") }}</div>
<div class="mt-1 text-base font-semibold">{{ formatRate(leaseRevokedRate) }} / {{ formatRate(leaseExpiredRate) }}</div>
</div>
<div>
<div class="text-muted-foreground">{{ t("etcd.dashboard.averageTtl") }}</div>
<div class="mt-1 text-base font-semibold">{{ averageLeaseTtl == null ? "-" : `${averageLeaseTtl.toFixed(1)}s` }}</div>
</div>
</div>
</div>
</div>
<div class="border-t px-4 py-3">
<div class="flex items-center gap-2 text-sm font-medium"><Cpu class="h-4 w-4 text-rose-500" /> {{ t("etcd.dashboard.runtimeResources") }}</div>
<div class="mt-3 grid gap-3 sm:grid-cols-2 xl:grid-cols-5">
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.memory") }}</div>
<div class="mt-2 font-semibold">RSS {{ formatBytes(metrics.residentMemoryBytes ?? Number.NaN) }}</div>
<div class="mt-1 text-xs text-muted-foreground">Heap {{ formatBytes(metrics.goHeapAllocBytes ?? Number.NaN) }} / {{ formatBytes(metrics.goHeapSysBytes ?? Number.NaN) }}</div>
</div>
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.runtime") }}</div>
<div class="mt-2 font-semibold">{{ formatCount(metrics.goroutines) }} goroutines</div>
<div class="mt-1 text-xs text-muted-foreground">{{ formatCount(metrics.goThreads) }} threads · GOMAXPROCS {{ formatCount(metrics.goMaxProcs) }}</div>
</div>
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.processResources") }}</div>
<div class="mt-2 font-semibold">CPU {{ formatPercent(cpuPercent) }}</div>
<div class="mt-1 text-xs text-muted-foreground">FD {{ formatCount(metrics.openFds) }} / {{ formatCount(metrics.maxFds) }} · {{ formatPercent(fdPercent) }}</div>
</div>
<div class="rounded-md border p-3">
<div class="flex items-center gap-1.5 text-xs text-muted-foreground"><Network class="h-3.5 w-3.5" /> {{ t("etcd.dashboard.networkTraffic") }}</div>
<div class="mt-2 font-semibold">↓ {{ formatByteRate(clientReceivedRate) }} · ↑ {{ formatByteRate(clientSentRate) }}</div>
<div class="mt-1 text-xs text-muted-foreground">Peer ↓ {{ formatByteRate(peerReceivedRate) }} · ↑ {{ formatByteRate(peerSentRate) }}</div>
</div>
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.processNetworkGc") }}</div>
<div class="mt-2 font-semibold">↓ {{ formatByteRate(processReceivedRate) }} · ↑ {{ formatByteRate(processTransmittedRate) }}</div>
<div class="mt-1 text-xs text-muted-foreground">GC {{ formatMilliseconds(goGcMs) }} · {{ formatCount(metrics.goHeapObjects) }} objects</div>
</div>
</div>
</div>
<div class="flex flex-wrap items-center gap-2 border-t px-4 py-3 text-xs">
<Badge variant="outline">etcd {{ metrics.serverVersion ?? "-" }}</Badge>
<Badge variant="outline">Cluster {{ metrics.clusterVersion ?? "-" }}</Badge>
<Badge variant="outline">Auth revision {{ formatCount(metrics.authRevision) }}</Badge>
<Badge variant="outline">Keys {{ formatCount(metrics.mvccKeysTotal) }}</Badge>
<Badge variant="outline">Health {{ formatCount(metrics.healthSuccessTotal) }} / {{ formatCount(metrics.healthFailuresTotal) }}</Badge>
<span v-if="requestRate == null" class="text-muted-foreground">{{ t("etcd.dashboard.rateNeedsRefresh") }}</span>
</div>
</section>
<section v-else-if="metrics && !metrics.available" class="rounded-lg border border-amber-500/30 bg-amber-500/5 p-4">
<div v-else-if="error" class="mb-4 rounded-lg border border-destructive/30 bg-destructive/5 p-4">
<div class="flex items-start gap-3">
<AlertTriangle class="mt-0.5 h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400" />
<AlertTriangle class="mt-0.5 h-4 w-4 shrink-0 text-destructive" />
<div class="min-w-0">
<div class="text-sm font-medium">{{ t("etcd.dashboard.metricsUnavailable") }}</div>
<p class="mt-1 text-xs leading-5 text-muted-foreground">{{ t("etcd.dashboard.metricsUnavailableHint") }}</p>
<p v-if="metrics.error" class="mt-2 break-words font-mono text-xs text-muted-foreground">{{ metrics.error }}</p>
<div class="text-sm font-medium text-destructive">{{ t("etcd.dashboard.loadFailed") }}</div>
<div class="mt-1 break-words text-xs leading-5 text-muted-foreground">{{ error }}</div>
</div>
</div>
</section>
<div class="overflow-auto rounded-lg border">
<table class="w-full min-w-[1050px] text-left text-sm">
<thead class="bg-muted/70 text-xs text-muted-foreground">
<tr>
<th class="px-3 py-2">{{ t("etcd.dashboard.endpointMember") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.role") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.version") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.revision") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.raftTermApplied") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.dbSizeInUse") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.latency") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.status") }}</th>
</tr>
</thead>
<tbody>
<tr v-for="member in status.members" :key="member.endpoint" class="border-t">
<td class="px-3 py-2">
<div class="font-medium">{{ member.name || member.endpoint }}</div>
<div class="max-w-72 truncate font-mono text-xs text-muted-foreground">{{ member.endpoint }} · {{ member.memberId || "-" }}</div>
</td>
<td class="px-3 py-2">{{ member.learner ? t("etcd.dashboard.learner") : member.memberId === status.leaderId ? t("etcd.dashboard.leader") : t("etcd.dashboard.follower") }}</td>
<td class="px-3 py-2">{{ member.version || "-" }}</td>
<td class="px-3 py-2 font-mono text-xs">{{ member.revision || "-" }}</td>
<td class="px-3 py-2 font-mono text-xs">{{ member.raftTerm || "-" }} / {{ member.raftAppliedIndex || "-" }}</td>
<td class="px-3 py-2">{{ formatBytes(Number(member.dbSize || 0)) }} / {{ formatBytes(Number(member.dbSizeInUse || 0)) }}</td>
<td class="px-3 py-2">{{ member.latencyMs == null ? "-" : `${member.latencyMs} ms` }}</td>
<td class="px-3 py-2">
<Badge :variant="member.reachable && member.errors.length === 0 ? 'secondary' : 'destructive'">
{{ member.reachable ? member.errors[0] || t("etcd.dashboard.reachable") : member.errors[0] || t("etcd.dashboard.unreachable") }}
</Badge>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div v-else-if="loading" class="flex h-64 items-center justify-center text-sm text-muted-foreground">
<Loader2 class="mr-2 h-4 w-4 animate-spin" />
{{ t("etcd.dashboard.loading") }}
<div v-if="status" class="grid gap-3">
<div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-5">
<div class="rounded-lg border p-4">
<div class="flex items-center gap-2 text-xs text-muted-foreground"><Gauge class="h-4 w-4" /> {{ t("etcd.dashboard.observedHealth") }}</div>
<div class="mt-3 flex items-center gap-2 text-xl font-semibold">
<CheckCircle2 v-if="health === 'healthy'" class="h-5 w-5 text-emerald-500" />
<AlertTriangle v-else class="h-5 w-5 text-amber-500" />
{{ t(`etcd.dashboard.health.${health}`) }}
</div>
</div>
<div class="rounded-lg border p-4">
<div class="flex items-center gap-2 text-xs text-muted-foreground"><Server class="h-4 w-4" /> {{ t("etcd.dashboard.reachableMembers") }}</div>
<div class="mt-3 text-xl font-semibold">{{ reachable }} / {{ status.members.length }}</div>
</div>
<div class="rounded-lg border p-4">
<div class="flex items-center gap-2 text-xs text-muted-foreground"><KeyRound class="h-4 w-4" /> {{ t("etcd.dashboard.keyCount") }}</div>
<div class="mt-3 text-xl font-semibold">{{ status.keyCount ?? "-" }}</div>
</div>
<div class="rounded-lg border p-4">
<div class="flex items-center gap-2 text-xs text-muted-foreground"><Database class="h-4 w-4" /> {{ t("etcd.dashboard.backendSize") }}</div>
<div class="mt-3 text-xl font-semibold">{{ formatBytes(totalDbSize) }}</div>
</div>
<div class="rounded-lg border p-4">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.fragmentation") }}</div>
<div class="mt-3 text-xl font-semibold">{{ (fragmentation * 100).toFixed(1) }}%</div>
</div>
</div>
<div class="flex flex-wrap gap-2 rounded-lg border p-3 text-xs">
<Badge variant="outline">{{ t("etcd.dashboard.cluster") }} {{ status.clusterId ?? "-" }}</Badge>
<Badge variant="outline">{{ t("etcd.dashboard.revision") }} {{ status.revision ?? "-" }}</Badge>
<Badge variant="outline">{{ t("etcd.dashboard.leader") }} {{ status.leaderId ?? "-" }}</Badge>
<Badge v-for="alarm in status.alarms" :key="alarm" variant="destructive">{{ alarm }}</Badge>
<Badge v-if="status.alarms.length === 0" variant="secondary">{{ t("etcd.dashboard.noAlarms") }}</Badge>
</div>
<section v-if="metrics?.available" class="rounded-lg border">
<div class="flex flex-wrap items-start justify-between gap-3 border-b px-4 py-3">
<div>
<div class="flex items-center gap-2 text-sm font-medium">
<Activity class="h-4 w-4 text-emerald-500" />
{{ t("etcd.dashboard.prometheusMetrics") }}
</div>
<p class="mt-1 text-xs text-muted-foreground">{{ t("etcd.dashboard.prometheusDescription") }}</p>
</div>
<div class="min-w-0 text-right text-xs text-muted-foreground">
<div class="max-w-[420px] truncate font-mono">{{ metrics.sourceUrl }}</div>
<div>{{ t("etcd.dashboard.collectedAt") }} {{ formatCollectedAt(metrics.collectedAtMs) }}</div>
</div>
</div>
<div class="grid gap-px bg-border sm:grid-cols-2 xl:grid-cols-4">
<div class="bg-background p-4">
<div class="flex items-center gap-2 text-xs text-muted-foreground"><Activity class="h-4 w-4" /> {{ t("etcd.dashboard.requests") }}</div>
<div class="mt-2 text-xl font-semibold">{{ formatRate(requestRate) }}</div>
<div class="mt-1 text-xs text-muted-foreground">{{ t("etcd.dashboard.requestFailureRate") }} {{ formatPercent(requestFailurePercent) }}</div>
</div>
<div class="bg-background p-4">
<div class="flex items-center gap-2 text-xs text-muted-foreground"><Gauge class="h-4 w-4" /> {{ t("etcd.dashboard.proposals") }}</div>
<div class="mt-2 text-xl font-semibold">{{ proposalLag ?? "-" }}</div>
<div class="mt-1 text-xs text-muted-foreground">{{ t("etcd.dashboard.proposalLag") }} · {{ t("etcd.dashboard.pending") }} {{ formatCount(metrics.proposalsPending) }}</div>
</div>
<div class="bg-background p-4">
<div class="flex items-center gap-2 text-xs text-muted-foreground"><Database class="h-4 w-4" /> {{ t("etcd.dashboard.storageQuota") }}</div>
<div class="mt-2 text-xl font-semibold">{{ formatPercent(quotaPercent) }}</div>
<div class="mt-1 text-xs text-muted-foreground">{{ formatBytes(metrics.dbSizeMetricBytes ?? Number.NaN) }} / {{ formatBytes(metrics.quotaBackendBytes ?? Number.NaN) }}</div>
</div>
<div class="bg-background p-4">
<div class="flex items-center gap-2 text-xs text-muted-foreground"><Clock3 class="h-4 w-4" /> {{ t("etcd.dashboard.uptime") }}</div>
<div class="mt-2 text-xl font-semibold">{{ formatDuration(uptimeSeconds) }}</div>
<div class="mt-1 text-xs text-muted-foreground">etcd {{ metrics.serverVersion ?? "-" }} · {{ metrics.goVersion ?? "-" }}</div>
</div>
</div>
<div class="border-t px-4 py-3">
<div class="flex items-center gap-2 text-sm font-medium"><Gauge class="h-4 w-4 text-sky-500" /> {{ t("etcd.dashboard.consensusReliability") }}</div>
<div class="mt-3 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
<div class="rounded-md border bg-muted/10 p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.leadership") }}</div>
<div class="mt-2 text-base font-semibold">{{ metrics.isLeader === 1 ? t("etcd.dashboard.leader") : t("etcd.dashboard.follower") }}</div>
<div class="mt-1 text-xs text-muted-foreground">{{ t("etcd.dashboard.leaderChanges") }} {{ formatCount(metrics.leaderChangesTotal) }} · {{ t("etcd.dashboard.knownPeers") }} {{ formatCount(metrics.knownPeers) }}</div>
</div>
<div class="rounded-md border bg-muted/10 p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.proposalState") }}</div>
<div class="mt-2 text-base font-semibold">{{ t("etcd.dashboard.pending") }} {{ formatCount(metrics.proposalsPending) }} · {{ t("etcd.dashboard.lag") }} {{ proposalLag ?? "-" }}</div>
<div class="mt-1 text-xs text-muted-foreground">{{ t("etcd.dashboard.failedProposals") }} {{ formatCount(metrics.proposalsFailedTotal) }} · {{ formatRate(proposalFailureRate) }}</div>
</div>
<div class="rounded-md border bg-muted/10 p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.raftFailures") }}</div>
<div class="mt-2 text-base font-semibold">Heartbeat {{ formatCount(metrics.heartbeatSendFailuresTotal) }}</div>
<div class="mt-1 text-xs text-muted-foreground">Read index {{ formatCount(metrics.readIndexesFailedTotal) }} · Slow {{ formatCount(metrics.slowReadIndexesTotal) }}</div>
</div>
<div class="rounded-md border bg-muted/10 p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.revisionState") }}</div>
<div class="mt-2 text-base font-semibold">{{ formatCount(metrics.mvccCurrentRevision) }}</div>
<div class="mt-1 text-xs text-muted-foreground">{{ t("etcd.dashboard.compactRevision") }} {{ formatCount(metrics.mvccCompactRevision) }} · {{ t("etcd.dashboard.slowApply") }} {{ formatCount(metrics.slowApplyTotal) }}</div>
</div>
</div>
</div>
<div class="border-t px-4 py-3">
<div class="flex items-center gap-2 text-sm font-medium"><Activity class="h-4 w-4 text-violet-500" /> {{ t("etcd.dashboard.requestLoad") }}</div>
<div class="mt-3 grid gap-3 xl:grid-cols-[minmax(0,2fr)_minmax(300px,1fr)]">
<div class="overflow-auto rounded-md border">
<table class="w-full min-w-[620px] text-left text-xs">
<thead class="bg-muted/60 text-muted-foreground">
<tr>
<th class="px-3 py-2">{{ t("etcd.dashboard.grpcMethod") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.total") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.rate") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.failures") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.avgLatency") }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in grpcMethodRows" :key="row.method" class="border-t">
<td class="px-3 py-2 font-medium">{{ row.method }}</td>
<td class="px-3 py-2 tabular-nums">{{ formatCount(row.total) }}</td>
<td class="px-3 py-2 tabular-nums">{{ formatRate(row.rate) }}</td>
<td class="px-3 py-2 tabular-nums">
{{ formatCount(row.failures) }} <span v-if="row.failureRate != null" class="text-muted-foreground">({{ formatRate(row.failureRate) }})</span>
</td>
<td class="px-3 py-2 tabular-nums">{{ formatMilliseconds(row.latencyMs) }}</td>
</tr>
</tbody>
</table>
</div>
<div class="grid grid-cols-2 gap-2">
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">Range</div>
<div class="mt-1 font-semibold">{{ formatRate(mvccRangeRate) }}</div>
<div class="text-xs text-muted-foreground">{{ formatCount(metrics.mvccRangeTotal) }}</div>
</div>
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">Put</div>
<div class="mt-1 font-semibold">{{ formatRate(mvccPutRate) }}</div>
<div class="text-xs text-muted-foreground">{{ formatCount(metrics.mvccPutTotal) }}</div>
</div>
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">Delete</div>
<div class="mt-1 font-semibold">{{ formatRate(mvccDeleteRate) }}</div>
<div class="text-xs text-muted-foreground">{{ formatCount(metrics.mvccDeleteTotal) }}</div>
</div>
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">Txn</div>
<div class="mt-1 font-semibold">{{ formatRate(mvccTxnRate) }}</div>
<div class="text-xs text-muted-foreground">{{ formatCount(metrics.mvccTxnTotal) }}</div>
</div>
</div>
</div>
</div>
<div class="border-t px-4 py-3">
<div class="flex items-center gap-2 text-sm font-medium"><HardDrive class="h-4 w-4 text-amber-500" /> {{ t("etcd.dashboard.storageDisk") }}</div>
<div class="mt-3 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.diskLatency") }}</div>
<div class="mt-2 font-semibold">WAL fsync {{ formatMilliseconds(walFsyncMs) }}</div>
<div class="mt-1 text-xs text-muted-foreground">WAL write {{ formatMilliseconds(walWriteMs) }} · {{ formatByteRate(walWriteRate) }}</div>
</div>
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">Backend</div>
<div class="mt-2 font-semibold">Commit {{ formatMilliseconds(backendCommitMs) }}</div>
<div class="mt-1 text-xs text-muted-foreground">Snapshot {{ formatMilliseconds(backendSnapshotMs) }} · Defrag {{ formatMilliseconds(backendDefragMs) }}</div>
</div>
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.databaseState") }}</div>
<div class="mt-2 font-semibold">{{ formatBytes(metrics.dbSizeInUseMetricBytes ?? Number.NaN) }} {{ t("etcd.dashboard.inUse") }}</div>
<div class="mt-1 text-xs text-muted-foreground">{{ t("etcd.dashboard.openReadTransactions") }} {{ formatCount(metrics.openReadTransactions) }} · {{ t("etcd.dashboard.putBytes") }} {{ formatBytes(metrics.mvccTotalPutSizeBytes ?? Number.NaN) }}</div>
</div>
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.backgroundTasks") }}</div>
<div class="mt-2 font-semibold">Defrag {{ formatCount(metrics.diskDefragInflight) }}</div>
<div class="mt-1 text-xs text-muted-foreground">Snapshot apply {{ formatCount(metrics.snapshotApplyInProgress) }}</div>
</div>
</div>
</div>
<div class="grid border-t xl:grid-cols-2 xl:divide-x">
<div class="px-4 py-3">
<div class="flex items-center gap-2 text-sm font-medium"><Eye class="h-4 w-4 text-cyan-500" /> {{ t("etcd.dashboard.watchState") }}</div>
<div class="mt-3 grid grid-cols-2 gap-2 text-xs sm:grid-cols-4">
<div>
<div class="text-muted-foreground">{{ t("etcd.dashboard.watchers") }}</div>
<div class="mt-1 text-base font-semibold">{{ formatCount(metrics.mvccWatcherTotal) }}</div>
</div>
<div>
<div class="text-muted-foreground">{{ t("etcd.dashboard.watchStreams") }}</div>
<div class="mt-1 text-base font-semibold">{{ formatCount(metrics.mvccWatchStreamTotal) }}</div>
</div>
<div>
<div class="text-muted-foreground">{{ t("etcd.dashboard.events") }}</div>
<div class="mt-1 text-base font-semibold">{{ formatRate(mvccEventRate) }}</div>
</div>
<div>
<div class="text-muted-foreground">{{ t("etcd.dashboard.slowPending") }}</div>
<div class="mt-1 text-base font-semibold">{{ formatCount(metrics.mvccSlowWatcherTotal) }} / {{ formatCount(metrics.mvccPendingEventsTotal) }}</div>
</div>
</div>
</div>
<div class="border-t px-4 py-3 xl:border-t-0">
<div class="flex items-center gap-2 text-sm font-medium"><Radio class="h-4 w-4 text-emerald-500" /> {{ t("etcd.dashboard.leaseState") }}</div>
<div class="mt-3 grid grid-cols-2 gap-2 text-xs sm:grid-cols-4">
<div>
<div class="text-muted-foreground">{{ t("etcd.dashboard.granted") }}</div>
<div class="mt-1 text-base font-semibold">{{ formatRate(leaseGrantedRate) }}</div>
</div>
<div>
<div class="text-muted-foreground">{{ t("etcd.dashboard.renewed") }}</div>
<div class="mt-1 text-base font-semibold">{{ formatRate(leaseRenewedRate) }}</div>
</div>
<div>
<div class="text-muted-foreground">{{ t("etcd.dashboard.revokedExpired") }}</div>
<div class="mt-1 text-base font-semibold">{{ formatRate(leaseRevokedRate) }} / {{ formatRate(leaseExpiredRate) }}</div>
</div>
<div>
<div class="text-muted-foreground">{{ t("etcd.dashboard.averageTtl") }}</div>
<div class="mt-1 text-base font-semibold">{{ averageLeaseTtl == null ? "-" : `${averageLeaseTtl.toFixed(1)}s` }}</div>
</div>
</div>
</div>
</div>
<div class="border-t px-4 py-3">
<div class="flex items-center gap-2 text-sm font-medium"><Cpu class="h-4 w-4 text-rose-500" /> {{ t("etcd.dashboard.runtimeResources") }}</div>
<div class="mt-3 grid gap-3 sm:grid-cols-2 xl:grid-cols-5">
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.memory") }}</div>
<div class="mt-2 font-semibold">RSS {{ formatBytes(metrics.residentMemoryBytes ?? Number.NaN) }}</div>
<div class="mt-1 text-xs text-muted-foreground">Heap {{ formatBytes(metrics.goHeapAllocBytes ?? Number.NaN) }} / {{ formatBytes(metrics.goHeapSysBytes ?? Number.NaN) }}</div>
</div>
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.runtime") }}</div>
<div class="mt-2 font-semibold">{{ formatCount(metrics.goroutines) }} goroutines</div>
<div class="mt-1 text-xs text-muted-foreground">{{ formatCount(metrics.goThreads) }} threads · GOMAXPROCS {{ formatCount(metrics.goMaxProcs) }}</div>
</div>
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.processResources") }}</div>
<div class="mt-2 font-semibold">CPU {{ formatPercent(cpuPercent) }}</div>
<div class="mt-1 text-xs text-muted-foreground">FD {{ formatCount(metrics.openFds) }} / {{ formatCount(metrics.maxFds) }} · {{ formatPercent(fdPercent) }}</div>
</div>
<div class="rounded-md border p-3">
<div class="flex items-center gap-1.5 text-xs text-muted-foreground"><Network class="h-3.5 w-3.5" /> {{ t("etcd.dashboard.networkTraffic") }}</div>
<div class="mt-2 font-semibold">↓ {{ formatByteRate(clientReceivedRate) }} · ↑ {{ formatByteRate(clientSentRate) }}</div>
<div class="mt-1 text-xs text-muted-foreground">Peer ↓ {{ formatByteRate(peerReceivedRate) }} · ↑ {{ formatByteRate(peerSentRate) }}</div>
</div>
<div class="rounded-md border p-3">
<div class="text-xs text-muted-foreground">{{ t("etcd.dashboard.processNetworkGc") }}</div>
<div class="mt-2 font-semibold">↓ {{ formatByteRate(processReceivedRate) }} · ↑ {{ formatByteRate(processTransmittedRate) }}</div>
<div class="mt-1 text-xs text-muted-foreground">GC {{ formatMilliseconds(goGcMs) }} · {{ formatCount(metrics.goHeapObjects) }} objects</div>
</div>
</div>
</div>
<div class="flex flex-wrap items-center gap-2 border-t px-4 py-3 text-xs">
<Badge variant="outline">etcd {{ metrics.serverVersion ?? "-" }}</Badge>
<Badge variant="outline">Cluster {{ metrics.clusterVersion ?? "-" }}</Badge>
<Badge variant="outline">Auth revision {{ formatCount(metrics.authRevision) }}</Badge>
<Badge variant="outline">Keys {{ formatCount(metrics.mvccKeysTotal) }}</Badge>
<Badge variant="outline">Health {{ formatCount(metrics.healthSuccessTotal) }} / {{ formatCount(metrics.healthFailuresTotal) }}</Badge>
<span v-if="requestRate == null" class="text-muted-foreground">{{ t("etcd.dashboard.rateNeedsRefresh") }}</span>
</div>
</section>
<section v-else-if="metrics && !metrics.available" class="rounded-lg border border-amber-500/30 bg-amber-500/5 p-4">
<div class="flex items-start gap-3">
<AlertTriangle class="mt-0.5 h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400" />
<div class="min-w-0">
<div class="text-sm font-medium">{{ t("etcd.dashboard.metricsUnavailable") }}</div>
<p class="mt-1 text-xs leading-5 text-muted-foreground">{{ t("etcd.dashboard.metricsUnavailableHint") }}</p>
<p v-if="metrics.error" class="mt-2 break-words font-mono text-xs text-muted-foreground">{{ metrics.error }}</p>
</div>
</div>
</section>
<div class="overflow-auto rounded-lg border">
<table class="w-full min-w-[1050px] text-left text-sm">
<thead class="bg-muted/70 text-xs text-muted-foreground">
<tr>
<th class="px-3 py-2">{{ t("etcd.dashboard.endpointMember") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.role") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.version") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.revision") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.raftTermApplied") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.dbSizeInUse") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.latency") }}</th>
<th class="px-3 py-2">{{ t("etcd.dashboard.status") }}</th>
</tr>
</thead>
<tbody>
<tr v-for="member in status.members" :key="member.endpoint" class="border-t">
<td class="px-3 py-2">
<div class="font-medium">{{ member.name || member.endpoint }}</div>
<div class="max-w-72 truncate font-mono text-xs text-muted-foreground">{{ member.endpoint }} · {{ member.memberId || "-" }}</div>
</td>
<td class="px-3 py-2">{{ member.learner ? t("etcd.dashboard.learner") : member.memberId === status.leaderId ? t("etcd.dashboard.leader") : t("etcd.dashboard.follower") }}</td>
<td class="px-3 py-2">{{ member.version || "-" }}</td>
<td class="px-3 py-2 font-mono text-xs">{{ member.revision || "-" }}</td>
<td class="px-3 py-2 font-mono text-xs">{{ member.raftTerm || "-" }} / {{ member.raftAppliedIndex || "-" }}</td>
<td class="px-3 py-2">{{ formatBytes(Number(member.dbSize || 0)) }} / {{ formatBytes(Number(member.dbSizeInUse || 0)) }}</td>
<td class="px-3 py-2">{{ member.latencyMs == null ? "-" : `${member.latencyMs} ms` }}</td>
<td class="px-3 py-2">
<Badge :variant="member.reachable && member.errors.length === 0 ? 'secondary' : 'destructive'">
{{ member.reachable ? member.errors[0] || t("etcd.dashboard.reachable") : member.errors[0] || t("etcd.dashboard.unreachable") }}
</Badge>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div v-else-if="loading" class="flex h-64 items-center justify-center text-sm text-muted-foreground">
<Loader2 class="mr-2 h-4 w-4 animate-spin" />
{{ t("etcd.dashboard.loading") }}
</div>
</div>
</div>
</template>
File diff suppressed because it is too large. Load diff
@@ -166,6 +166,47 @@ describe("EtcdKeyBrowser TTL capability recovery", () => {
});
});
describe("EtcdKeyBrowser global search", () => {
it("clears results and counters while retaining the search form", async () => {
backend.etcdListPrefix.mockResolvedValue({
keys: [
{
key: "/test/config",
keyBytes: { encoding: "utf8", data: "/test/config" },
value: { encoding: "utf8", data: "matched value" },
modRevision: "8",
},
],
continuation: null,
revision: "8",
});
await mountBrowser();
const openSearch = [...root!.querySelectorAll("button")].find((button) => button.textContent?.includes("etcd.globalSearch"));
openSearch?.click();
await flushUi();
const input = root!.querySelector<HTMLInputElement>('input[placeholder="etcd.searchPlaceholder"]')!;
input.value = "matched";
input.dispatchEvent(new Event("input"));
await flushUi();
const submit = [...root!.querySelectorAll("button")].filter((button) => button.textContent?.includes("etcd.globalSearch")).at(-1);
submit?.click();
await flushUi();
expect(root!.textContent).toContain("/test/config");
const clear = [...root!.querySelectorAll("button")].find((button) => button.textContent?.includes("etcd.clearSearchResults"));
expect(clear).toBeTruthy();
clear?.click();
await flushUi();
expect(root!.textContent).not.toContain("/test/config");
expect(root!.textContent).toContain("已扫描 0 个 Key");
expect(input.value).toBe("matched");
expect([...root!.querySelectorAll("button")].some((button) => button.textContent?.includes("etcd.clearSearchResults"))).toBe(false);
});
});
describe("EtcdKeyBrowser byte-identity routing", () => {
it("keeps colliding display keys on distinct keyBytes routes", async () => {
backend.etcdListPrefix.mockResolvedValue({
@@ -264,10 +305,10 @@ describe("EtcdKeyBrowser byte-identity routing", () => {
searchSubmit?.click();
await flushUi();
const rows = [...root.querySelectorAll("tbody tr")];
expect(rows).toHaveLength(2);
rows[0].dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
rows[1].dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
const resultButtons = [...root.querySelectorAll("button")].filter((button) => button.textContent?.includes("[base64:/w==]"));
expect(resultButtons).toHaveLength(2);
resultButtons[0].click();
resultButtons[1].click();
await flushUi();
expect(backend.selectKeyCalls).toHaveLength(2);
+185 -15
View File
@@ -4,7 +4,7 @@ import { useI18n } from "vue-i18n";
import { Pane, Splitpanes } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import { useConnectionStore } from "@/stores/connectionStore";
import { ChevronDown, ChevronRight, Clock3, Copy, Download, FolderClosed, FolderOpen, KeyRound, Loader2, Pencil, Plus, RefreshCw, Search, Trash2 } from "@lucide/vue";
import { Activity, ChevronDown, ChevronRight, Clock3, Copy, Download, FolderClosed, FolderOpen, KeyRound, Loader2, Pencil, Plus, RefreshCw, Search, Trash2 } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
@@ -96,6 +96,12 @@ interface KvKeyBrowserLabels {
summaryVersion?: string;
summaryLease?: string;
summarySize?: string;
watch?: string;
selectExistingLease?: string;
enterLeaseId?: string;
leasePickerHint?: string;
noLeasePickerHint?: string;
registryWarning?: string;
}
interface KvCreateModeOption {
@@ -154,6 +160,9 @@ const props = withDefaults(
safeWrite?: boolean;
allowBinaryEdit?: boolean;
readOnly?: boolean;
onWatchKey?: (route: KvKeyRoute) => void;
leaseOptions?: Array<{ id: KvInt64; ttl: number; grantedTtl?: number }>;
onLeaseOptionsRequested?: () => void;
}>(),
{
supportsCreateModes: false,
@@ -167,6 +176,7 @@ const props = withDefaults(
safeWrite: false,
allowBinaryEdit: false,
readOnly: false,
leaseOptions: () => [],
},
);
@@ -175,6 +185,8 @@ const { toast } = useToast();
const connectionStore = useConnectionStore();
const searchInputRef = ref<HTMLInputElement>();
const prefix = ref("");
const keySuggestionOpen = ref(false);
const keySuggestionIndex = ref(-1);
const keys = ref<KvKeySummary[]>([]);
const continuation = ref<string | null>(null);
const listRevision = ref<KvInt64 | null>(null);
@@ -232,6 +244,7 @@ let metadataRefreshInFlight = false;
let keyListRefreshTimer: ReturnType<typeof setTimeout> | null = null;
let keyListRefreshGeneration = 0;
let keyListRefreshDelayMs = keyListRefreshBaseIntervalMs;
let initialLoadPromise: Promise<void> | null = null;
type LoadKeysOptions = {
preserveSelection?: boolean;
};
@@ -262,6 +275,21 @@ function knownLeaseKeyRoutes(): KvKeyRoute[] {
}
const tree = computed(() => buildKvKeyTree(keys.value));
const keySuggestions = computed(() => {
const query = prefix.value.trim();
if (!query) return [];
const seen = new Set<string>();
const suggestions: KvKeySummary[] = [];
for (const key of keys.value) {
if (key.key === query || !key.key.startsWith(query) || seen.has(summaryIdentity(key))) continue;
seen.add(summaryIdentity(key));
suggestions.push(key);
if (suggestions.length === 8) break;
}
return suggestions;
});
const showKeySuggestions = computed(() => keySuggestionOpen.value && keySuggestions.value.length > 0);
const visibleRows = computed<BrowserTreeRow[]>(() => {
if (props.lazyHierarchy) return flattenLazyKvKeyTree(lazyTreeState, expandedGroupIds.value);
return flattenVisibleKvKeyTree(tree.value, expandedGroupIds.value).map((row) => ({ type: "node", node: row.node, depth: row.depth }));
@@ -333,6 +361,61 @@ function preserveExpandedGroups(expandAll = false) {
expandedGroupIds.value = preserveKvExpandedGroupIds(tree.value, expandedGroupIds.value, expandAll);
}
function closeKeySuggestions() {
keySuggestionOpen.value = false;
keySuggestionIndex.value = -1;
}
function onPrefixInput(event: Event) {
const value = (event.target as HTMLInputElement).value;
keySuggestionOpen.value = Boolean(value.trim());
keySuggestionIndex.value = -1;
}
function moveKeySuggestion(delta: number) {
if (!keySuggestions.value.length) return;
keySuggestionOpen.value = true;
keySuggestionIndex.value = (keySuggestionIndex.value + delta + keySuggestions.value.length) % keySuggestions.value.length;
}
function acceptKeySuggestion(index: number) {
const suggestion = keySuggestions.value[index];
if (!suggestion) return;
prefix.value = suggestion.key;
closeKeySuggestions();
void loadKeys(true);
}
function onPrefixKeydown(event: KeyboardEvent) {
if (event.isComposing) return;
if (event.key === "Escape") {
closeKeySuggestions();
return;
}
if (event.key === "ArrowDown") {
if (!keySuggestions.value.length) return;
event.preventDefault();
moveKeySuggestion(1);
return;
}
if (event.key === "ArrowUp") {
if (!keySuggestions.value.length) return;
event.preventDefault();
moveKeySuggestion(-1);
return;
}
if (event.key !== "Enter") return;
event.preventDefault();
if (showKeySuggestions.value && keySuggestionIndex.value >= 0) {
acceptKeySuggestion(keySuggestionIndex.value);
return;
}
closeKeySuggestions();
void loadKeys(true);
}
function handleKvBrowserSplitResized(payload: { panes?: { size: number }[] }) {
const size = payload.panes?.[0]?.size;
if (typeof size !== "number" || size < 20 || size > 70) return;
@@ -756,6 +839,11 @@ function openCreateDialog(parentPath?: string) {
showEditDialog.value = true;
}
function selectExpiryMode(mode: KvExpiryMode) {
editExpiryMode.value = mode;
if (mode === "lease") props.onLeaseOptionsRequested?.();
}
function openEditDialog() {
if (!selectedKey.value || !canEditSelectedValue.value) return;
isCreating.value = false;
@@ -930,6 +1018,15 @@ async function copySelectedKey() {
await navigator.clipboard.writeText(selectedKey.value);
}
function watchSelectedKey() {
if (!selectedKey.value || !props.onWatchKey) return;
props.onWatchKey({
key: selectedKey.value,
keyIdentity: selectedKeyIdentity.value,
keyBytes: selectedKeyBytes.value,
});
}
function downloadText(filename: string, content: string, type = "application/json") {
const url = URL.createObjectURL(new Blob([content], { type }));
const anchor = document.createElement("a");
@@ -1206,6 +1303,27 @@ function refresh(): boolean {
return true;
}
function expandPathToKey(key: string) {
if (props.lazyHierarchy) return;
const segments = key.split("/").filter(Boolean);
if (segments.length < 2) return;
const next = new Set(expandedGroupIds.value);
const groupPrefix = key.startsWith("/") ? "/" : "";
for (let index = 1; index < segments.length; index++) {
next.add(`group:${groupPrefix}${segments.slice(0, index).join("\u0000")}`);
}
expandedGroupIds.value = next;
}
async function selectKeyFromNavigation(key: string | KvKeyRoute) {
// Search results can remount this browser. Wait for the initial list reset
// before applying the selection so it cannot clear the detail pane afterward.
await initialLoadPromise?.catch(() => undefined);
const route = routeFromKey(key);
expandPathToKey(route.key);
await loadSelectedKey(route);
}
watch(
() => props.connectionId,
async () => {
@@ -1251,13 +1369,19 @@ watch(editKey, () => {
editErrorKind.value = "request";
});
onMounted(async () => {
try {
await connectionStore.ensureConnected(props.connectionId);
} catch (e) {
console.warn("[DBX] ensureConnected failed for", props.connectionId, e);
}
void loadKeys(true);
onMounted(() => {
initialLoadPromise = (async () => {
try {
await connectionStore.ensureConnected(props.connectionId);
} catch (e) {
console.warn("[DBX] ensureConnected failed for", props.connectionId, e);
}
try {
await loadKeys(true);
} catch {
// The browser's normal refresh path can retry after a transient failure.
}
})();
});
onBeforeUnmount(() => {
@@ -1267,7 +1391,7 @@ onBeforeUnmount(() => {
defineExpose({
focusSearch,
refresh,
selectKey: (key: string | KvKeyRoute) => loadSelectedKey(key),
selectKey: selectKeyFromNavigation,
openCreate: (parentPath?: string) => openCreateDialog(parentPath),
selection: () => ({ key: selectedKey.value, value: selectedValue.value }),
});
@@ -1278,7 +1402,38 @@ defineExpose({
<div class="flex shrink-0 items-center gap-2 border-b px-3 py-2">
<div class="relative min-w-0 flex-1">
<Search class="pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input ref="searchInputRef" v-model="prefix" class="h-8 pl-8" :placeholder="labels.prefixPlaceholder" @keyup.enter="loadKeys(true)" />
<Input
ref="searchInputRef"
v-model="prefix"
class="h-8 pl-8"
role="combobox"
aria-autocomplete="list"
:aria-expanded="showKeySuggestions"
aria-controls="kv-key-prefix-suggestions"
:aria-activedescendant="keySuggestionIndex >= 0 ? `kv-key-prefix-suggestion-${keySuggestionIndex}` : undefined"
:placeholder="labels.prefixPlaceholder"
@input="onPrefixInput"
@focus="keySuggestionOpen = Boolean(prefix.trim())"
@blur="closeKeySuggestions"
@keydown="onPrefixKeydown"
/>
<div v-if="showKeySuggestions" id="kv-key-prefix-suggestions" role="listbox" class="absolute z-50 mt-1 max-h-64 w-full overflow-auto rounded-md border bg-popover py-1 text-popover-foreground shadow-lg">
<button
v-for="(suggestion, index) in keySuggestions"
:id="`kv-key-prefix-suggestion-${index}`"
:key="summaryIdentity(suggestion)"
type="button"
role="option"
:aria-selected="keySuggestionIndex === index"
class="flex w-full items-center gap-2 px-3 py-1.5 text-left font-mono text-xs"
:class="keySuggestionIndex === index ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/70'"
@mouseenter="keySuggestionIndex = index"
@mousedown.prevent="acceptKeySuggestion(index)"
>
<Search class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<span class="truncate">{{ suggestion.key }}</span>
</button>
</div>
</div>
<Button size="sm" variant="outline" class="h-8 gap-1.5" :disabled="loading" @click="loadKeys(true, { preserveSelection: true })">
<Loader2 v-if="loading" class="h-3.5 w-3.5 animate-spin" />
@@ -1306,8 +1461,8 @@ defineExpose({
<CustomContextMenu v-if="row.type === 'node'" :items="nodeContextMenuItems(row.node)" v-slot="{ onContextMenu }">
<button
type="button"
class="flex h-8 w-full items-center gap-1.5 px-2 text-left hover:bg-accent"
:class="{ 'bg-accent/70': rowIsSelected(row.node) }"
class="flex h-8 w-full items-center gap-1.5 px-2 text-left transition-colors hover:bg-accent"
:class="rowIsSelected(row.node) ? 'bg-primary/10 font-medium text-foreground shadow-[inset_3px_0_0_hsl(var(--primary))]' : ''"
:style="{ paddingLeft: `${8 + row.depth * 18}px` }"
@click="onRowClick(row.node)"
@dblclick.stop.prevent="onRowDoubleClick(row.node)"
@@ -1369,6 +1524,10 @@ defineExpose({
</div>
</div>
<div class="flex shrink-0 gap-2">
<Button v-if="onWatchKey" size="sm" variant="outline" class="h-8 gap-1.5" @click="watchSelectedKey">
<Activity class="h-3.5 w-3.5" />
{{ labels.watch || "Watch" }}
</Button>
<Button v-if="api.history" size="sm" variant="outline" class="h-8 gap-1.5" @click="openHistory">
<Clock3 class="h-3.5 w-3.5" />
{{ labels.history || "History" }}
@@ -1427,7 +1586,9 @@ defineExpose({
<div v-if="editError && editErrorKind === 'keyAlreadyExists'" class="rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-sm text-amber-700 dark:text-amber-300">
{{ editError }}
</div>
<div v-if="highRiskRegistryKey" class="rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs text-amber-700 dark:text-amber-300">This key is under /registry/, a namespace commonly used by control-plane components. Verify the owner and impact before saving.</div>
<div v-if="highRiskRegistryKey" class="rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs text-amber-700 dark:text-amber-300">
{{ labels.registryWarning || "This key is under /registry/, a namespace commonly used by control-plane components. Verify the owner and impact before saving." }}
</div>
</div>
<div v-if="showCreateModeSelect" class="grid gap-2">
@@ -1454,7 +1615,7 @@ defineExpose({
class="flex min-h-20 items-start gap-3 rounded-md border bg-background px-3 py-3 text-left transition-colors hover:border-primary/50 disabled:cursor-not-allowed disabled:opacity-45"
:class="editExpiryMode === option.value ? 'border-primary bg-primary/5 ring-1 ring-primary/30' : 'border-input'"
:disabled="option.disabled"
@click="editExpiryMode = option.value"
@click="selectExpiryMode(option.value)"
>
<span class="mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full border" :class="editExpiryMode === option.value ? 'border-primary' : 'border-muted-foreground/50'">
<span v-if="editExpiryMode === option.value" class="h-2 w-2 rounded-full bg-primary" />
@@ -1471,7 +1632,16 @@ defineExpose({
</div>
<div v-else-if="editExpiryMode === 'lease'" class="grid gap-2 md:grid-cols-[160px_1fr] md:items-center">
<Label for="kv-edit-lease">{{ labels.leaseId || "Lease ID" }}</Label>
<Input id="kv-edit-lease" v-model="editLeaseId" class="h-10 font-mono" inputmode="numeric" :placeholder="labels.leasePlaceholder || 'Existing Lease ID'" />
<div class="grid gap-2">
<Select v-if="leaseOptions.length" :model-value="editLeaseId" @update:model-value="(value) => (editLeaseId = String(value))">
<SelectTrigger class="h-10 font-mono"><SelectValue :placeholder="labels.selectExistingLease || 'Select an existing Lease'" /></SelectTrigger>
<SelectContent
><SelectItem v-for="lease in leaseOptions" :key="lease.id" :value="String(lease.id)">{{ lease.id }} · TTL {{ lease.ttl }}s</SelectItem></SelectContent
>
</Select>
<Input id="kv-edit-lease" v-model="editLeaseId" class="h-10 font-mono" inputmode="numeric" :placeholder="leaseOptions.length ? labels.enterLeaseId || 'Or enter a Lease ID manually' : labels.leasePlaceholder || 'Existing Lease ID'" />
<span class="text-xs text-muted-foreground">{{ leaseOptions.length ? labels.leasePickerHint || "Choose a Lease from this session or enter a Lease ID manually." : labels.noLeasePickerHint || "No Lease is available in this session. Enter an ID manually and save." }}</span>
</div>
</div>
<div v-if="showTtlUnavailable" class="text-xs text-amber-700 dark:text-amber-300">
{{ labels.ttlUnavailable }}
@@ -14,17 +14,15 @@ describe("KvKeyBrowser node export", () => {
it("delegates etcd directory export to a fixed-revision recursive scan", () => {
expect(etcdBrowserSource).toContain("exportScope: exportEtcdNodeScope");
expect(etcdBrowserSource).toContain("const scan = await scanConnection(connectionId, request.path)");
expect(etcdBrowserSource).toContain("isKeyInKvExportScope(displayKey(keyValue(entry), entry.key), request)");
expect(etcdBrowserSource).toContain("isKeyInKvExportScope(displayKey(keyValue(entry)), request)");
expect(etcdBrowserSource).toContain("const missingValue = entries.find((entry) => !entry.value)");
});
it("keeps mirror deletes inside the exported directory and compares canonical Key bytes", () => {
expect(etcdBrowserSource).toContain("if (!isKeyInKvExportScope(shown, mirrorScope)");
expect(etcdBrowserSource).toContain("sourceKeys.has(kvValueByteIdentity(bytes))");
it("compares canonical Key bytes without exposing mirror-delete operations", () => {
expect(etcdBrowserSource).toContain("id: `source:${kvValueByteIdentity(source.key)}`");
expect(etcdBrowserSource).not.toContain("id: source.key.data");
expect(etcdBrowserSource).toContain('const mirrorDeleteAvailable = computed(() => transferBundle.value?.scopeKind === "prefix")');
expect(etcdBrowserSource).toContain(':disabled="!mirrorDeleteAvailable || transferLoading || transferApplying"');
expect(etcdBrowserSource).not.toContain("mirrorDeletes");
expect(etcdBrowserSource).not.toContain('operation: "delete"');
});
it("snapshots the target and invalidates stale transfer previews", () => {
@@ -2,7 +2,7 @@
import { computed, ref, watch, nextTick, onUnmounted } from "vue";
import type { CSSProperties } from "vue";
import { useI18n } from "vue-i18n";
import { X, Pin, ChevronDown, Table2, Code2, TableProperties, PencilRuler, KeyRound, Pencil, Package, Lock, Copy, AlertTriangle, Network, Minimize2, Maximize2, Settings, CalendarClock, Activity, Gauge } from "@lucide/vue";
import { X, Pin, ChevronDown, Table2, Code2, TableProperties, PencilRuler, KeyRound, Pencil, Package, Lock, Copy, AlertTriangle, Network, Minimize2, Maximize2, Settings, CalendarClock, Activity, Gauge, ShieldCheck } from "@lucide/vue";
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
@@ -480,6 +480,7 @@ function tabMenuIcon(tab: QueryTab) {
if (tab.mode === "vector") return TableProperties;
if (tab.mode === "etcd" || tab.mode === "zookeeper") return KeyRound;
if (tab.mode === "etcd-dashboard") return Gauge;
if (tab.mode === "etcd-access-control") return ShieldCheck;
if (tab.mode === "nacos") return Network;
if (tab.mode === "objects") return TableProperties;
if (tab.mode === "structure") return PencilRuler;
@@ -624,6 +625,7 @@ function onOverflowItemKeydown(event: KeyboardEvent, tabId: string, kind: "regul
<TableProperties v-else-if="tab.mode === 'vector'" class="h-3.5 w-3.5" />
<KeyRound v-else-if="tab.mode === 'etcd' || tab.mode === 'zookeeper'" class="h-3.5 w-3.5" />
<Gauge v-else-if="tab.mode === 'etcd-dashboard'" class="h-3.5 w-3.5" />
<ShieldCheck v-else-if="tab.mode === 'etcd-access-control'" class="h-3.5 w-3.5" />
<Network v-else-if="tab.mode === 'nacos'" class="h-3.5 w-3.5" />
<TableProperties v-else-if="tab.mode === 'objects'" class="h-3.5 w-3.5" />
<PencilRuler v-else-if="tab.mode === 'structure'" class="h-3.5 w-3.5" />
@@ -818,6 +820,7 @@ function onOverflowItemKeydown(event: KeyboardEvent, tabId: string, kind: "regul
<TableProperties v-else-if="tab.mode === 'vector'" class="h-3.5 w-3.5" />
<KeyRound v-else-if="tab.mode === 'etcd' || tab.mode === 'zookeeper'" class="h-3.5 w-3.5" />
<Gauge v-else-if="tab.mode === 'etcd-dashboard'" class="h-3.5 w-3.5" />
<ShieldCheck v-else-if="tab.mode === 'etcd-access-control'" class="h-3.5 w-3.5" />
<Network v-else-if="tab.mode === 'nacos'" class="h-3.5 w-3.5" />
<TableProperties v-else-if="tab.mode === 'objects'" class="h-3.5 w-3.5" />
<PencilRuler v-else-if="tab.mode === 'structure'" class="h-3.5 w-3.5" />
@@ -46,6 +46,7 @@ const RedisKeyBrowser = defineAsyncComponent(() => import("@/components/redis/Re
const RedisDashboard = defineAsyncComponent(() => import("@/components/redis/RedisDashboard.vue"));
const EtcdKeyBrowser = defineAsyncComponent(() => import("@/components/etcd/EtcdKeyBrowser.vue"));
const EtcdDashboard = defineAsyncComponent(() => import("@/components/etcd/EtcdDashboard.vue"));
const EtcdAccessControl = defineAsyncComponent(() => import("@/components/etcd/EtcdAccessControl.vue"));
const ZooKeeperKeyBrowser = defineAsyncComponent(() => import("@/components/zookeeper/ZooKeeperKeyBrowser.vue"));
const DocumentBrowser = defineAsyncComponent(() => import("@/components/document/DocumentBrowser.vue"));
const MongoGridFsBrowser = defineAsyncComponent(() => import("@/components/document/MongoGridFsBrowser.vue"));
@@ -1875,6 +1876,12 @@ defineExpose({ focusSearch, refreshData, refreshQueryEditorCompletionCache, hand
</div>
</template>
<template v-else-if="activeTab.mode === 'etcd-access-control'">
<div class="flex-1 min-h-0">
<EtcdAccessControl :key="activeTab.id" :connection-id="activeTab.connectionId" />
</div>
</template>
<!-- ZooKeeper mode: znode browser -->
<template v-else-if="activeTab.mode === 'zookeeper'">
<div class="flex-1 min-h-0">
@@ -1039,7 +1039,7 @@ function resolveLoadedLocateTarget(target: ActiveTabSidebarTarget, candidate: Qu
}
async function ensureTreeLoadedForTarget(target: ActiveTabSidebarTarget, opts?: { force?: boolean }) {
if (target.type === "saved-sql-file" || target.type === "etcd-root" || target.type === "etcd-dashboard" || target.type === "zookeeper-root") return;
if (target.type === "saved-sql-file" || target.type === "etcd-root" || target.type === "etcd-dashboard" || target.type === "etcd-access-control" || target.type === "zookeeper-root") return;
const connId = target.connectionId;
if (!connId) return;
@@ -609,6 +609,10 @@ async function toggle() {
await connectionStore.ensureConnected(node.connectionId);
const tabTitle = `${connectionStore.getConfig(node.connectionId)?.name || "etcd"}:dashboard`;
queryStore.createTab(node.connectionId, "", tabTitle, "etcd-dashboard");
} else if (node.type === "etcd-access-control" && node.connectionId) {
await connectionStore.ensureConnected(node.connectionId);
const tabTitle = `${connectionStore.getConfig(node.connectionId)?.name || "etcd"}:access-control`;
queryStore.createTab(node.connectionId, "", tabTitle, "etcd-access-control");
} else if (node.type === "zookeeper-root" && node.connectionId) {
await connectionStore.ensureConnected(node.connectionId);
const tabTitle = `${connectionStore.getConfig(node.connectionId)?.name || "ZooKeeper"}:keys`;
@@ -4091,7 +4095,7 @@ function buildSpecialSidebarMenu(context: SidebarMenuFactoryContext): boolean {
return true;
}
if (node.type === "etcd-root" || node.type === "etcd-dashboard" || node.type === "zookeeper-root") {
if (node.type === "etcd-root" || node.type === "etcd-dashboard" || node.type === "etcd-access-control" || node.type === "zookeeper-root") {
items.push({ label: t("contextMenu.openConnection"), action: toggle, icon: Database });
return true;
}
@@ -30,6 +30,7 @@ import {
UsersRound,
CalendarClock,
Gauge,
ShieldCheck,
Lock,
Archive,
Square,
@@ -257,6 +258,8 @@ function getIconInfo(node: TreeNode): { icon: any; colorClass: string } | null {
return { icon: Database, colorClass: "text-sky-500" };
case "etcd-dashboard":
return { icon: Gauge, colorClass: "text-sky-500" };
case "etcd-access-control":
return { icon: ShieldCheck, colorClass: "text-sky-500" };
case "zookeeper-root":
return { icon: Database, colorClass: "text-blue-500" };
case "mongo-db":