Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat: ZK 节点树改为真正懒加载 (#1987)

miraclede39c1662db7
diff --git a/agents/drivers/zookeeper/src/test/java/com/dbx/agent/zookeeper/ZooKeeperAgentTest.java b/agents/drivers/zookeeper/src/test/java/com/dbx/agent/zookeeper/ZooKeeperAgentTest.java
index 94ba12250b..83ea7d8dd4 100644
--- a/agents/drivers/zookeeper/src/test/java/com/dbx/agent/zookeeper/ZooKeeperAgentTest.java
+++ b/agents/drivers/zookeeper/src/test/java/com/dbx/agent/zookeeper/ZooKeeperAgentTest.java
@@ -465,6 +465,29 @@ final class ZooKeeperAgentTest {
}
}
+ @Test
+ void listPrefixPaginatesDirectChildrenWhenRecursiveIsFalse() throws Exception {
+ try (TestingServer server = new TestingServer()) {
+ connect(server);
+ result(request(2, "kv_put", "{\"key\":\"/app/c/deep\",\"value\":{\"encoding\":\"utf8\",\"data\":\"c\"}}"));
+ result(request(3, "kv_put", "{\"key\":\"/app/a/deep\",\"value\":{\"encoding\":\"utf8\",\"data\":\"a\"}}"));
+ result(request(4, "kv_put", "{\"key\":\"/app/b/deep\",\"value\":{\"encoding\":\"utf8\",\"data\":\"b\"}}"));
+
+ JsonObject first = result(request(5, "kv_list_prefix", "{\"prefix\":\"/app\",\"recursive\":false,\"limit\":2}"));
+ String continuation = first.get("continuation").getAsString();
+ JsonObject second = result(request(
+ 6,
+ "kv_list_prefix",
+ "{\"prefix\":\"/app\",\"recursive\":false,\"limit\":2,\"continuation\":\"" + continuation + "\"}"
+ ));
+
+ Assertions.assertEquals(List.of("/app/a", "/app/b"), listedKeys(first));
+ Assertions.assertFalse(continuation.isBlank());
+ Assertions.assertEquals(List.of("/app/c"), listedKeys(second));
+ Assertions.assertTrue(second.get("continuation").isJsonNull());
+ }
+ }
+
@Test
void listPrefixRejectsContinuationForDifferentRequest() throws Exception {
try (TestingServer server = new TestingServer()) {
diff --git a/apps/desktop/src/components/kv/KvKeyBrowser.vue b/apps/desktop/src/components/kv/KvKeyBrowser.vue
index 581bbecedd..ee9de8c7b4 100644
--- a/apps/desktop/src/components/kv/KvKeyBrowser.vue
+++ b/apps/desktop/src/components/kv/KvKeyBrowser.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { computed, onMounted, ref, watch } from "vue";
+import { computed, onMounted, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { ChevronDown, ChevronRight, FolderClosed, FolderOpen, KeyRound, Loader2, Plus, RefreshCw, Search, Trash2 } from "@lucide/vue";
import { Button } from "@/components/ui/button";
@@ -10,10 +10,11 @@ import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
-import type { KvCreateMode, KvGetResponse, KvKeySummary, KvPutOptions, KvPutResponse, KvValue } from "@/lib/api";
+import type { KvCreateMode, KvGetResponse, KvKeySummary, KvListPrefixOptions, KvPutOptions, KvPutResponse, KvValue } from "@/lib/api";
import { buildKvKeyTree, flattenVisibleKvKeyTree, preserveKvExpandedGroupIds, type KvKeyTreeNode } from "@/lib/kvKeyTree";
import { refreshedKvSelectionKey } from "@/lib/kvRefreshSelection";
import { formatZooKeeperMetadataRows, formatZooKeeperSummaryBadges, prettyPrintJsonText } from "@/lib/kvValueDisplay";
+import { createLazyKvKeyTreeState, flattenLazyKvKeyTree, lazyExpandedKeyFromId, normalizeZooKeeperPath, parentZooKeeperPath, replaceLazyKvChildren, replaceLazyKvFocusedRoot, resetLazyKvKeyTree, type LazyKvKeyTreeNode, type LazyKvKeyTreeRow } from "@/lib/zookeeperLazyKeyTree";
import { useToast } from "@/composables/useToast";
interface KvKeyBrowserLabels {
@@ -52,12 +53,15 @@ interface KvCreateModeOption {
}
interface KvKeyBrowserApi {
- listPrefix: (connectionId: string, prefix: string, limit: number, continuation?: string | null) => Promise<{ keys: KvKeySummary[]; continuation?: string | null }>;
+ listPrefix: (connectionId: string, prefix: string, limit: number, continuation?: string | null, options?: KvListPrefixOptions | null) => Promise<{ keys: KvKeySummary[]; continuation?: string | null }>;
get: (connectionId: string, key: string) => Promise<KvGetResponse>;
put: (connectionId: string, key: string, value: KvValue, options?: KvPutOptions | null) => Promise<KvPutResponse>;
deleteKey: (connectionId: string, key: string) => Promise<{ deleted: number }>;
}
+type BrowserTreeNode = KvKeyTreeNode | LazyKvKeyTreeNode;
+type BrowserTreeRow = { type: "node"; node: BrowserTreeNode; depth: number } | LazyKvKeyTreeRow;
+
const props = withDefaults(
defineProps<{
connectionId: string;
@@ -67,12 +71,14 @@ const props = withDefaults(
createModeOptions?: KvCreateModeOption[];
enableNodeActions?: boolean;
metadataStyle?: "default" | "zookeeper";
+ lazyHierarchy?: boolean;
}>(),
{
supportsCreateModes: false,
createModeOptions: () => [],
enableNodeActions: false,
metadataStyle: "default",
+ lazyHierarchy: false,
},
);
@@ -99,14 +105,18 @@ const showDeleteConfirm = ref(false);
const deleting = ref(false);
const selectedCreateMode = ref<KvCreateMode>("persistent");
const selectedPrettyValue = ref<string | null>(null);
+const lazyTreeState = reactive(createLazyKvKeyTreeState());
const pageSize = 200;
type LoadKeysOptions = {
preserveSelection?: boolean;
};
const tree = computed(() => buildKvKeyTree(keys.value));
-const visibleRows = computed(() => flattenVisibleKvKeyTree(tree.value, expandedGroupIds.value));
-const selectedMetadata = computed(() => selectedValue.value?.metadata ?? keys.value.find((key) => key.key === selectedKey.value));
+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 }));
+});
+const selectedMetadata = computed(() => selectedValue.value?.metadata ?? (props.lazyHierarchy && selectedKey.value ? lazyTreeState.nodeByKey.get(selectedKey.value) : keys.value.find((key) => key.key === selectedKey.value)));
const selectedTextValue = computed(() => {
const value = selectedValue.value?.value;
if (!value) return "";
@@ -132,6 +142,11 @@ function preserveExpandedGroups(expandAll = false) {
}
async function loadKeys(reset = true, options: LoadKeysOptions = {}) {
+ if (props.lazyHierarchy) {
+ await loadLazyRoot(reset, options);
+ return;
+ }
+
const keyToRestore = options.preserveSelection ? selectedKey.value : null;
if (reset) {
loading.value = true;
@@ -166,6 +181,150 @@ async function loadKeys(reset = true, options: LoadKeysOptions = {}) {
}
}
+async function loadLazyRoot(reset = true, options: LoadKeysOptions = {}) {
+ const keyToRestore = options.preserveSelection ? selectedKey.value : null;
+ if (!reset) {
+ await loadMoreLazyChildren(null);
+ return;
+ }
+
+ const previousExpanded = new Set(expandedGroupIds.value);
+ loading.value = true;
+ loadingMore.value = false;
+ if (!options.preserveSelection) {
+ selectedKey.value = null;
+ selectedValue.value = null;
+ }
+
+ try {
+ const rootPath = normalizeZooKeeperPath(prefix.value);
+ resetLazyKvKeyTree(lazyTreeState, rootPath);
+ const result = await props.api.listPrefix(props.connectionId, rootPath, pageSize, null, { recursive: false });
+ if (rootPath === "/") {
+ replaceLazyKvChildren(lazyTreeState, null, result.keys, result.continuation);
+ } else {
+ const rootSummary = await loadLazyRootSummary(rootPath, result.keys, result.continuation);
+ if (rootSummary) {
+ replaceLazyKvFocusedRoot(lazyTreeState, rootSummary, result.keys, result.continuation);
+ } else {
+ replaceLazyKvChildren(lazyTreeState, null, result.keys, result.continuation);
+ }
+ }
+
+ if (options.preserveSelection) {
+ await restoreLazyExpandedBranches(previousExpanded);
+ expandFocusedRoot(rootPath);
+ if (keyToRestore && lazyTreeState.nodeByKey.has(keyToRestore)) {
+ await loadSelectedKey(keyToRestore);
+ } else {
+ selectedKey.value = null;
+ selectedValue.value = null;
+ }
+ } else {
+ expandedGroupIds.value = focusedRootExpansion(rootPath);
+ }
+ } finally {
+ loading.value = false;
+ }
+}
+
+async function loadLazyRootSummary(rootPath: string, children: KvKeySummary[], continuation?: string | null): Promise<KvKeySummary | null> {
+ try {
+ const rootValue = await props.api.get(props.connectionId, rootPath);
+ if (rootValue.found) return { key: rootValue.key || rootPath, ...(rootValue.metadata ?? {}) };
+ if (children.length === 0 && !continuation) return null;
+ } catch {
+ if (children.length === 0 && !continuation) return null;
+ }
+ return { key: rootPath, numChildren: children.length + (continuation ? 1 : 0) };
+}
+
+function focusedRootExpansion(rootPath: string): Set<string> {
+ const normalized = normalizeZooKeeperPath(rootPath);
+ if (normalized === "/") return new Set();
+ return new Set(
+ focusedPathKeys(normalized)
+ .filter((key) => lazyTreeState.nodeByKey.has(key))
+ .map((key) => `lazy:${key}`),
+ );
+}
+
+function expandFocusedRoot(rootPath: string) {
+ expandedGroupIds.value = new Set([...expandedGroupIds.value, ...focusedRootExpansion(rootPath)]);
+}
+
+function focusedPathKeys(rootPath: string): string[] {
+ const segments = normalizeZooKeeperPath(rootPath).split("/").filter(Boolean);
+ return segments.map((_, index) => `/${segments.slice(0, index + 1).join("/")}`);
+}
+
+async function restoreLazyExpandedBranches(previousExpanded: ReadonlySet<string>) {
+ const restored = new Set<string>();
+ const keysToExpand = [...previousExpanded]
+ .map((id) => lazyExpandedKeyFromId(id))
+ .filter((key): key is string => !!key)
+ .sort((a, b) => a.split("/").length - b.split("/").length);
+
+ for (const key of keysToExpand) {
+ const node = lazyTreeState.nodeByKey.get(key);
+ if (!node?.hasChildren) continue;
+ restored.add(node.id);
+ await loadLazyChildren(key, true);
+ }
+
+ expandedGroupIds.value = restored;
+}
+
+async function loadLazyChildren(parentKey: string, reset = true) {
+ const node = lazyTreeState.nodeByKey.get(parentKey);
+ if (!node || node.loading) return;
+ node.loading = true;
+ try {
+ const continuationToUse = reset ? null : node.continuation;
+ const result = await props.api.listPrefix(props.connectionId, parentKey, pageSize, continuationToUse, { recursive: false });
+ replaceLazyKvChildren(lazyTreeState, parentKey, result.keys, result.continuation, { append: !reset });
+ } finally {
+ const latest = lazyTreeState.nodeByKey.get(parentKey);
+ if (latest) latest.loading = false;
+ }
+}
+
+async function loadMoreLazyChildren(parentKey: string | null) {
+ if (parentKey) {
+ await loadLazyChildren(parentKey, false);
+ return;
+ }
+
+ if (loadingMore.value || !lazyTreeState.rootContinuation) return;
+ loadingMore.value = true;
+ try {
+ const result = await props.api.listPrefix(props.connectionId, lazyTreeState.rootPath, pageSize, lazyTreeState.rootContinuation, { recursive: false });
+ replaceLazyKvChildren(lazyTreeState, null, result.keys, result.continuation, { append: true });
+ } finally {
+ loadingMore.value = false;
+ }
+}
+
+async function refreshLazyParent(parentPath: string) {
+ const normalizedParent = normalizeZooKeeperPath(parentPath);
+ if (normalizedParent === lazyTreeState.rootPath) {
+ if (lazyTreeState.rootPath === "/") {
+ const result = await props.api.listPrefix(props.connectionId, lazyTreeState.rootPath, pageSize, null, { recursive: false });
+ replaceLazyKvChildren(lazyTreeState, null, result.keys, result.continuation);
+ } else {
+ await loadLazyChildren(lazyTreeState.rootPath, true);
+ expandFocusedRoot(lazyTreeState.rootPath);
+ }
+ return;
+ }
+
+ if (lazyTreeState.nodeByKey.has(normalizedParent)) {
+ await loadLazyChildren(normalizedParent, true);
+ } else {
+ await loadLazyRoot(true, { preserveSelection: true });
+ }
+}
+
async function loadSelectedKey(key: string) {
selectedKey.value = key;
selectedPrettyValue.value = null;
@@ -180,36 +339,43 @@ async function loadSelectedKey(key: string) {
}
}
-function toggleGroup(node: KvKeyTreeNode) {
- if (node.kind !== "group") return;
+async function toggleGroup(node: BrowserTreeNode) {
+ if (!nodeIsExpandable(node)) return;
const next = new Set(expandedGroupIds.value);
- if (next.has(node.id)) next.delete(node.id);
- else next.add(node.id);
+ if (next.has(node.id)) {
+ next.delete(node.id);
+ } else {
+ next.add(node.id);
+ if (node.kind === "lazy" && node.hasChildren && !node.loaded) {
+ void loadLazyChildren(node.key, true);
+ }
+ }
expandedGroupIds.value = next;
}
-function nodePath(node: KvKeyTreeNode): string {
+function nodePath(node: BrowserTreeNode): string {
+ if (node.kind === "lazy") return node.key;
if (node.kind === "leaf") return node.key;
return `/${node.pathSegments.join("/")}`;
}
-function onRowClick(node: KvKeyTreeNode) {
- if (node.kind === "group") {
- toggleGroup(node);
+function onRowClick(node: BrowserTreeNode) {
+ if (nodeIsExpandable(node)) {
+ void toggleGroup(node);
if (props.enableNodeActions) void loadSelectedKey(nodePath(node));
} else {
- void loadSelectedKey(node.key);
+ void loadSelectedKey(nodePath(node));
}
}
-function onRowDoubleClick(node: KvKeyTreeNode) {
- if (node.kind === "leaf") {
- void loadSelectedKey(node.key).then(() => openEditDialog());
+function onRowDoubleClick(node: BrowserTreeNode) {
+ if (!nodeIsExpandable(node)) {
+ void loadSelectedKey(nodePath(node)).then(() => openEditDialog());
}
}
function createKeyPrefix(parentPath?: string): string {
- const path = parentPath ?? prefix.value.trim();
+ const path = props.lazyHierarchy ? normalizeZooKeeperPath(parentPath ?? prefix.value) : (parentPath ?? prefix.value.trim());
if (!path) return "";
if (path === "/") return "/";
return path.endsWith("/") ? path : `${path}/`;
@@ -254,7 +420,11 @@ async function saveKey() {
const response = await props.api.put(props.connectionId, key, value, putOptions());
const keyToSelect = response.createdKey || response.key || key;
showEditDialog.value = false;
- await loadKeys(true);
+ if (props.lazyHierarchy) {
+ await refreshLazyParent(parentZooKeeperPath(keyToSelect));
+ } else {
+ await loadKeys(true);
+ }
await loadSelectedKey(keyToSelect);
toast(props.labels.saved, 2500);
} catch (error) {
@@ -266,31 +436,36 @@ async function saveKey() {
async function deleteSelectedKey() {
if (!selectedKey.value) return;
+ const parentPath = parentZooKeeperPath(selectedKey.value);
deleting.value = true;
try {
await props.api.deleteKey(props.connectionId, selectedKey.value);
showDeleteConfirm.value = false;
selectedKey.value = null;
selectedValue.value = null;
- await loadKeys(true);
+ if (props.lazyHierarchy) {
+ await refreshLazyParent(parentPath);
+ } else {
+ await loadKeys(true);
+ }
toast(props.labels.deleted, 2500);
} finally {
deleting.value = false;
}
}
-function selectNodeForAction(node: KvKeyTreeNode) {
+function selectNodeForAction(node: BrowserTreeNode) {
const key = nodePath(node);
if (selectedKey.value !== key) void loadSelectedKey(key);
else selectedKey.value = key;
}
-function openDeleteForNode(node: KvKeyTreeNode) {
+function openDeleteForNode(node: BrowserTreeNode) {
selectNodeForAction(node);
showDeleteConfirm.value = true;
}
-function nodeContextMenuItems(node: KvKeyTreeNode): ContextMenuItem[] {
+function nodeContextMenuItems(node: BrowserTreeNode): ContextMenuItem[] {
if (!props.enableNodeActions) return [];
return [
{
@@ -307,16 +482,28 @@ function nodeContextMenuItems(node: KvKeyTreeNode): ContextMenuItem[] {
];
}
-function onRowContextMenu(event: MouseEvent, node: KvKeyTreeNode, openContextMenu: (event: MouseEvent) => void) {
+function onRowContextMenu(event: MouseEvent, node: BrowserTreeNode, openContextMenu: (event: MouseEvent) => void) {
if (!props.enableNodeActions) return;
selectNodeForAction(node);
openContextMenu(event);
}
-function rowIsSelected(node: KvKeyTreeNode): boolean {
+function rowIsSelected(node: BrowserTreeNode): boolean {
return nodePath(node) === selectedKey.value;
}
+function nodeIsExpandable(node: BrowserTreeNode): boolean {
+ return node.kind === "group" || (node.kind === "lazy" && node.hasChildren);
+}
+
+function nodeIsExpanded(node: BrowserTreeNode): boolean {
+ return expandedGroupIds.value.has(node.id);
+}
+
+function nodeIsLoading(node: BrowserTreeNode): boolean {
+ return node.kind === "lazy" && node.loading;
+}
+
function prettifySelectedJson() {
const result = prettyPrintJsonText(selectedTextValue.value);
if (result.ok && result.value != null) {
@@ -397,30 +584,39 @@ defineExpose({ focusSearch, refresh });
{{ labels.empty }}
</div>
<div v-else class="h-full overflow-auto py-1 text-sm">
- <CustomContextMenu v-for="row in visibleRows" :key="row.node.id" :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) }"
- :style="{ paddingLeft: `${8 + row.depth * 18}px` }"
- @click="onRowClick(row.node)"
- @dblclick.stop.prevent="onRowDoubleClick(row.node)"
- @contextmenu="(event) => onRowContextMenu(event, row.node, onContextMenu)"
- >
- <template v-if="row.node.kind === 'group'">
- <ChevronDown v-if="expandedGroupIds.has(row.node.id)" class="h-3.5 w-3.5 shrink-0" />
- <ChevronRight v-else class="h-3.5 w-3.5 shrink-0" />
- <FolderOpen v-if="expandedGroupIds.has(row.node.id)" class="h-4 w-4 shrink-0 text-sky-500" />
- <FolderClosed v-else class="h-4 w-4 shrink-0 text-sky-500" />
- </template>
- <template v-else>
- <span class="w-3.5 shrink-0" />
- <KeyRound class="h-4 w-4 shrink-0 text-sky-500" />
- </template>
- <span class="truncate">{{ row.node.label }}</span>
- </button>
- </CustomContextMenu>
- <div v-if="continuation" class="border-t p-2">
+ <template v-for="row in visibleRows" :key="row.type === 'node' ? row.node.id : row.id">
+ <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) }"
+ :style="{ paddingLeft: `${8 + row.depth * 18}px` }"
+ @click="onRowClick(row.node)"
+ @dblclick.stop.prevent="onRowDoubleClick(row.node)"
+ @contextmenu="(event) => onRowContextMenu(event, row.node, onContextMenu)"
+ >
+ <template v-if="nodeIsExpandable(row.node)">
+ <Loader2 v-if="nodeIsLoading(row.node)" class="h-3.5 w-3.5 shrink-0 animate-spin" />
+ <ChevronDown v-else-if="nodeIsExpanded(row.node)" class="h-3.5 w-3.5 shrink-0" />
+ <ChevronRight v-else class="h-3.5 w-3.5 shrink-0" />
+ <FolderOpen v-if="nodeIsExpanded(row.node)" class="h-4 w-4 shrink-0 text-sky-500" />
+ <FolderClosed v-else class="h-4 w-4 shrink-0 text-sky-500" />
+ </template>
+ <template v-else>
+ <span class="w-3.5 shrink-0" />
+ <KeyRound class="h-4 w-4 shrink-0 text-sky-500" />
+ </template>
+ <span class="truncate">{{ row.node.label }}</span>
+ </button>
+ </CustomContextMenu>
+ <div v-else class="px-2 py-1" :style="{ paddingLeft: `${8 + row.depth * 18}px` }">
+ <Button size="sm" variant="outline" class="h-7 w-full gap-1.5" :disabled="row.loading || loadingMore" @click="loadMoreLazyChildren(row.parentKey)">
+ <Loader2 v-if="row.loading || (row.parentKey === null && loadingMore)" class="h-3.5 w-3.5 animate-spin" />
+ {{ labels.loadMore }}
+ </Button>
+ </div>
+ </template>
+ <div v-if="!lazyHierarchy && continuation" class="border-t p-2">
<Button size="sm" variant="outline" class="h-8 w-full gap-1.5" :disabled="loadingMore" @click="loadKeys(false)">
<Loader2 v-if="loadingMore" class="h-3.5 w-3.5 animate-spin" />
{{ labels.loadMore }}
diff --git a/apps/desktop/src/components/zookeeper/ZooKeeperKeyBrowser.vue b/apps/desktop/src/components/zookeeper/ZooKeeperKeyBrowser.vue
index ab36c8ce16..a3a9d64688 100644
--- a/apps/desktop/src/components/zookeeper/ZooKeeperKeyBrowser.vue
+++ b/apps/desktop/src/components/zookeeper/ZooKeeperKeyBrowser.vue
@@ -66,5 +66,5 @@ defineExpose({ focusSearch, refresh });
</script>
<template>
- <KvKeyBrowser ref="browserRef" :connection-id="props.connectionId" :api="zookeeperApi" :labels="labels" supports-create-modes enable-node-actions metadata-style="zookeeper" :create-mode-options="createModeOptions" />
+ <KvKeyBrowser ref="browserRef" :connection-id="props.connectionId" :api="zookeeperApi" :labels="labels" supports-create-modes enable-node-actions metadata-style="zookeeper" lazy-hierarchy :create-mode-options="createModeOptions" />
</template>
diff --git a/apps/desktop/src/lib/__tests__/zookeeperApiContract.spec.ts b/apps/desktop/src/lib/__tests__/zookeeperApiContract.spec.ts
index 3954c0b1f6..419b673be5 100644
--- a/apps/desktop/src/lib/__tests__/zookeeperApiContract.spec.ts
+++ b/apps/desktop/src/lib/__tests__/zookeeperApiContract.spec.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { zookeeperDelete, zookeeperGet, zookeeperListPrefix, zookeeperPut, type KvPutOptions, type KvPutResponse } from "../api";
+import { zookeeperDelete, zookeeperGet, zookeeperListPrefix, zookeeperPut, type KvListPrefixOptions, type KvPutOptions, type KvPutResponse } from "../api";
import type { DatabaseType } from "@/types/database";
describe("zookeeper frontend API contract", () => {
@@ -13,9 +13,13 @@ describe("zookeeper frontend API contract", () => {
key: "/sessions/member-0000000001",
createdKey: "/sessions/member-0000000001",
};
+ const listOptions: KvListPrefixOptions = {
+ recursive: false,
+ };
expect(dbType).toBe("zookeeper");
expect(options.createMode).toBe("ephemeral_sequential");
+ expect(listOptions.recursive).toBe(false);
expect(response.createdKey).toBe(response.key);
expect(typeof zookeeperListPrefix).toBe("function");
expect(typeof zookeeperGet).toBe("function");
diff --git a/apps/desktop/src/lib/__tests__/zookeeperLazyKeyTree.spec.ts b/apps/desktop/src/lib/__tests__/zookeeperLazyKeyTree.spec.ts
new file mode 100644
index 0000000000..363401240a
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/zookeeperLazyKeyTree.spec.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from "vitest";
+import { createLazyKvKeyTreeState, flattenLazyKvKeyTree, replaceLazyKvChildren, resetLazyKvKeyTree } from "../zookeeperLazyKeyTree";
+
+describe("zookeeper lazy key tree", () => {
+ it("stores only the current path direct children on reset", () => {
+ const state = createLazyKvKeyTreeState();
+
+ resetLazyKvKeyTree(state, "/app");
+ replaceLazyKvChildren(
+ state,
+ null,
+ [
+ { key: "/app/a", numChildren: 0, valueSize: 1 },
+ { key: "/app/folder", numChildren: 2, valueSize: 0 },
+ ],
+ null,
+ );
+
+ expect(state.rootPath).toBe("/app");
+ expect(state.roots.map((node) => node.key)).toEqual(["/app/a", "/app/folder"]);
+ expect(flattenLazyKvKeyTree(state, new Set()).map((row) => `${row.depth}:${row.node.label}`)).toEqual(["0:a", "0:folder"]);
+ });
+
+ it("does not expose grandchildren until their parent is loaded", () => {
+ const state = createLazyKvKeyTreeState("/");
+ replaceLazyKvChildren(state, null, [{ key: "/app", numChildren: 1 }], null);
+
+ expect(flattenLazyKvKeyTree(state, new Set(["lazy:/app"])).map((row) => row.node.key)).toEqual(["/app"]);
+
+ replaceLazyKvChildren(state, "/app", [{ key: "/app/name", numChildren: 0 }], null);
+
+ expect(flattenLazyKvKeyTree(state, new Set(["lazy:/app"])).map((row) => row.node.key)).toEqual(["/app", "/app/name"]);
+ });
+
+ it("keeps child pagination continuation on the owning node", () => {
+ const state = createLazyKvKeyTreeState("/");
+ replaceLazyKvChildren(state, null, [{ key: "/app", numChildren: 3 }], "root-next");
+ replaceLazyKvChildren(state, "/app", [{ key: "/app/a", numChildren: 0 }], "child-next");
+
+ const app = state.nodeByKey.get("/app");
+
+ expect(state.rootContinuation).toBe("root-next");
+ expect(app?.continuation).toBe("child-next");
+ });
+});
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index 2e73bad3e3..87e56c3d22 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -443,6 +443,7 @@ export type {
KvKeyMetadata,
KvKeySummary,
KvListPrefixResponse,
+ KvListPrefixOptions,
KvGetResponse,
KvWriteMode,
KvCreateMode,
diff --git a/apps/desktop/src/lib/http.ts b/apps/desktop/src/lib/http.ts
index a25b3383bd..9c4aa01e1a 100644
--- a/apps/desktop/src/lib/http.ts
+++ b/apps/desktop/src/lib/http.ts
@@ -58,6 +58,7 @@ import type {
RedisNodeEndpoint,
KvValue,
KvListPrefixResponse,
+ KvListPrefixOptions,
KvGetResponse,
KvPutOptions,
KvPutResponse,
@@ -1602,8 +1603,8 @@ export async function etcdDelete(connectionId: string, key: string): Promise<KvD
// ZooKeeper
// ---------------------------------------------------------------------------
-export async function zookeeperListPrefix(connectionId: string, prefix: string, limit: number, continuation?: string | null): Promise<KvListPrefixResponse> {
- return post("/api/zookeeper/list-prefix", { connectionId, prefix, limit, continuation });
+export async function zookeeperListPrefix(connectionId: string, prefix: string, limit: number, continuation?: string | null, options?: KvListPrefixOptions | null): Promise<KvListPrefixResponse> {
+ return post("/api/zookeeper/list-prefix", { connectionId, prefix, limit, continuation, recursive: options?.recursive ?? null });
}
export async function zookeeperGet(connectionId: string, key: string): Promise<KvGetResponse> {
diff --git a/apps/desktop/src/lib/tauri.ts b/apps/desktop/src/lib/tauri.ts
index a44769a393..779f2f2259 100644
--- a/apps/desktop/src/lib/tauri.ts
+++ b/apps/desktop/src/lib/tauri.ts
@@ -1346,6 +1346,10 @@ export interface KvListPrefixResponse {
revision?: number | null;
}
+export interface KvListPrefixOptions {
+ recursive?: boolean | null;
+}
+
export interface KvGetResponse {
found: boolean;
key?: string | null;
@@ -1391,8 +1395,8 @@ export async function etcdDelete(connectionId: string, key: string): Promise<KvD
}
// --- ZooKeeper ---
-export async function zookeeperListPrefix(connectionId: string, prefix: string, limit: number, continuation?: string | null): Promise<KvListPrefixResponse> {
- return invoke("zookeeper_list_prefix", { connectionId, prefix, limit, continuation });
+export async function zookeeperListPrefix(connectionId: string, prefix: string, limit: number, continuation?: string | null, options?: KvListPrefixOptions | null): Promise<KvListPrefixResponse> {
+ return invoke("zookeeper_list_prefix", { connectionId, prefix, limit, continuation, recursive: options?.recursive ?? null });
}
export async function zookeeperGet(connectionId: string, key: string): Promise<KvGetResponse> {
diff --git a/apps/desktop/src/lib/zookeeperLazyKeyTree.ts b/apps/desktop/src/lib/zookeeperLazyKeyTree.ts
new file mode 100644
index 0000000000..b4b6a746f4
--- /dev/null
+++ b/apps/desktop/src/lib/zookeeperLazyKeyTree.ts
@@ -0,0 +1,187 @@
+import type { KvKeyMetadata, KvKeySummary } from "./api";
+
+export interface LazyKvKeyTreeNode extends KvKeyMetadata {
+ kind: "lazy";
+ id: string;
+ label: string;
+ key: string;
+ pathSegments: string[];
+ hasChildren: boolean;
+ children: LazyKvKeyTreeNode[];
+ loaded: boolean;
+ loading: boolean;
+ continuation: string | null;
+}
+
+export interface LazyKvKeyTreeState {
+ rootPath: string;
+ roots: LazyKvKeyTreeNode[];
+ rootContinuation: string | null;
+ nodeByKey: Map<string, LazyKvKeyTreeNode>;
+}
+
+export type LazyKvKeyTreeRow =
+ | {
+ type: "node";
+ node: LazyKvKeyTreeNode;
+ depth: number;
+ }
+ | {
+ type: "loadMore";
+ id: string;
+ parentKey: string | null;
+ depth: number;
+ loading: boolean;
+ };
+
+export function normalizeZooKeeperPath(path: string): string {
+ const trimmed = path.trim();
+ if (!trimmed || trimmed === "/") return "/";
+ const withSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
+ return withSlash.replace(/\/+$/, "") || "/";
+}
+
+export function parentZooKeeperPath(path: string): string {
+ const normalized = normalizeZooKeeperPath(path);
+ if (normalized === "/") return "/";
+ const parent = normalized.slice(0, normalized.lastIndexOf("/"));
+ return parent || "/";
+}
+
+export function createLazyKvKeyTreeState(rootPath = "/"): LazyKvKeyTreeState {
+ return {
+ rootPath: normalizeZooKeeperPath(rootPath),
+ roots: [],
+ rootContinuation: null,
+ nodeByKey: new Map(),
+ };
+}
+
+export function resetLazyKvKeyTree(state: LazyKvKeyTreeState, rootPath = "/") {
+ state.rootPath = normalizeZooKeeperPath(rootPath);
+ state.roots = [];
+ state.rootContinuation = null;
+ state.nodeByKey.clear();
+}
+
+export function replaceLazyKvChildren(state: LazyKvKeyTreeState, parentKey: string | null, keys: KvKeySummary[], continuation: string | null | undefined, options: { append?: boolean } = {}) {
+ const previous = new Map(state.nodeByKey);
+ const nextChildren = keys.map((key) => lazyNodeFromSummary(key, previous.get(key.key)));
+ const children = options.append ? mergeLazyChildren(parentKey ? state.nodeByKey.get(parentKey)?.children || [] : state.roots, nextChildren) : nextChildren;
+
+ if (parentKey) {
+ const parent = state.nodeByKey.get(parentKey);
+ if (!parent) return;
+ parent.children = children;
+ parent.loaded = true;
+ parent.continuation = continuation || null;
+ } else {
+ state.roots = children;
+ state.rootContinuation = continuation || null;
+ }
+
+ rebuildLazyNodeIndex(state);
+}
+
+export function replaceLazyKvFocusedRoot(state: LazyKvKeyTreeState, root: KvKeySummary, keys: KvKeySummary[], continuation: string | null | undefined) {
+ const previous = new Map(state.nodeByKey);
+ const focusedPath = normalizeZooKeeperPath(root.key);
+ const childNodes = keys.map((key) => lazyNodeFromSummary(key, previous.get(key.key)));
+ const chain = focusedPathChain(focusedPath);
+ let rootNode: LazyKvKeyTreeNode | null = null;
+ let parentNode: LazyKvKeyTreeNode | null = null;
+
+ for (const path of chain) {
+ const node = lazyNodeFromSummary(path === focusedPath ? { ...root, key: focusedPath } : { key: path, numChildren: 1 }, previous.get(path));
+ node.hasChildren = true;
+ node.loaded = true;
+ node.continuation = null;
+ node.children = [];
+
+ if (parentNode) parentNode.children = [node];
+ else rootNode = node;
+ parentNode = node;
+ }
+
+ if (parentNode) {
+ parentNode.children = childNodes;
+ parentNode.hasChildren = parentNode.hasChildren || childNodes.length > 0 || !!continuation;
+ parentNode.continuation = continuation || null;
+ }
+
+ state.roots = rootNode ? [rootNode] : [];
+ state.rootContinuation = null;
+ rebuildLazyNodeIndex(state);
+}
+
+export function flattenLazyKvKeyTree(state: LazyKvKeyTreeState, expandedIds: ReadonlySet<string>): LazyKvKeyTreeRow[] {
+ const rows = flattenLazyNodes(state.roots, expandedIds, 0);
+ if (state.rootContinuation) {
+ rows.push({ type: "loadMore", id: "lazy-load-more:root", parentKey: null, depth: 0, loading: false });
+ }
+ return rows;
+}
+
+export function lazyExpandedKeyFromId(id: string): string | null {
+ return id.startsWith("lazy:") ? id.slice("lazy:".length) : null;
+}
+
+function flattenLazyNodes(nodes: LazyKvKeyTreeNode[], expandedIds: ReadonlySet<string>, depth: number): LazyKvKeyTreeRow[] {
+ const rows: LazyKvKeyTreeRow[] = [];
+ for (const node of nodes) {
+ rows.push({ type: "node", node, depth });
+ if (node.hasChildren && expandedIds.has(node.id)) {
+ rows.push(...flattenLazyNodes(node.children, expandedIds, depth + 1));
+ if (node.continuation) {
+ rows.push({ type: "loadMore", id: `lazy-load-more:${node.key}`, parentKey: node.key, depth: depth + 1, loading: node.loading });
+ }
+ }
+ }
+ return rows;
+}
+
+function lazyNodeFromSummary(summary: KvKeySummary, previous?: LazyKvKeyTreeNode): LazyKvKeyTreeNode {
+ const pathSegments = keySegments(summary.key);
+ return {
+ ...summary,
+ kind: "lazy",
+ id: `lazy:${summary.key}`,
+ label: pathSegments[pathSegments.length - 1] || summary.key || "/",
+ key: summary.key,
+ pathSegments,
+ hasChildren: (summary.numChildren ?? 0) > 0,
+ children: previous?.children || [],
+ loaded: previous?.loaded || false,
+ loading: previous?.loading || false,
+ continuation: previous?.continuation || null,
+ };
+}
+
+function mergeLazyChildren(existing: LazyKvKeyTreeNode[], incoming: LazyKvKeyTreeNode[]): LazyKvKeyTreeNode[] {
+ const seen = new Set(existing.map((node) => node.key));
+ return [...existing, ...incoming.filter((node) => !seen.has(node.key))];
+}
+
+function rebuildLazyNodeIndex(state: LazyKvKeyTreeState) {
+ state.nodeByKey.clear();
+ const visit = (nodes: LazyKvKeyTreeNode[]) => {
+ for (const node of nodes) {
+ state.nodeByKey.set(node.key, node);
+ visit(node.children);
+ }
+ };
+ visit(state.roots);
+}
+
+function keySegments(key: string): string[] {
+ return key.split("/").filter(Boolean);
+}
+
+function focusedPathChain(path: string): string[] {
+ const segments = keySegments(path);
+ const chain: string[] = [];
+ for (let index = 0; index < segments.length; index++) {
+ chain.push(`/${segments.slice(0, index + 1).join("/")}`);
+ }
+ return chain;
+}
diff --git a/crates/dbx-core/src/agent_kv.rs b/crates/dbx-core/src/agent_kv.rs
index 530b391d9d..8b279c65a5 100644
--- a/crates/dbx-core/src/agent_kv.rs
+++ b/crates/dbx-core/src/agent_kv.rs
@@ -52,6 +52,8 @@ pub struct KvListPrefixRequest {
pub limit: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub continuation: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub recursive: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
@@ -140,10 +142,20 @@ pub struct KvDeleteResponse {
}
pub fn kv_list_prefix_params(prefix: &str, limit: usize, continuation: Option<&str>) -> serde_json::Value {
+ kv_list_prefix_params_with_options(prefix, limit, continuation, None)
+}
+
+pub fn kv_list_prefix_params_with_options(
+ prefix: &str,
+ limit: usize,
+ continuation: Option<&str>,
+ recursive: Option<bool>,
+) -> serde_json::Value {
serde_json::to_value(KvListPrefixRequest {
prefix: prefix.to_string(),
limit,
continuation: continuation.map(str::to_string),
+ recursive,
})
.expect("KV list prefix request should serialize")
}
@@ -178,8 +190,24 @@ pub async fn kv_list_prefix_core(
limit: usize,
continuation: Option<&str>,
) -> Result<KvListPrefixResponse, String> {
- call_agent_kv(state, connection_id, AgentKvMethod::ListPrefix, kv_list_prefix_params(prefix, limit, continuation))
- .await
+ kv_list_prefix_core_with_options(state, connection_id, prefix, limit, continuation, None).await
+}
+
+pub async fn kv_list_prefix_core_with_options(
+ state: &AppState,
+ connection_id: &str,
+ prefix: &str,
+ limit: usize,
+ continuation: Option<&str>,
+ recursive: Option<bool>,
+) -> Result<KvListPrefixResponse, String> {
+ call_agent_kv(
+ state,
+ connection_id,
+ AgentKvMethod::ListPrefix,
+ kv_list_prefix_params_with_options(prefix, limit, continuation, recursive),
+ )
+ .await
}
pub async fn kv_get_core(state: &AppState, connection_id: &str, key: &str) -> Result<KvGetResponse, String> {
@@ -259,6 +287,18 @@ mod tests {
);
}
+ #[test]
+ fn serializes_kv_list_prefix_params_with_recursive_false() {
+ assert_eq!(
+ kv_list_prefix_params_with_options("/app", 200, None, Some(false)),
+ serde_json::json!({
+ "prefix": "/app",
+ "limit": 200,
+ "recursive": false
+ })
+ );
+ }
+
#[test]
fn serializes_kv_get_put_delete_params() {
assert_eq!(kv_get_params("/app/name"), serde_json::json!({ "key": "/app/name" }));
diff --git a/crates/dbx-web/src/routes/zookeeper.rs b/crates/dbx-web/src/routes/zookeeper.rs
index f2e175530d..bfac64dbed 100644
--- a/crates/dbx-web/src/routes/zookeeper.rs
+++ b/crates/dbx-web/src/routes/zookeeper.rs
@@ -28,6 +28,7 @@ pub struct ZooKeeperListPrefixRequest {
pub prefix: String,
pub limit: usize,
pub continuation: Option<String>,
+ pub recursive: Option<bool>,
}
#[derive(Deserialize)]
@@ -50,12 +51,13 @@ pub async fn list_prefix(
State(state): State<Arc<WebState>>,
Json(req): Json<ZooKeeperListPrefixRequest>,
) -> Result<Json<dbx_core::agent_kv::KvListPrefixResponse>, AppError> {
- let result = dbx_core::agent_kv::kv_list_prefix_core(
+ let result = dbx_core::agent_kv::kv_list_prefix_core_with_options(
&state.app,
&req.connection_id,
&req.prefix,
req.limit,
req.continuation.as_deref(),
+ req.recursive,
)
.await
.map_err(AppError)?;
diff --git a/src-tauri/src/commands/zookeeper_cmd.rs b/src-tauri/src/commands/zookeeper_cmd.rs
index da3a324e9f..8956a2ada6 100644
--- a/src-tauri/src/commands/zookeeper_cmd.rs
+++ b/src-tauri/src/commands/zookeeper_cmd.rs
@@ -12,8 +12,17 @@ pub async fn zookeeper_list_prefix(
prefix: String,
limit: usize,
continuation: Option<String>,
+ recursive: Option<bool>,
) -> Result<KvListPrefixResponse, String> {
- dbx_core::agent_kv::kv_list_prefix_core(&state, &connection_id, &prefix, limit, continuation.as_deref()).await
+ dbx_core::agent_kv::kv_list_prefix_core_with_options(
+ &state,
+ &connection_id,
+ &prefix,
+ limit,
+ continuation.as_deref(),
+ recursive,
+ )
+ .await
}
#[tauri::command]