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。

fix(kafka): improve mq admin compatibility

miracle72a72072831a
diff --git a/agents/drivers/kafka/src/main/java/com/dbx/agent/kafka/KafkaAgent.java b/agents/drivers/kafka/src/main/java/com/dbx/agent/kafka/KafkaAgent.java
index cd81b902df..bcb13bdd79 100644
--- a/agents/drivers/kafka/src/main/java/com/dbx/agent/kafka/KafkaAgent.java
+++ b/agents/drivers/kafka/src/main/java/com/dbx/agent/kafka/KafkaAgent.java
@@ -87,7 +87,7 @@ public final class KafkaAgent {
} catch (Exception e) {
JsonObject error = new JsonObject();
error.addProperty("code", -1);
- error.addProperty("message", e.getMessage() == null ? "Unknown error" : e.getMessage());
+ error.addProperty("message", normalizeErrorMessage(e));
response.add("error", error);
}
return GSON.toJson(response);
@@ -255,9 +255,10 @@ public final class KafkaAgent {
if (securityProtocol.isBlank()) {
securityProtocol = stringOrEmpty(conn, "securityProtocol");
}
- if (!securityProtocol.isBlank()) {
- props.put("security.protocol", securityProtocol);
+ if (securityProtocol.isBlank()) {
+ securityProtocol = "PLAINTEXT";
}
+ props.put("security.protocol", securityProtocol);
String saslMechanism = stringOrEmpty(conn, "sasl_mechanism");
if (saslMechanism.isBlank()) {
@@ -576,56 +577,63 @@ public final class KafkaAgent {
int timeout = requestTimeout(params);
String topic = stringOrEmpty(params, "topic");
- TopicDescription desc = admin.describeTopics(Collections.singletonList(topic))
- .allTopicNames().get(timeout, TimeUnit.MILLISECONDS).get(topic);
- List<TopicPartition> partitions = desc.partitions().stream()
- .map(pi -> new TopicPartition(topic, pi.partition()))
- .collect(Collectors.toList());
-
- DescribeProducersResult described = admin.describeProducers(
- partitions,
- new DescribeProducersOptions().timeoutMs(timeout));
-
- Map<Long, Map<String, Object>> byProducer = new LinkedHashMap<>();
- for (TopicPartition tp : partitions) {
- DescribeProducersResult.PartitionProducerState state =
- described.partitionResult(tp).get(timeout, TimeUnit.MILLISECONDS);
- for (ProducerState producerState : state.activeProducers()) {
- long producerId = producerState.producerId();
- Map<String, Object> producer = byProducer.computeIfAbsent(producerId, id -> {
- Map<String, Object> p = new LinkedHashMap<>();
- p.put("producerId", id);
- p.put("producerName", "producer-" + id);
- p.put("msgRateIn", 0.0);
- p.put("msgThroughputIn", 0.0);
- p.put("clientVersion", "Kafka producer");
- p.put("partitions", new ArrayList<Integer>());
- p.put("lastTimestamp", producerState.lastTimestamp());
- return p;
- });
+ try {
+ TopicDescription desc = admin.describeTopics(Collections.singletonList(topic))
+ .allTopicNames().get(timeout, TimeUnit.MILLISECONDS).get(topic);
+ List<TopicPartition> partitions = desc.partitions().stream()
+ .map(pi -> new TopicPartition(topic, pi.partition()))
+ .collect(Collectors.toList());
+
+ DescribeProducersResult described = admin.describeProducers(
+ partitions,
+ new DescribeProducersOptions().timeoutMs(timeout));
+
+ Map<Long, Map<String, Object>> byProducer = new LinkedHashMap<>();
+ for (TopicPartition tp : partitions) {
+ DescribeProducersResult.PartitionProducerState state =
+ described.partitionResult(tp).get(timeout, TimeUnit.MILLISECONDS);
+ for (ProducerState producerState : state.activeProducers()) {
+ long producerId = producerState.producerId();
+ Map<String, Object> producer = byProducer.computeIfAbsent(producerId, id -> {
+ Map<String, Object> p = new LinkedHashMap<>();
+ p.put("producerId", id);
+ p.put("producerName", "producer-" + id);
+ p.put("msgRateIn", 0.0);
+ p.put("msgThroughputIn", 0.0);
+ p.put("clientVersion", "Kafka producer");
+ p.put("partitions", new ArrayList<Integer>());
+ p.put("lastTimestamp", producerState.lastTimestamp());
+ return p;
+ });
+ @SuppressWarnings("unchecked")
+ List<Integer> producerPartitions = (List<Integer>) producer.get("partitions");
+ producerPartitions.add(tp.partition());
+ long currentLastTimestamp = (long) producer.get("lastTimestamp");
+ if (producerState.lastTimestamp() > currentLastTimestamp) {
+ producer.put("lastTimestamp", producerState.lastTimestamp());
+ }
+ }
+ }
+
+ for (Map<String, Object> producer : byProducer.values()) {
@SuppressWarnings("unchecked")
List<Integer> producerPartitions = (List<Integer>) producer.get("partitions");
- producerPartitions.add(tp.partition());
- long currentLastTimestamp = (long) producer.get("lastTimestamp");
- if (producerState.lastTimestamp() > currentLastTimestamp) {
- producer.put("lastTimestamp", producerState.lastTimestamp());
- }
+ producerPartitions.sort(Integer::compareTo);
+ producer.put(
+ "address",
+ producerPartitions.size() == 1
+ ? "partition " + producerPartitions.get(0)
+ : "partitions " + producerPartitions.stream().map(String::valueOf).collect(Collectors.joining(", "))
+ );
}
- }
- for (Map<String, Object> producer : byProducer.values()) {
- @SuppressWarnings("unchecked")
- List<Integer> producerPartitions = (List<Integer>) producer.get("partitions");
- producerPartitions.sort(Integer::compareTo);
- producer.put(
- "address",
- producerPartitions.size() == 1
- ? "partition " + producerPartitions.get(0)
- : "partitions " + producerPartitions.stream().map(String::valueOf).collect(Collectors.joining(", "))
- );
+ return Collections.singletonMap("producers", new ArrayList<>(byProducer.values()));
+ } catch (Exception e) {
+ if (isUnsupportedVersionError(e)) {
+ return Collections.singletonMap("producers", Collections.emptyList());
+ }
+ throw e;
}
-
- return Collections.singletonMap("producers", new ArrayList<>(byProducer.values()));
}
private static Object deleteConsumerGroup(JsonObject params) throws Exception {
@@ -1010,6 +1018,74 @@ public final class KafkaAgent {
// Helpers
// -----------------------------------------------------------------------
+ private static String normalizeErrorMessage(Exception e) {
+ String message = e.getMessage() == null || e.getMessage().isBlank()
+ ? e.getClass().getName()
+ : e.getMessage();
+ Throwable root = rootCause(e);
+ if (root != e && root.getMessage() != null && !root.getMessage().isBlank()
+ && !message.contains(root.getMessage())) {
+ message = message + ": " + root.getMessage();
+ }
+ if (isSslHandshakeError(e)) {
+ message = message
+ + ". Hint: SSL handshake failed. Check the Kafka security protocol. "
+ + "Use PLAINTEXT for a PLAINTEXT broker listener, SSL for SSL, "
+ + "SASL_PLAINTEXT for SASL without TLS, or SASL_SSL for SASL with TLS. "
+ + "For older Kafka/JDK TLS setups, also check truststore settings, certificates, "
+ + "hostname verification, and enabled TLS protocol versions.";
+ }
+ return message;
+ }
+
+ private static boolean isSslHandshakeError(Throwable error) {
+ for (Throwable current : causeChain(error)) {
+ String className = current.getClass().getName();
+ String message = current.getMessage() == null ? "" : current.getMessage().toLowerCase(Locale.ROOT);
+ if (className.contains("SslAuthenticationException")
+ || className.contains("SSLHandshakeException")
+ || message.contains("ssl handshake failed")) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static boolean isUnsupportedVersionError(Throwable error) {
+ for (Throwable current : causeChain(error)) {
+ String className = current.getClass().getName();
+ String message = current.getMessage() == null ? "" : current.getMessage().toLowerCase(Locale.ROOT);
+ if (className.contains("UnsupportedVersionException")
+ || message.contains("unsupported version")) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static Throwable rootCause(Throwable error) {
+ Throwable current = null;
+ for (Throwable cause : causeChain(error)) {
+ current = cause;
+ }
+ return current == null ? error : current;
+ }
+
+ private static List<Throwable> causeChain(Throwable error) {
+ List<Throwable> chain = new ArrayList<>();
+ Set<Throwable> seen = Collections.newSetFromMap(new IdentityHashMap<>());
+ Throwable current = error;
+ for (int depth = 0; current != null && depth < 32 && seen.add(current); depth++) {
+ chain.add(current);
+ Throwable next = current.getCause();
+ if (next == current) {
+ break;
+ }
+ current = next;
+ }
+ return chain;
+ }
+
private static AdminClient requireAdmin() {
if (adminClient == null) {
throw new IllegalStateException("Not connected. Call connect first.");
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue
index 8d4c8fcf18..1eac27c58e 100644
--- a/apps/desktop/src/components/connection/ConnectionDialog.vue
+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { computed, nextTick, ref, watch } from "vue";
+import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
import { uuid } from "@/lib/utils";
import { useI18n } from "vue-i18n";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
@@ -32,10 +32,11 @@ import { isLocalFileTypeDb } from "@/lib/connectionFile";
import { MQ_PINNED_VERSION_OPTIONS, pinnedVersionToSelection, selectionToPinnedVersion } from "@/lib/mqPinnedVersionOptions";
import { mongodbAuthFailureHint, mongoUrlParam, setMongoUrlParam } from "@/lib/mongoConnectionOptions";
import { copyToClipboard } from "@/lib/clipboard";
-import { appendAgentDriverUpdateHint, hasAgentDriverUpdate, showAgentDriverInstallHint, type AgentDriverInstallState } from "@/lib/agentDriverInstallHint";
+import { agentDriverInstallKey, appendAgentDriverUpdateHint, hasAgentDriverUpdate, showAgentDriverInstallHint, type AgentDriverInstallState } from "@/lib/agentDriverInstallHint";
import { prestoSqlBuiltinDriverPaths } from "@/lib/prestoSqlBuiltinDriver";
import { SQLITE_DATABASE_FILE_EXTENSIONS } from "@/lib/databaseFileDetection";
import { connectionAttemptOriginalErrorMessage, connectionAttemptTimeoutMessage, connectionAttemptTimeoutMs } from "@/lib/connectionAttemptTimeout";
+import { driverInstallProgressPercent, type DriverInstallProgress } from "@/lib/driverInstallProgressUi";
import { ArrowLeft, ArrowDown, ArrowUp, CheckSquare, ChevronRight, CircleHelp, Copy, ExternalLink, FilePlus2, FolderOpen, GripVertical, Grid3X3, KeyRound, Link2, List, ListFilter, Loader2, Pipette, Plus, Search, ShieldCheck, Square, Trash2 } from "@lucide/vue";
import { buildDraftVisibleDatabasesConnectionId, connectionCanChooseVisibleDatabases, initialVisibleDatabaseSelection, visibleDatabaseSelectionIsStale } from "@/lib/connectionVisibleDatabases";
import { canSaveVisibleDatabaseSelection, connectionUsesVisibleSchemaFilter, filterDatabaseNamesForVisiblePicker, isSystemDatabaseName, normalizeVisibleDatabaseSelection, buildDraftVisibleSchemasConnectionId, normalizeVisibleSchemaSelection } from "@/lib/visibleDatabases";
@@ -111,7 +112,16 @@ const store = useConnectionStore();
const isTesting = ref(false);
const isSaving = ref(false);
const testResult = ref<{ ok: boolean; message: string } | null>(null);
+const showAgentInstallDialog = ref(false);
+const agentInstallRunning = ref(false);
+const agentInstallDriverKey = ref("");
+const agentInstallLabel = ref("");
+const agentInstallProgress = ref<DriverInstallProgress | null>(null);
+const agentInstallError = ref("");
+const showConnectionErrorDialog = ref(false);
+const connectionErrorDetail = ref("");
const editingId = ref<string | null>(null);
+const draftTestConnectionId = ref(uuid());
const showVisibleDatabasesDialog = ref(false);
const isLoadingVisibleDatabases = ref(false);
const visibleDatabaseNames = ref<string[]>([]);
@@ -125,6 +135,7 @@ const visibleSchemaNames = ref<string[]>([]);
const visibleSchemaInitialSelection = ref<string[]>([]);
const visibleSchemaError = ref("");
let testRunId = 0;
+let unlistenAgentInstallProgress: (() => void) | null = null;
function initialConfigTab(): ConfigTab {
return props.initialTab ?? "connection";
@@ -868,6 +879,91 @@ function connectionErrorWithDriverUpdateHint(config: ConnectionConfig, message:
return appendAgentDriverUpdateHint(message, t("connection.agentDriverUpdateConnectionHint"));
}
+function installedAgentDriver(drivers: readonly AgentDriverInstallState[], key: string): AgentDriverInstallState | undefined {
+ return drivers.find((driver) => driver.db_type === key);
+}
+
+async function refreshLocalAgentDrivers(): Promise<AgentDriverInstallState[]> {
+ const drivers = await api.listInstalledAgentsLocal();
+ agentDrivers.value = drivers;
+ return drivers;
+}
+
+function beginAgentDriverInstall(driverKey: string, label: string) {
+ agentInstallDriverKey.value = driverKey;
+ agentInstallLabel.value = label;
+ agentInstallProgress.value = null;
+ agentInstallError.value = "";
+ agentInstallRunning.value = true;
+ showAgentInstallDialog.value = true;
+}
+
+function finishAgentDriverInstall() {
+ agentInstallRunning.value = false;
+ agentInstallProgress.value = null;
+ agentInstallError.value = "";
+ showAgentInstallDialog.value = false;
+}
+
+function failAgentDriverInstall(error: unknown) {
+ agentInstallRunning.value = false;
+ agentInstallError.value = errorMessage(error);
+ showAgentInstallDialog.value = true;
+}
+
+function showConnectionError(message: string) {
+ connectionErrorDetail.value = translateBackendError(t, message);
+ showConnectionErrorDialog.value = true;
+}
+
+function setAgentInstallDialogOpen(value: boolean) {
+ if (value || canCloseAgentInstallDialog.value) {
+ showAgentInstallDialog.value = value;
+ }
+}
+
+function handleAgentInstallProgress(payload: DriverInstallProgress) {
+ if (!agentInstallRunning.value || !agentInstallDriverKey.value) return;
+ if (payload.db_type && payload.db_type !== agentInstallDriverKey.value) return;
+ if (payload.step === "done" || payload.step === "all-done") {
+ agentInstallProgress.value = null;
+ return;
+ }
+ agentInstallProgress.value = payload;
+}
+
+function formatInstallSize(bytes: number): string {
+ if (!bytes) return "0 B";
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
+}
+
+async function ensureRequiredAgentDriverInstalled(config: ConnectionConfig): Promise<void> {
+ const driverKey = agentDriverInstallKey(config.db_type, config.driver_profile);
+ if (!driverKey) return;
+
+ let drivers = agentDrivers.value.length ? agentDrivers.value : await refreshLocalAgentDrivers();
+ if (!showAgentDriverInstallHint(config.db_type, drivers, config.driver_profile)) return;
+ if (installedAgentDriver(drivers, driverKey)?.installed === true) return;
+
+ drivers = await refreshLocalAgentDrivers();
+ if (installedAgentDriver(drivers, driverKey)?.installed === true) return;
+
+ const label = config.driver_label || driverKey;
+ testResult.value = { ok: true, message: `Installing ${label} driver...` };
+ beginAgentDriverInstall(driverKey, label);
+ try {
+ await api.installAgent(driverKey);
+ await refreshLocalAgentDrivers();
+ finishAgentDriverInstall();
+ } catch (error) {
+ testResult.value = { ok: false, message: errorMessage(error) };
+ failAgentDriverInstall(error);
+ throw error;
+ }
+}
+
function isSqlServerLegacyUnencryptedMode(params: string | undefined): boolean {
const normalized = (params || "").trim().replace(/^\?/, "").replace(/;/g, "&");
if (!normalized) return false;
@@ -1633,6 +1729,18 @@ const testResultMessage = computed(() => {
if (!testResult.value) return "";
return testResult.value.ok ? t("connection.testSuccess") : translateBackendError(t, testResult.value.message);
});
+const agentInstallPercent = computed(() => driverInstallProgressPercent(agentInstallProgress.value));
+const agentInstallProgressLabel = computed(() => {
+ const progress = agentInstallProgress.value;
+ if (agentInstallError.value) return "安装失败";
+ if (!agentInstallRunning.value) return "等待安装";
+ if (!progress) return "准备安装驱动...";
+ if (progress.step === "jre-extract") return "解压 JRE...";
+ const label = progress.step === "jre" ? "下载 JRE" : progress.step === "driver" ? "下载驱动" : progress.step || "安装驱动";
+ if (!progress.total) return `${label}...`;
+ return `${label} ${formatInstallSize(progress.downloaded ?? 0)} / ${formatInstallSize(progress.total)} (${agentInstallPercent.value ?? 0}%)`;
+});
+const canCloseAgentInstallDialog = computed(() => !agentInstallRunning.value || !!agentInstallError.value);
const sqlServerLegacyUnencryptedModeEnabled = computed({
get: () => form.value.db_type === "sqlserver" && isSqlServerLegacyUnencryptedMode(form.value.url_params),
set: (enabled: boolean) => {
@@ -1704,8 +1812,9 @@ async function testConnection() {
const runId = ++testRunId;
isTesting.value = true;
testResult.value = null;
- const config = connectionConfigForSubmit(editingId.value || uuid());
+ const config = connectionConfigForSubmit(editingId.value || draftTestConnectionId.value);
try {
+ await ensureRequiredAgentDriverInstalled(config);
const msg = await testConnectionWithTimeout(config, runId);
if (runId !== testRunId) return;
if (config.db_type === "mongodb" && /legacy driver/i.test(msg)) {
@@ -1722,6 +1831,9 @@ async function testConnection() {
configTab.value = "advanced";
}
testResult.value = fallbackMessage ? { ok: true, message: fallbackMessage } : { ok: false, message };
+ if (!fallbackMessage) {
+ showConnectionError(message);
+ }
} finally {
if (runId === testRunId) {
isTesting.value = false;
@@ -2304,6 +2416,8 @@ function resetTestState() {
testRunId += 1;
isTesting.value = false;
testResult.value = null;
+ showConnectionErrorDialog.value = false;
+ connectionErrorDetail.value = "";
}
function resetVisibleDatabaseDraftState() {
@@ -2494,6 +2608,26 @@ async function copyTestResult() {
}
}
+async function copyAgentInstallError() {
+ if (!agentInstallError.value) return;
+ try {
+ await copyToClipboard(agentInstallError.value);
+ toast(t("grid.copied"));
+ } catch (e: any) {
+ toast(t("grid.copyFailed", { message: e?.message || String(e) }), 5000);
+ }
+}
+
+async function copyConnectionErrorDetail() {
+ if (!connectionErrorDetail.value) return;
+ try {
+ await copyToClipboard(connectionErrorDetail.value);
+ toast(t("grid.copied"));
+ } catch (e: any) {
+ toast(t("grid.copyFailed", { message: e?.message || String(e) }), 5000);
+ }
+}
+
function resetForm() {
editingId.value = null;
form.value = defaultForm();
@@ -2588,8 +2722,13 @@ watch(
open,
(value) => {
if (!value) {
+ const draftId = editingId.value ? null : draftTestConnectionId.value;
submittedOneTimePrefillKey.value = null;
resetForm();
+ if (draftId) {
+ void api.disconnectDb(draftId).catch(() => undefined);
+ draftTestConnectionId.value = uuid();
+ }
return;
}
if (!props.editConfig) {
@@ -2755,11 +2894,14 @@ async function save() {
try {
if (editingId.value) {
const updated = connectionConfigForSubmit(editingId.value);
+ await ensureRequiredAgentDriverInstalled(updated);
await store.updateConnection(updated);
store.stopEditing();
} else {
- const config = connectionConfigForSubmit(uuid());
+ const config = connectionConfigForSubmit(draftTestConnectionId.value);
+ await ensureRequiredAgentDriverInstalled(config);
await store.addConnection(config);
+ draftTestConnectionId.value = uuid();
if (config.db_type === "jdbc") {
open.value = false;
return;
@@ -2780,7 +2922,9 @@ async function save() {
}
open.value = false;
} catch (e: any) {
- testResult.value = { ok: false, message: mongodbAuthFailureHint(String(e?.message || e)) };
+ const message = mongodbAuthFailureHint(String(e?.message || e));
+ testResult.value = { ok: false, message };
+ showConnectionError(message);
} finally {
isSaving.value = false;
}
@@ -3050,6 +3194,15 @@ function onJdbcDriverSelect(id: any) {
jdbcManualClasspathOpen.value = false;
}
+onMounted(async () => {
+ unlistenAgentInstallProgress = await api.listenAgentInstallProgress(handleAgentInstallProgress);
+});
+
+onUnmounted(() => {
+ unlistenAgentInstallProgress?.();
+ unlistenAgentInstallProgress = null;
+});
+
function openExternalUrl(url: string) {
if (isTauriRuntime()) {
import("@tauri-apps/plugin-shell").then(({ open }) => open(url));
@@ -4574,6 +4727,65 @@ function openExternalUrl(url: string) {
</DialogContent>
</Dialog>
+ <Dialog :open="showAgentInstallDialog" @update:open="setAgentInstallDialogOpen">
+ <DialogContent class="sm:max-w-[520px]" @interact-outside.prevent @escape-key-down.prevent>
+ <DialogHeader>
+ <DialogTitle>{{ agentInstallError ? "驱动安装失败" : "正在安装驱动" }}</DialogTitle>
+ </DialogHeader>
+
+ <div class="space-y-4">
+ <div class="rounded-lg border bg-muted/20 p-4">
+ <div class="flex items-center justify-between gap-3">
+ <div class="min-w-0">
+ <div class="truncate text-sm font-medium">{{ agentInstallLabel || agentInstallDriverKey }}</div>
+ <div class="mt-1 text-xs text-muted-foreground">{{ agentInstallProgressLabel }}</div>
+ </div>
+ <Loader2 v-if="agentInstallRunning && !agentInstallError" class="h-4 w-4 shrink-0 animate-spin text-muted-foreground" />
+ </div>
+ <div v-if="!agentInstallError" class="mt-4 h-2 overflow-hidden rounded-full bg-muted">
+ <div class="h-full rounded-full bg-primary transition-all" :class="{ 'animate-pulse': agentInstallPercent === null }" :style="{ width: `${agentInstallPercent ?? 35}%` }" />
+ </div>
+ </div>
+
+ <div v-if="agentInstallError" class="space-y-2">
+ <div class="text-sm font-medium text-destructive">完整错误</div>
+ <pre class="max-h-56 overflow-auto whitespace-pre-wrap break-words rounded-md border bg-muted/30 p-3 text-xs leading-5 text-destructive">{{ agentInstallError }}</pre>
+ </div>
+ </div>
+
+ <DialogFooter class="gap-2">
+ <Button v-if="agentInstallError" variant="outline" @click="copyAgentInstallError">
+ <Copy class="mr-1.5 h-3.5 w-3.5" />
+ 复制错误
+ </Button>
+ <Button :disabled="!canCloseAgentInstallDialog" @click="showAgentInstallDialog = false">
+ {{ agentInstallError ? "关闭" : "安装中..." }}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ <Dialog v-model:open="showConnectionErrorDialog">
+ <DialogContent class="sm:max-w-[560px]">
+ <DialogHeader>
+ <DialogTitle>连接失败</DialogTitle>
+ </DialogHeader>
+
+ <div class="space-y-2">
+ <div class="text-sm text-muted-foreground">完整错误信息</div>
+ <pre class="max-h-72 overflow-auto whitespace-pre-wrap break-words rounded-md border bg-muted/30 p-3 text-xs leading-5 text-destructive">{{ connectionErrorDetail }}</pre>
+ </div>
+
+ <DialogFooter class="gap-2">
+ <Button variant="outline" @click="copyConnectionErrorDetail">
+ <Copy class="mr-1.5 h-3.5 w-3.5" />
+ 复制错误
+ </Button>
+ <Button @click="showConnectionErrorDialog = false">关闭</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
<Dialog v-model:open="showVisibleDatabasesDialog">
<DialogContent class="sm:max-w-[460px]">
<DialogHeader>
diff --git a/apps/desktop/src/components/mq/MqAdminConsole.vue b/apps/desktop/src/components/mq/MqAdminConsole.vue
index 8f67cc9ef1..80d9f2aff8 100644
--- a/apps/desktop/src/components/mq/MqAdminConsole.vue
+++ b/apps/desktop/src/components/mq/MqAdminConsole.vue
@@ -70,10 +70,10 @@ const availableTabs = computed<MqTab[]>(() => {
if (canManageTenants.value) tabs.push("tenants");
if (canManageNamespaces.value) tabs.push("namespaces");
tabs.push("topics");
- if (canSendMessage.value) tabs.push("messages");
if (canManageSubscriptions.value) tabs.push("subscriptions");
tabs.push("monitoring");
tabs.push("clients");
+ if (canSendMessage.value) tabs.push("messages");
tabs.push("broker");
if (canManagePolicies.value) tabs.push("policies");
if (canManagePermissions.value) tabs.push("permissions");
@@ -220,10 +220,10 @@ onMounted(async () => {
<button v-if="canManageTenants" :class="{ active: activeTab === 'tenants' }" @click="setActiveTab('tenants')">租户</button>
<button v-if="canManageNamespaces" :class="{ active: activeTab === 'namespaces' }" @click="setActiveTab('namespaces')">命名空间</button>
<button :class="{ active: activeTab === 'topics' }" @click="setActiveTab('topics')">主题</button>
- <button v-if="canSendMessage" :class="{ active: activeTab === 'messages' }" @click="setActiveTab('messages')">发送消息</button>
<button v-if="canManageSubscriptions" :class="{ active: activeTab === 'subscriptions' }" @click="setActiveTab('subscriptions')">订阅</button>
<button :class="{ active: activeTab === 'monitoring' }" @click="setActiveTab('monitoring')">监控</button>
<button :class="{ active: activeTab === 'clients' }" @click="setActiveTab('clients')">客户端</button>
+ <button v-if="canSendMessage" :class="{ active: activeTab === 'messages' }" @click="setActiveTab('messages')">消息</button>
<button :class="{ active: activeTab === 'broker' }" @click="setActiveTab('broker')">Broker</button>
<button v-if="canManagePolicies" :class="{ active: activeTab === 'policies' }" @click="setActiveTab('policies')">策略</button>
<button v-if="canManagePermissions" :class="{ active: activeTab === 'permissions' }" @click="setActiveTab('permissions')">权限</button>
@@ -234,8 +234,7 @@ onMounted(async () => {
<div class="mq-content">
<TenantsPanel v-if="activeTab === 'tenants'" :connection-id="connectionId" :supports-tenants="canManageTenants" :read-only="readOnly" :cluster-options="clusterOptions" @tenant-selected="handleTenantSelected" />
<NamespacesPanel v-else-if="activeTab === 'namespaces'" :connection-id="connectionId" :tenant="selectedTenant" :supports-namespaces="canManageNamespaces" :read-only="readOnly" @namespace-selected="handleNamespaceSelected" @namespace-roles-selected="handleNamespaceRolesSelected" />
- <TopicsPanel v-else-if="activeTab === 'topics'" :connection-id="connectionId" :tenant="effectiveTenant" :namespace="effectiveNamespace" :read-only="readOnly" :supports-partitioned-topics="canManagePartitionedTopics" @topic-selected="handleTopicSelected" />
- <SendMessagePanel v-else-if="activeTab === 'messages' && canSendMessage" :connection-id="connectionId" :tenant="effectiveTenant" :namespace="effectiveNamespace" :topic="selectedTopic" :read-only="readOnly" />
+ <TopicsPanel v-else-if="activeTab === 'topics'" :connection-id="connectionId" :tenant="effectiveTenant" :namespace="effectiveNamespace" :read-only="readOnly" :supports-partitioned-topics="canManagePartitionedTopics" :is-kafka-cluster="isKafkaCluster" @topic-selected="handleTopicSelected" />
<SubscriptionsPanel
v-else-if="activeTab === 'subscriptions' && canManageSubscriptions"
:connection-id="connectionId"
@@ -252,7 +251,8 @@ onMounted(async () => {
@subscription-selected="handleSubscriptionSelected"
/>
<MonitoringPanel v-else-if="activeTab === 'monitoring'" :connection-id="connectionId" :topic="selectedTopic" :tenant="effectiveTenant" :namespace="effectiveNamespace" />
- <ProducerConsumerPanel v-else-if="activeTab === 'clients'" :connection-id="connectionId" :topic="selectedTopic" :tenant="effectiveTenant" :namespace="effectiveNamespace" :read-only="readOnly" :selected-subscription="selectedSubscriptionName" />
+ <ProducerConsumerPanel v-else-if="activeTab === 'clients'" :connection-id="connectionId" :topic="selectedTopic" :tenant="effectiveTenant" :namespace="effectiveNamespace" :read-only="readOnly" :selected-subscription="selectedSubscriptionName" :is-kafka-cluster="isKafkaCluster" />
+ <SendMessagePanel v-else-if="activeTab === 'messages' && canSendMessage" :connection-id="connectionId" :tenant="effectiveTenant" :namespace="effectiveNamespace" :topic="selectedTopic" :read-only="readOnly" :is-kafka-cluster="isKafkaCluster" :supports-peek-messages="canPeekMessages" />
<BrokerPanel v-else-if="activeTab === 'broker'" :connection-id="connectionId" :read-only="readOnly" />
<PoliciesPanel
v-else-if="activeTab === 'policies' && canManagePolicies"
@@ -261,6 +261,7 @@ onMounted(async () => {
:tenant="effectiveTenant"
:namespace="effectiveNamespace"
:read-only="readOnly"
+ :is-kafka-cluster="isKafkaCluster"
:supports-rate-limits="canManageRateLimits"
:supports-backlog-quota="canManageBacklogQuota"
:supports-retention="canManageRetention"
diff --git a/apps/desktop/src/components/mq/PoliciesPanel.vue b/apps/desktop/src/components/mq/PoliciesPanel.vue
index 452dd822fe..5dcc1c095a 100644
--- a/apps/desktop/src/components/mq/PoliciesPanel.vue
+++ b/apps/desktop/src/components/mq/PoliciesPanel.vue
@@ -11,6 +11,7 @@ interface Props {
namespace?: string;
topic?: TopicInfo;
readOnly?: boolean;
+ isKafkaCluster?: boolean;
supportsRateLimits?: boolean;
supportsBacklogQuota?: boolean;
supportsRetention?: boolean;
@@ -37,6 +38,7 @@ const retentionForm = ref<RetentionPolicy>({ ...defaultForms.retentionForm });
const scope = computed<PolicyScope | null>(() => {
if (!props.tenant || !props.namespace) return null;
+ if (props.isKafkaCluster && !props.topic) return null;
if (props.topic) {
return {
level: "topic",
@@ -53,6 +55,8 @@ const scope = computed<PolicyScope | null>(() => {
};
});
+const scopePlaceholderMessage = computed(() => (props.isKafkaCluster ? "请先选择主题" : "请选择命名空间或主题"));
+
const scopeLabel = computed(() => {
const current = scope.value;
if (!current) return "";
@@ -97,7 +101,7 @@ async function applyPolicy(kind: string, action: (current: PolicyScope) => Promi
if (!guardWritable()) return;
const current = scope.value;
if (!current) {
- error.value = "请先选择命名空间或主题";
+ error.value = scopePlaceholderMessage.value;
return;
}
@@ -174,7 +178,7 @@ watch(
</button>
</div>
- <div v-if="!scope" class="panel-placeholder">请先选择命名空间或主题</div>
+ <div v-if="!scope" class="panel-placeholder">{{ scopePlaceholderMessage }}</div>
<div v-else class="policies-content">
<div v-if="readOnly" class="readonly-hint">当前连接为只读模式,策略编辑已禁用。</div>
diff --git a/apps/desktop/src/components/mq/ProducerConsumerPanel.vue b/apps/desktop/src/components/mq/ProducerConsumerPanel.vue
index b64601e0c9..913b918a6a 100644
--- a/apps/desktop/src/components/mq/ProducerConsumerPanel.vue
+++ b/apps/desktop/src/components/mq/ProducerConsumerPanel.vue
@@ -11,6 +11,7 @@ interface Props {
namespace?: string;
readOnly?: boolean;
selectedSubscription?: string;
+ isKafkaCluster?: boolean;
}
const props = defineProps<Props>();
@@ -46,6 +47,9 @@ const loading = ref(false);
const unloading = ref(false);
const error = ref<string>();
+let runtimeLoadSeq = 0;
+let consumerLoadSeq = 0;
+
const topicRef = computed<TopicRef | null>(() => {
if (!props.topic || !props.tenant || !props.namespace) return null;
return {
@@ -75,6 +79,8 @@ const displayedConsumers = computed(() => {
const selectedScopeLabel = computed(() => selectedPartition.value?.shortName ?? "聚合 topic");
async function loadRuntimeClients() {
+ const loadSeq = ++runtimeLoadSeq;
+ consumerLoadSeq++;
const current = topicRef.value;
if (!current) {
producers.value = [];
@@ -82,35 +88,47 @@ async function loadRuntimeClients() {
stats.value = undefined;
selectedSubscription.value = "";
selectedPartitionName.value = "";
+ loading.value = false;
+ error.value = undefined;
return;
}
+ const currentKey = topicRefKey(current);
loading.value = true;
error.value = undefined;
try {
const statsData = await mqGetTopicStats(props.connectionId, current);
+ if (!isRuntimeLoadCurrent(loadSeq, currentKey)) return;
stats.value = statsData;
const parsedProducers = extractProducersFromStats(statsData.raw);
producers.value = parsedProducers.length ? parsedProducers : await mqListProducers(props.connectionId, current);
+ if (!isRuntimeLoadCurrent(loadSeq, currentKey)) return;
const parsedSubscriptions = extractSubscriptionsFromStats(statsData.raw);
const partitionSubscriptions = mergeSubscriptionOptions([], extractPartitionClientRows(statsData.raw));
subscriptions.value = parsedSubscriptions.length || partitionSubscriptions.length ? mergeSubscriptionOptions(parsedSubscriptions, extractPartitionClientRows(statsData.raw)) : await mqListSubscriptions(props.connectionId, current);
- syncSelectedSubscription();
- if (selectedSubscription.value && !subscriptions.value.some((sub) => sub.name === selectedSubscription.value && sub.consumers.length > 0)) {
- await loadSelectedSubscriptionConsumers();
- }
+ if (!isRuntimeLoadCurrent(loadSeq, currentKey)) return;
+ const subscriptionChanged = syncSelectedSubscription();
syncSelectedPartition();
+ if (selectedSubscription.value && !subscriptionChanged && !hasConsumersForSelectedSubscription()) {
+ await loadSelectedSubscriptionConsumers({ retryIfEmpty: true });
+ if (!isRuntimeLoadCurrent(loadSeq, currentKey)) return;
+ syncSelectedPartition();
+ }
} catch (e: unknown) {
- error.value = formatError(e) || String(e);
+ if (isRuntimeLoadCurrent(loadSeq, currentKey)) {
+ error.value = formatError(e) || String(e);
+ }
} finally {
- loading.value = false;
+ if (loadSeq === runtimeLoadSeq) {
+ loading.value = false;
+ }
}
}
async function unloadTopic() {
const current = topicRef.value;
if (!current || props.readOnly || unloading.value) return;
- if (!confirm("确认 unload 当前 topic?活跃生产者和消费者会重新连接。")) return;
+ if (!confirm("确认卸载当前主题?活跃生产者和消费者会重新连接。")) return;
unloading.value = true;
error.value = undefined;
@@ -143,13 +161,15 @@ function formatOptionalBytes(value: number): string {
return isKafkaStats.value ? "-" : formatBytes(value);
}
-function syncSelectedSubscription() {
+function syncSelectedSubscription(): boolean {
+ const previous = selectedSubscription.value;
const options = subscriptionOptions.value;
if (props.selectedSubscription && options.some((sub) => sub.name === props.selectedSubscription)) {
selectedSubscription.value = props.selectedSubscription;
} else if (!options.some((sub) => sub.name === selectedSubscription.value)) {
selectedSubscription.value = options[0]?.name ?? "";
}
+ return previous !== selectedSubscription.value;
}
function syncSelectedPartition() {
@@ -175,11 +195,59 @@ function syncSelectedSubscriptionForPartition() {
selectedSubscription.value = (active ?? partition.subscriptions[0])?.name ?? selectedSubscription.value;
}
-async function loadSelectedSubscriptionConsumers() {
+interface LoadConsumersOptions {
+ retryIfEmpty?: boolean;
+}
+
+async function loadSelectedSubscriptionConsumers(options: LoadConsumersOptions = {}): Promise<ConsumerInfo[]> {
const current = topicRef.value;
- if (!current || !selectedSubscription.value) return;
- const consumers = await mqListConsumers(props.connectionId, current, selectedSubscription.value);
- subscriptions.value = subscriptions.value.map((sub) => (sub.name === selectedSubscription.value ? { ...sub, consumers } : sub));
+ const subscriptionName = selectedSubscription.value;
+ if (!current || !subscriptionName) return [];
+
+ const loadSeq = ++consumerLoadSeq;
+ const currentKey = topicRefKey(current);
+ let consumers = await mqListConsumers(props.connectionId, current, subscriptionName);
+ if (!isConsumerLoadCurrent(loadSeq, currentKey, subscriptionName)) return [];
+ applySubscriptionConsumers(subscriptionName, consumers);
+
+ if (options.retryIfEmpty && consumers.length === 0) {
+ await sleep(700);
+ if (!isConsumerLoadCurrent(loadSeq, currentKey, subscriptionName)) return consumers;
+ consumers = await mqListConsumers(props.connectionId, current, subscriptionName);
+ if (!isConsumerLoadCurrent(loadSeq, currentKey, subscriptionName)) return [];
+ applySubscriptionConsumers(subscriptionName, consumers);
+ }
+
+ return consumers;
+}
+
+function applySubscriptionConsumers(subscriptionName: string, consumers: ConsumerInfo[]) {
+ subscriptions.value = subscriptions.value.map((sub) => (sub.name === subscriptionName ? { ...sub, consumers } : sub));
+}
+
+function hasConsumersForSelectedSubscription(): boolean {
+ return subscriptions.value.some((sub) => sub.name === selectedSubscription.value && sub.consumers.length > 0);
+}
+
+function topicRefKey(topic: TopicRef): string {
+ return [topic.tenant, topic.namespace, topic.topic, topic.persistent ? "1" : "0", topic.partitioned ? "1" : "0"].join("|");
+}
+
+function isRuntimeLoadCurrent(loadSeq: number, topicKey: string): boolean {
+ return loadSeq === runtimeLoadSeq && isCurrentTopic(topicKey);
+}
+
+function isConsumerLoadCurrent(loadSeq: number, topicKey: string, subscriptionName: string): boolean {
+ return loadSeq === consumerLoadSeq && selectedSubscription.value === subscriptionName && isCurrentTopic(topicKey);
+}
+
+function isCurrentTopic(topicKey: string): boolean {
+ const current = topicRef.value;
+ return !!current && topicRefKey(current) === topicKey;
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
}
function extractProducersFromStats(raw: unknown): ProducerInfo[] {
@@ -326,7 +394,7 @@ watch(
watch(selectedSubscription, () => {
syncSelectedPartition();
- void loadSelectedSubscriptionConsumers().catch((e: unknown) => {
+ void loadSelectedSubscriptionConsumers({ retryIfEmpty: true }).catch((e: unknown) => {
error.value = formatError(e) || String(e);
});
});
@@ -350,8 +418,8 @@ watch(
<div class="panel-toolbar">
<h3>生产者 / 消费者</h3>
<div class="toolbar-actions">
- <button class="btn-sm danger" :disabled="readOnly || !topic || unloading" @click="unloadTopic">
- {{ unloading ? "卸载中..." : "Unload topic" }}
+ <button v-if="!isKafkaCluster" class="btn-sm danger" :disabled="readOnly || !topic || unloading" @click="unloadTopic">
+ {{ unloading ? "卸载中..." : "卸载主题" }}
</button>
<button class="btn-sm" :disabled="loading || !topic" @click="loadRuntimeClients">
{{ loading ? "刷新中..." : "刷新" }}
diff --git a/apps/desktop/src/components/mq/SendMessagePanel.vue b/apps/desktop/src/components/mq/SendMessagePanel.vue
index ea424a5f8d..30d6ab7739 100644
--- a/apps/desktop/src/components/mq/SendMessagePanel.vue
+++ b/apps/desktop/src/components/mq/SendMessagePanel.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed, onUnmounted, ref, watch } from "vue";
-import type { TopicInfo, SendMessageRequest, SendMessageResponse } from "@/types/mq";
-import { mqSendMessage, mqListTopics } from "@/lib/api";
+import type { PeekedMessage, TopicInfo, TopicRef, SendMessageRequest, SendMessageResponse } from "@/types/mq";
+import { mqSendMessage, mqListTopics, mqPeekMessages } from "@/lib/api";
import { formatError } from "@/lib/errorUtils";
interface Props {
@@ -10,6 +10,8 @@ interface Props {
namespace?: string;
topic?: TopicInfo;
readOnly?: boolean;
+ isKafkaCluster?: boolean;
+ supportsPeekMessages?: boolean;
}
const props = defineProps<Props>();
@@ -24,6 +26,12 @@ const success = ref<SendMessageResponse>();
const availableTopics = ref<TopicInfo[]>([]);
const topicsLoading = ref(false);
const headersExpanded = ref(false);
+const peekLoading = ref(false);
+const peekError = ref<string>();
+const peekMessages = ref<PeekedMessage[]>([]);
+const peekPartition = ref(0);
+const peekOffset = ref(0);
+const peekCount = ref(20);
let successTimer: ReturnType<typeof setTimeout> | undefined;
@@ -37,6 +45,21 @@ const topicOptions = computed(() => {
}));
});
+const selectedTopicRef = computed<TopicRef | null>(() => {
+ const topic = topicName.value.trim();
+ if (!topic || !props.tenant || !props.namespace) return null;
+ const selected = availableTopics.value.find((item) => item.shortName === topic);
+ return {
+ tenant: props.tenant,
+ namespace: props.namespace,
+ topic,
+ persistent: selected?.persistent ?? true,
+ partitioned: selected?.partitioned,
+ };
+});
+
+const canBrowseMessages = computed(() => props.isKafkaCluster === true && props.supportsPeekMessages !== false);
+
function clearSuccessLater() {
if (successTimer) clearTimeout(successTimer);
successTimer = setTimeout(() => {
@@ -119,6 +142,11 @@ async function sendMessage() {
headers,
};
success.value = await mqSendMessage(props.connectionId, req);
+ if (canBrowseMessages.value) {
+ peekPartition.value = success.value.partition;
+ peekOffset.value = success.value.offset;
+ void loadMessages();
+ }
messageValue.value = "";
messageKey.value = "";
clearSuccessLater();
@@ -129,6 +157,40 @@ async function sendMessage() {
}
}
+async function loadMessages() {
+ const topic = selectedTopicRef.value;
+ if (!topic) {
+ peekError.value = "Select a topic before loading messages";
+ return;
+ }
+ peekLoading.value = true;
+ peekError.value = undefined;
+ try {
+ const count = Math.max(1, Math.min(100, Number(peekCount.value) || 20));
+ const partition = Math.max(0, Number(peekPartition.value) || 0);
+ const offset = Math.max(0, Number(peekOffset.value) || 0);
+ peekCount.value = count;
+ peekPartition.value = partition;
+ peekOffset.value = offset;
+ peekMessages.value = await mqPeekMessages(props.connectionId, topic, "__dbx_kafka_viewer__", count, { partition, offset });
+ } catch (e: unknown) {
+ peekError.value = formatError(e);
+ } finally {
+ peekLoading.value = false;
+ }
+}
+
+function messagePayload(message: PeekedMessage): string {
+ return message.payloadText ?? message.payloadBase64;
+}
+
+function formatMessageTimestamp(value?: string): string {
+ if (!value) return "-";
+ const numeric = Number(value);
+ if (!Number.isFinite(numeric)) return value;
+ return new Date(numeric).toLocaleString();
+}
+
function formatJson() {
try {
const parsed = JSON.parse(messageValue.value);
@@ -155,6 +217,11 @@ watch(
{ immediate: true },
);
+watch(topicName, () => {
+ peekError.value = undefined;
+ peekMessages.value = [];
+});
+
watch(
() => props.topic,
(newTopic) => {
@@ -233,6 +300,48 @@ watch(
{{ loading ? "发送中..." : "发送消息" }}
</button>
</div>
+
+ <section v-if="canBrowseMessages" class="message-browser">
+ <div class="message-browser-header">
+ <h4>消息列表</h4>
+ <button type="button" class="btn-sm" :disabled="peekLoading || !selectedTopicRef" @click="loadMessages">
+ {{ peekLoading ? "加载中..." : "加载消息" }}
+ </button>
+ </div>
+
+ <div class="peek-controls">
+ <label>
+ <span>分区</span>
+ <input v-model.number="peekPartition" type="number" min="0" :disabled="peekLoading" />
+ </label>
+ <label>
+ <span>Offset</span>
+ <input v-model.number="peekOffset" type="number" min="0" :disabled="peekLoading" />
+ </label>
+ <label>
+ <span>数量</span>
+ <input v-model.number="peekCount" type="number" min="1" max="100" :disabled="peekLoading" />
+ </label>
+ </div>
+
+ <div v-if="peekError" class="panel-error">{{ peekError }}</div>
+ <div v-else-if="peekLoading" class="message-empty">消息加载中...</div>
+ <div v-else-if="!peekMessages.length" class="message-empty">暂无消息</div>
+ <div v-else class="message-list">
+ <article v-for="message in peekMessages" :key="message.messageId || message.position" class="message-row">
+ <div class="message-meta">
+ <span>#{{ message.position }}</span>
+ <span>offset {{ message.messageId || "-" }}</span>
+ <span v-if="message.key">key {{ message.key }}</span>
+ <span>{{ formatMessageTimestamp(message.publishTime) }}</span>
+ </div>
+ <pre class="message-payload">{{ messagePayload(message) }}</pre>
+ <div v-if="Object.keys(message.headers || {}).length" class="message-headers">
+ <span v-for="(value, key) in message.headers" :key="key">{{ key }}: {{ value }}</span>
+ </div>
+ </article>
+ </div>
+ </section>
</div>
</div>
</template>
@@ -406,7 +515,8 @@ watch(
}
}
-input[type="text"] {
+input[type="text"],
+input[type="number"] {
padding: 7px 10px;
border: 1px solid var(--color-border);
border-radius: 6px;
@@ -416,7 +526,8 @@ input[type="text"] {
box-sizing: border-box;
}
-input[type="text"]:focus {
+input[type="text"]:focus,
+input[type="number"]:focus {
outline: none;
border-color: var(--color-primary);
box-shadow: 0 0 0 2px var(--color-primary-alpha);
@@ -522,6 +633,124 @@ input[type="text"]:focus {
opacity: 0.9;
}
+.message-browser {
+ margin-top: 4px;
+ padding: 14px;
+ border: 1px solid var(--color-border);
+ border-radius: 8px;
+ background: var(--color-background-secondary);
+}
+
+.message-browser-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ margin-bottom: 12px;
+}
+
+.message-browser-header h4 {
+ margin: 0;
+ color: var(--color-text);
+ font-size: 14px;
+ font-weight: 600;
+}
+
+.peek-controls {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 10px;
+ margin-bottom: 12px;
+}
+
+.peek-controls label {
+ display: flex;
+ flex-direction: column;
+ gap: 5px;
+ color: var(--color-text-secondary);
+ font-size: 12px;
+ font-weight: 500;
+}
+
+.peek-controls input {
+ width: 100%;
+}
+
+.message-empty {
+ padding: 18px;
+ border: 1px dashed var(--color-border);
+ border-radius: 6px;
+ color: var(--color-text-tertiary);
+ text-align: center;
+ font-size: 13px;
+}
+
+.message-list {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ max-height: 360px;
+ overflow: auto;
+}
+
+.message-row {
+ padding: 10px 12px;
+ border: 1px solid var(--color-border);
+ border-radius: 6px;
+ background: var(--color-background);
+}
+
+.message-meta {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ flex-wrap: wrap;
+ color: var(--color-text-tertiary);
+ font-size: 12px;
+}
+
+.message-meta span:first-child {
+ color: var(--color-primary);
+ font-weight: 700;
+}
+
+.message-payload {
+ margin: 8px 0 0;
+ padding: 10px;
+ max-height: 160px;
+ overflow: auto;
+ border-radius: 6px;
+ background: var(--color-background-tertiary, var(--color-background-secondary));
+ color: var(--color-text);
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
+ font-size: 12px;
+ line-height: 1.5;
+ white-space: pre-wrap;
+ word-break: break-word;
+}
+
+.message-headers {
+ display: flex;
+ gap: 6px;
+ flex-wrap: wrap;
+ margin-top: 8px;
+}
+
+.message-headers span {
+ padding: 2px 6px;
+ border: 1px solid var(--color-border);
+ border-radius: 4px;
+ color: var(--color-text-secondary);
+ background: var(--color-background-secondary);
+ font-size: 12px;
+}
+
+@media (max-width: 720px) {
+ .peek-controls {
+ grid-template-columns: 1fr;
+ }
+}
+
button:disabled,
input:disabled,
textarea:disabled,
diff --git a/apps/desktop/src/components/mq/TopicsPanel.vue b/apps/desktop/src/components/mq/TopicsPanel.vue
index ebf24cbf5b..3d2731087d 100644
--- a/apps/desktop/src/components/mq/TopicsPanel.vue
+++ b/apps/desktop/src/components/mq/TopicsPanel.vue
@@ -10,6 +10,7 @@ interface Props {
namespace?: string;
readOnly?: boolean;
supportsPartitionedTopics?: boolean;
+ isKafkaCluster?: boolean;
}
const props = defineProps<Props>();
@@ -77,7 +78,7 @@ function openCreateDialog() {
formData.value = {
topicName: "",
persistent: true,
- partitioned: false,
+ partitioned: props.isKafkaCluster ?? false,
partitions: 4,
};
showCreateDialog.value = true;
@@ -205,7 +206,12 @@ watch(includeNonPersistent, () => {
包含非持久化主题
</label>
</div>
- <button @click="openCreateDialog" :disabled="loading || readOnly || !tenant || !namespace" class="btn-primary">+ 创建主题</button>
+ <div class="toolbar-actions">
+ <button @click="loadTopics" :disabled="loading || !tenant || !namespace" class="btn-secondary">
+ {{ loading ? "刷新中..." : "刷新" }}
+ </button>
+ <button @click="openCreateDialog" :disabled="loading || readOnly || !tenant || !namespace" class="btn-primary">+ 创建主题</button>
+ </div>
</div>
<div v-if="!tenant || !namespace" class="panel-placeholder">请先选择租户和命名空间</div>
@@ -260,7 +266,7 @@ watch(includeNonPersistent, () => {
<button @click="showCreateDialog = false" class="btn-close">×</button>
</div>
<div class="dialog-body">
- <div class="form-group">
+ <div v-if="!isKafkaCluster" class="form-group">
<label>租户 / 命名空间</label>
<input type="text" :value="`${tenant} / ${namespace}`" disabled />
</div>
@@ -344,6 +350,12 @@ watch(includeNonPersistent, () => {
gap: 16px;
}
+.toolbar-actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
.toolbar-left h3 {
margin: 0;
font-size: 16px;
@@ -377,6 +389,7 @@ watch(includeNonPersistent, () => {
.topics-table {
flex: 1;
overflow: auto;
+ background: var(--color-background);
}
table {
@@ -392,12 +405,17 @@ thead {
}
th {
+ position: sticky;
+ top: 0;
+ z-index: 2;
padding: 10px 12px;
text-align: left;
font-weight: 600;
font-size: 13px;
color: var(--color-text-secondary);
+ background: var(--color-background-secondary);
border-bottom: 1px solid var(--color-border);
+ box-shadow: 0 1px 0 var(--color-border);
}
tbody tr {
diff --git a/apps/desktop/src/lib/agentDriverInstallHint.ts b/apps/desktop/src/lib/agentDriverInstallHint.ts
index 06290148f7..2477c88aeb 100644
--- a/apps/desktop/src/lib/agentDriverInstallHint.ts
+++ b/apps/desktop/src/lib/agentDriverInstallHint.ts
@@ -7,7 +7,7 @@ export interface AgentDriverInstallState {
update_available?: boolean;
}
-function agentDriverInstallKey(dbType: DatabaseType | undefined, driverProfile?: string): string | undefined {
+export function agentDriverInstallKey(dbType: DatabaseType | undefined, driverProfile?: string): string | undefined {
if (dbType === "oracle") return "oracle";
if (dbType === "mongodb") return "mongodb";
if (dbType === "dameng") return "dameng";
diff --git a/apps/desktop/src/lib/mq-http.ts b/apps/desktop/src/lib/mq-http.ts
index c4f1f606b4..54fa0b21b5 100644
--- a/apps/desktop/src/lib/mq-http.ts
+++ b/apps/desktop/src/lib/mq-http.ts
@@ -30,6 +30,7 @@ import type {
MqIssuedToken,
BacklogStats,
PeekedMessage,
+ PeekMessagesOptions,
MqRawRequest,
MqRawResponse,
SendMessageRequest,
@@ -137,8 +138,8 @@ export async function mqClearBacklog(connectionId: string, topic: TopicRef, sub:
return post("/api/mq/subscriptions/clear-backlog", { connectionId, topic, sub });
}
-export async function mqPeekMessages(connectionId: string, topic: TopicRef, sub: string, count: number): Promise<PeekedMessage[]> {
- return post("/api/mq/subscriptions/peek-messages", { connectionId, topic, sub, count });
+export async function mqPeekMessages(connectionId: string, topic: TopicRef, sub: string, count: number, options?: PeekMessagesOptions): Promise<PeekedMessage[]> {
+ return post("/api/mq/subscriptions/peek-messages", { connectionId, topic, sub, count, options });
}
export async function mqExpireMessages(connectionId: string, topic: TopicRef, sub: string, expireSeconds: number): Promise<void> {
diff --git a/apps/desktop/src/lib/mq-tauri.ts b/apps/desktop/src/lib/mq-tauri.ts
index ad2df91c99..2472810bd8 100644
--- a/apps/desktop/src/lib/mq-tauri.ts
+++ b/apps/desktop/src/lib/mq-tauri.ts
@@ -30,6 +30,7 @@ import type {
MqIssuedToken,
BacklogStats,
PeekedMessage,
+ PeekMessagesOptions,
MqRawRequest,
MqRawResponse,
SendMessageRequest,
@@ -129,8 +130,8 @@ export async function mqClearBacklog(connectionId: string, topic: TopicRef, sub:
return invoke("mq_clear_backlog", { connectionId, topic, sub });
}
-export async function mqPeekMessages(connectionId: string, topic: TopicRef, sub: string, count: number): Promise<PeekedMessage[]> {
- return invoke("mq_peek_messages", { connectionId, topic, sub, count });
+export async function mqPeekMessages(connectionId: string, topic: TopicRef, sub: string, count: number, options?: PeekMessagesOptions): Promise<PeekedMessage[]> {
+ return invoke("mq_peek_messages", { connectionId, topic, sub, count, options });
}
export async function mqExpireMessages(connectionId: string, topic: TopicRef, sub: string, expireSeconds: number): Promise<void> {
diff --git a/apps/desktop/src/types/mq.ts b/apps/desktop/src/types/mq.ts
index 36da99c462..08a20baece 100644
--- a/apps/desktop/src/types/mq.ts
+++ b/apps/desktop/src/types/mq.ts
@@ -218,6 +218,11 @@ export interface PeekedMessage {
payloadText?: string;
}
+export interface PeekMessagesOptions {
+ partition?: number;
+ offset?: number;
+}
+
// Policy scope
export type PolicyScope = { level: "namespace"; tenant: string; namespace: string } | { level: "topic"; tenant: string; namespace: string; topic: string; persistent: boolean };
diff --git a/crates/dbx-core/src/agent_manager.rs b/crates/dbx-core/src/agent_manager.rs
index b22e514f3e..e702a6328a 100644
--- a/crates/dbx-core/src/agent_manager.rs
+++ b/crates/dbx-core/src/agent_manager.rs
@@ -1,4 +1,6 @@
use std::ffi::OsStr;
+use std::fs::File;
+use std::io::Read;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
@@ -15,6 +17,23 @@ fn default_jre_key() -> String {
DEFAULT_JRE_KEY.to_string()
}
+fn is_valid_jar_file(path: &Path) -> bool {
+ if !path.is_file() {
+ return false;
+ }
+ let Some(file) = File::open(path).ok() else {
+ return false;
+ };
+ let Some(mut archive) = zip::ZipArchive::new(file).ok() else {
+ return false;
+ };
+ let Some(mut manifest) = archive.by_name("META-INF/MANIFEST.MF").ok() else {
+ return false;
+ };
+ let mut manifest_text = String::new();
+ manifest.read_to_string(&mut manifest_text).is_ok() && manifest_text.contains("Main-Class:")
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentRegistry {
#[serde(default)]
@@ -539,13 +558,17 @@ impl AgentManager {
}
pub fn is_driver_installed(&self, db_type: &str) -> bool {
- self.driver_jar_path(db_type).exists()
+ self.is_driver_jar_valid(db_type)
|| self.driver_native_path(db_type).exists()
|| self.driver_launch_config_path(db_type).exists()
}
+ pub fn is_driver_jar_valid(&self, db_type: &str) -> bool {
+ is_valid_jar_file(&self.driver_jar_path(db_type))
+ }
+
pub fn driver_requires_java_runtime(&self, db_type: &str) -> bool {
- self.driver_jar_path(db_type).exists()
+ self.is_driver_jar_valid(db_type)
&& !self.driver_native_path(db_type).exists()
&& !self.driver_launch_config_path(db_type).exists()
}
@@ -570,6 +593,11 @@ impl AgentManager {
let jar_path = self.driver_jar_path(driver_key);
if jar_path.exists() {
let java = self.resolve_java_runtime(state, jre_key)?;
+ if !is_valid_jar_file(&jar_path) {
+ return Err(format!(
+ "{driver_key} driver jar is invalid or corrupt. Please reinstall it from the Driver Manager."
+ ));
+ }
return Ok(AgentLaunchSpec::java_jar(java, jar_path));
}
diff --git a/crates/dbx-core/src/agent_service.rs b/crates/dbx-core/src/agent_service.rs
index 8c175e5639..c1752e091c 100644
--- a/crates/dbx-core/src/agent_service.rs
+++ b/crates/dbx-core/src/agent_service.rs
@@ -183,12 +183,18 @@ pub fn build_agent_list(am: &AgentManager, registry: Option<&AgentRegistry>) ->
let use_managed_jre = local_state.java_runtime.mode == JavaRuntimeMode::Managed;
agent_catalog::driver_store_entries()
.map(|(key, label)| {
- let installed = am.is_driver_installed(key);
+ let jar_valid = am.is_driver_jar_valid(key);
+ let native_installed = am.driver_native_path(key).exists();
+ let launch_config_installed = am.driver_launch_config_path(key).exists();
+ let installed = jar_valid || native_installed || launch_config_installed;
let local = local_state.installed_drivers.get(key);
let remote = registry.and_then(|r| agent_registry_driver(r, key));
let remote_requires_java_runtime = remote.is_some_and(remote_driver_requires_java_runtime);
- let requires_java_runtime =
- if installed { am.driver_requires_java_runtime(key) } else { remote_requires_java_runtime };
+ let requires_java_runtime = if installed {
+ jar_valid && !native_installed && !launch_config_installed
+ } else {
+ remote_requires_java_runtime
+ };
let jre_key = remote
.map(|r| r.jre.clone())
.or_else(|| local.map(|l| l.jre.clone()))
@@ -299,6 +305,10 @@ pub fn install_local_agent(am: &AgentManager, db_type: &str, source: PathBuf) ->
let parent = jar_path.parent().ok_or_else(|| format!("Invalid driver path: {}", jar_path.display()))?;
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
std::fs::copy(&source, &jar_path).map_err(|e| format!("Failed to copy local agent jar: {e}"))?;
+ if !am.is_driver_jar_valid(db_type) {
+ std::fs::remove_file(&jar_path).ok();
+ return Err(format!("Local agent jar is invalid or corrupt: {}", source.display()));
+ }
let mut local_state = am.load_state();
local_state.installed_drivers.insert(
@@ -488,7 +498,25 @@ async fn install_agent_driver_with_batch(
) -> Result<(), String> {
match fetch_registry().await {
Ok(registry) => {
- install_agent_driver_from_registry(am, &registry, db_type, progress, current, total_drivers).await
+ match install_agent_driver_from_registry(am, &registry, db_type, progress, current, total_drivers).await {
+ Ok(()) => Ok(()),
+ Err(registry_err) => {
+ if let Some(local_jar) = find_local_agent_jar(db_type) {
+ install_local_agent_with_registry_jre(
+ am,
+ &registry,
+ db_type,
+ local_jar,
+ progress,
+ current,
+ total_drivers,
+ )
+ .await?;
+ return Ok(());
+ }
+ Err(registry_err)
+ }
+ }
}
Err(registry_err) => {
if let Some(local_jar) = find_local_agent_jar(db_type) {
@@ -502,6 +530,75 @@ async fn install_agent_driver_with_batch(
}
}
+async fn ensure_jre_from_registry(
+ am: &AgentManager,
+ registry: &AgentRegistry,
+ jre_key: &str,
+ db_type: &str,
+ progress: &impl Fn(AgentProgressEvent),
+ current: Option<u32>,
+ total_drivers: Option<u32>,
+) -> Result<(), String> {
+ let jre_info = registry.resolve_jre(jre_key).ok_or_else(|| format!("No JRE definition for version: {jre_key}"))?;
+ let platform = AgentManager::current_platform();
+ let platform_jre = jre_info
+ .platforms
+ .get(platform)
+ .ok_or_else(|| format!("No JRE {jre_key} available for platform: {platform}"))?;
+ let jre_archive = am.base_dir().join("jre-download.tar.gz");
+ progress(AgentProgressEvent::transfer("jre", 0, platform_jre.size).with_batch(
+ Some(db_type),
+ current,
+ total_drivers,
+ ));
+ download_with_progress(
+ am,
+ progress,
+ "jre",
+ &platform_jre.url,
+ &r2_path_with_cache_buster(&github_url_to_r2_path(&platform_jre.url, "jre"), &jre_info.version),
+ &jre_archive,
+ platform_jre.size,
+ Some(CacheIdentity::Jre { key: jre_key, version: &jre_info.version }),
+ Some(db_type),
+ current,
+ total_drivers,
+ )
+ .await?;
+ progress(AgentProgressEvent::transfer("jre-extract", 0, 0).with_batch(Some(db_type), current, total_drivers));
+ let jre_dir = am.jre_dir(jre_key);
+ // Stop daemons first (Windows ERROR_ACCESS_DENIED, Issue #1100).
+ am.stop_daemons().await;
+ replace_old_jre_dir(am, &jre_dir)?;
+ extract_tar_gz(&jre_archive, &jre_dir)?;
+ std::fs::remove_file(&jre_archive).ok();
+ Ok(())
+}
+
+async fn install_local_agent_with_registry_jre(
+ am: &AgentManager,
+ registry: &AgentRegistry,
+ db_type: &str,
+ local_jar: PathBuf,
+ progress: &impl Fn(AgentProgressEvent),
+ current: Option<u32>,
+ total_drivers: Option<u32>,
+) -> Result<(), String> {
+ let jre_key = DEFAULT_JRE_KEY;
+ if jre_needs_install(am, registry, jre_key) {
+ ensure_jre_from_registry(am, registry, jre_key, db_type, progress, current, total_drivers).await?;
+ }
+ install_local_agent(am, db_type, local_jar)?;
+ if let Some(jre_info) = registry.resolve_jre(jre_key) {
+ let mut local_state = am.load_state();
+ local_state.jre_versions.insert(jre_key.to_string(), jre_info.version.clone());
+ am.save_state(&local_state)?;
+ }
+ am.stop_daemon_by_key(db_type).await;
+ progress(AgentProgressEvent::step("done"));
+ Ok(())
+}
+
async fn install_agent_driver_from_registry(
am: &AgentManager,
registry: &AgentRegistry,
@@ -512,9 +609,8 @@ async fn install_agent_driver_from_registry(
) -> Result<(), String> {
let Some(driver) = agent_registry_driver(registry, db_type) else {
if let Some(local_jar) = find_local_agent_jar(db_type) {
- install_local_agent(am, db_type, local_jar)?;
- am.stop_daemon_by_key(db_type).await;
- progress(AgentProgressEvent::step("done"));
+ install_local_agent_with_registry_jre(am, registry, db_type, local_jar, progress, current, total_drivers)
+ .await?;
return Ok(());
}
return Err(format!("Unknown driver type: {db_type}"));
@@ -526,40 +622,7 @@ async fn install_agent_driver_from_registry(
let needs_jre = requires_java_runtime && jre_needs_install(am, registry, jre_key);
if needs_jre {
- let jre_info =
- registry.resolve_jre(jre_key).ok_or_else(|| format!("No JRE definition for version: {jre_key}"))?;
- let platform = AgentManager::current_platform();
- let platform_jre = jre_info
- .platforms
- .get(platform)
- .ok_or_else(|| format!("No JRE {jre_key} available for platform: {platform}"))?;
- let jre_archive = am.base_dir().join("jre-download.tar.gz");
- progress(AgentProgressEvent::transfer("jre", 0, platform_jre.size).with_batch(
- Some(db_type),
- current,
- total_drivers,
- ));
- download_with_progress(
- am,
- progress,
- "jre",
- &platform_jre.url,
- &r2_path_with_cache_buster(&github_url_to_r2_path(&platform_jre.url, "jre"), &jre_info.version),
- &jre_archive,
- platform_jre.size,
- Some(CacheIdentity::Jre { key: jre_key, version: &jre_info.version }),
- Some(db_type),
- current,
- total_drivers,
- )
- .await?;
- progress(AgentProgressEvent::transfer("jre-extract", 0, 0).with_batch(Some(db_type), current, total_drivers));
- let jre_dir = am.jre_dir(jre_key);
- // Stop daemons first (Windows ERROR_ACCESS_DENIED, Issue #1100).
- am.stop_daemons().await;
- replace_old_jre_dir(am, &jre_dir)?;
- extract_tar_gz(&jre_archive, &jre_dir)?;
- std::fs::remove_file(&jre_archive).ok();
+ ensure_jre_from_registry(am, registry, jre_key, db_type, progress, current, total_drivers).await?;
}
let (artifact, target_path) = if let Some(native) = native_artifact {
@@ -591,6 +654,10 @@ async fn install_agent_driver_from_registry(
total_drivers,
)
.await?;
+ if jar_artifact.is_some() && !am.is_driver_jar_valid(db_type) {
+ std::fs::remove_file(&target_path).ok();
+ return Err(format!("Downloaded driver jar is invalid or corrupt: {}", target_path.display()));
+ }
if native_artifact.is_some() {
mark_executable(&target_path)?;
std::fs::remove_file(am.driver_jar_path(db_type)).ok();
@@ -1161,6 +1228,11 @@ pub fn import_offline_zip(
mark_executable(&driver_path)?;
std::fs::remove_file(am.driver_jar_path(db_type)).ok();
} else {
+ // Offline bundles are user-supplied; reject corrupt JARs before state says the driver is installed.
+ if !am.is_driver_jar_valid(db_type) {
+ std::fs::remove_file(&driver_path).ok();
+ return Err(format!("Offline agent jar is invalid or corrupt: {entry_name}"));
+ }
std::fs::remove_file(am.driver_native_path(db_type)).ok();
}
diff --git a/crates/dbx-core/src/connection.rs b/crates/dbx-core/src/connection.rs
index 0e95d5da67..1ffdd4ff74 100644
--- a/crates/dbx-core/src/connection.rs
+++ b/crates/dbx-core/src/connection.rs
@@ -1039,8 +1039,17 @@ impl AppState {
// connection_id is recognized as valid.
let mqc = self.mq_admin_config_for_connection(connection_id, &config).await?;
let kafka_launch = crate::mq::service::resolve_kafka_launch_spec(&mqc, self);
- let adapter = self.mq_registry.build_transient_config(mqc, kafka_launch).await?;
- adapter.test_connection().await?;
+ let adapter = match self.mq_registry.get_or_build_config(connection_id, mqc, kafka_launch).await {
+ Ok(adapter) => adapter,
+ Err(err) => {
+ self.mq_registry.drop_connection(connection_id).await;
+ return Err(err);
+ }
+ };
+ if let Err(err) = adapter.test_connection().await {
+ self.mq_registry.drop_connection(connection_id).await;
+ return Err(err);
+ }
PoolKind::MessageQueue
}
#[cfg(not(feature = "mq-admin"))]
diff --git a/crates/dbx-core/src/mq/adapters/kafka.rs b/crates/dbx-core/src/mq/adapters/kafka.rs
index 8b72406de0..8fe25f7d00 100644
--- a/crates/dbx-core/src/mq/adapters/kafka.rs
+++ b/crates/dbx-core/src/mq/adapters/kafka.rs
@@ -300,15 +300,21 @@ impl MessageQueueAdmin for KafkaAdmin {
.await
}
- async fn peek_messages(&self, topic: &TopicRef, _sub: &str, count: u32) -> Result<Vec<PeekedMessage>, String> {
+ async fn peek_messages(
+ &self,
+ topic: &TopicRef,
+ _sub: &str,
+ count: u32,
+ options: PeekMessagesOptions,
+ ) -> Result<Vec<PeekedMessage>, String> {
let conn_params = build_connection_params(&self.config);
let result: serde_json::Value = self
.call(
"mq_peek_messages",
serde_json::json!({
"topic": topic.topic,
- "partition": 0,
- "offset": 0,
+ "partition": options.partition.unwrap_or(0),
+ "offset": options.offset.unwrap_or(0),
"count": count,
"connection": conn_params,
}),
@@ -347,7 +353,14 @@ impl MessageQueueAdmin for KafkaAdmin {
async fn list_producers(&self, topic: &TopicRef) -> Result<Vec<ProducerInfo>, String> {
let result: serde_json::Value =
- self.call("mq_list_producers", serde_json::json!({ "topic": topic.topic })).await?;
+ match self.call("mq_list_producers", serde_json::json!({ "topic": topic.topic })).await {
+ Ok(result) => result,
+ Err(err) if is_describe_producers_unsupported(&err) => {
+ log::info!("Kafka broker does not support DESCRIBE_PRODUCERS; active producers are unavailable");
+ return Ok(Vec::new());
+ }
+ Err(err) => return Err(err),
+ };
let producers = result.get("producers").and_then(|v| v.as_array()).cloned().unwrap_or_default();
Ok(producers
.into_iter()
@@ -381,7 +394,7 @@ impl MessageQueueAdmin for KafkaAdmin {
}
async fn unload_topic(&self, _topic: &TopicRef) -> Result<(), String> {
- Err("Kafka does not support unloading topics".to_string())
+ Err("Kafka 不支持卸载主题".to_string())
}
// ---- Rate limits / quotas / retention ----
@@ -612,6 +625,12 @@ fn extra_str<'a>(extra: &'a serde_json::Value, key: &str) -> Option<&'a str> {
extra.get(key).and_then(|v| v.as_str()).filter(|v| !v.trim().is_empty())
}
+fn is_describe_producers_unsupported(message: &str) -> bool {
+ let normalized = message.to_ascii_lowercase();
+ (normalized.contains("unsupportedversionexception") && normalized.contains("describe_producers"))
+ || normalized.contains("the node does not support describe_producers")
+}
+
/// Build the connection params JSON from MqAdminConfig for the Java agent.
fn build_connection_params(cfg: &MqAdminConfig) -> serde_json::Value {
let extra = &cfg.extra;
@@ -624,8 +643,11 @@ fn build_connection_params(cfg: &MqAdminConfig) -> serde_json::Value {
let sasl_password =
extra_str(extra, "saslPassword").or_else(|| basic_auth.map(|(_, password)| password)).unwrap_or("");
let sasl_mechanism = extra_str(extra, "saslMechanism").unwrap_or(if basic_auth.is_some() { "PLAIN" } else { "" });
- let security_protocol =
- extra_str(extra, "securityProtocol").unwrap_or(if !sasl_mechanism.is_empty() { "SASL_PLAINTEXT" } else { "" });
+ let security_protocol = extra_str(extra, "securityProtocol").unwrap_or(if !sasl_mechanism.is_empty() {
+ "SASL_PLAINTEXT"
+ } else {
+ "PLAINTEXT"
+ });
let properties =
extra.get("properties").filter(|value| value.is_object()).cloned().unwrap_or_else(|| serde_json::json!({}));
diff --git a/crates/dbx-core/src/mq/adapters/pulsar.rs b/crates/dbx-core/src/mq/adapters/pulsar.rs
index f9a635f14c..5cc0fda3c4 100644
--- a/crates/dbx-core/src/mq/adapters/pulsar.rs
+++ b/crates/dbx-core/src/mq/adapters/pulsar.rs
@@ -439,7 +439,13 @@ impl MessageQueueAdmin for PulsarAdmin {
self.send_empty(reqwest::Method::POST, &path, None, None).await
}
- async fn peek_messages(&self, topic: &TopicRef, sub: &str, count: u32) -> Result<Vec<PeekedMessage>, String> {
+ async fn peek_messages(
+ &self,
+ topic: &TopicRef,
+ sub: &str,
+ count: u32,
+ _options: PeekMessagesOptions,
+ ) -> Result<Vec<PeekedMessage>, String> {
if count == 0 {
return Ok(Vec::new());
}
diff --git a/crates/dbx-core/src/mq/mod.rs b/crates/dbx-core/src/mq/mod.rs
index db4ce0aaef..e58b438bc6 100644
--- a/crates/dbx-core/src/mq/mod.rs
+++ b/crates/dbx-core/src/mq/mod.rs
@@ -20,6 +20,7 @@ pub mod types;
pub(crate) mod util;
use std::collections::HashMap;
+use std::hash::{Hash, Hasher};
use std::sync::Arc;
use tokio::sync::{Mutex, RwLock};
@@ -44,10 +45,15 @@ pub use crate::mq::types::*;
/// racing to construct an adapter.
#[derive(Default)]
pub struct MqAdminRegistry {
- instances: RwLock<HashMap<String, Arc<dyn MessageQueueAdmin>>>,
+ instances: RwLock<HashMap<String, CachedMqAdmin>>,
build_locks: RwLock<HashMap<String, Arc<Mutex<()>>>>,
}
+struct CachedMqAdmin {
+ fingerprint: u64,
+ adapter: Arc<dyn MessageQueueAdmin>,
+}
+
impl MqAdminRegistry {
pub fn new() -> Self {
Self { instances: RwLock::new(HashMap::new()), build_locks: RwLock::new(HashMap::new()) }
@@ -66,9 +72,13 @@ impl MqAdminRegistry {
mqc: MqAdminConfig,
kafka_launch: Option<AgentLaunchSpec>,
) -> Result<Arc<dyn MessageQueueAdmin>, String> {
+ let fingerprint = adapter_fingerprint(&mqc, kafka_launch.as_ref());
+
// Fast path: return the cached adapter.
- if let Some(adapter) = self.instances.read().await.get(connection_id) {
- return Ok(adapter.clone());
+ if let Some(entry) = self.instances.read().await.get(connection_id) {
+ if entry.fingerprint == fingerprint {
+ return Ok(entry.adapter.clone());
+ }
}
// Slow path: acquire a per-connection build lock so only one task
@@ -80,12 +90,17 @@ impl MqAdminRegistry {
let _guard = lock.lock().await;
// Another task may have built it while we were waiting for the lock.
- if let Some(adapter) = self.instances.read().await.get(connection_id) {
- return Ok(adapter.clone());
+ if let Some(entry) = self.instances.read().await.get(connection_id) {
+ if entry.fingerprint == fingerprint {
+ return Ok(entry.adapter.clone());
+ }
}
let adapter = build_adapter(mqc, kafka_launch).await?;
- self.instances.write().await.insert(connection_id.to_string(), adapter.clone());
+ self.instances
+ .write()
+ .await
+ .insert(connection_id.to_string(), CachedMqAdmin { fingerprint, adapter: adapter.clone() });
Ok(adapter)
}
@@ -111,6 +126,13 @@ impl MqAdminRegistry {
}
}
+fn adapter_fingerprint(mqc: &MqAdminConfig, kafka_launch: Option<&AgentLaunchSpec>) -> u64 {
+ let mut hasher = std::collections::hash_map::DefaultHasher::new();
+ format!("{mqc:?}").hash(&mut hasher);
+ format!("{kafka_launch:?}").hash(&mut hasher);
+ hasher.finish()
+}
+
async fn build_adapter(
mqc: MqAdminConfig,
kafka_launch: Option<AgentLaunchSpec>,
diff --git a/crates/dbx-core/src/mq/port.rs b/crates/dbx-core/src/mq/port.rs
index 91ff344e0d..697d19335f 100644
--- a/crates/dbx-core/src/mq/port.rs
+++ b/crates/dbx-core/src/mq/port.rs
@@ -46,7 +46,13 @@ pub trait MessageQueueAdmin: Send + Sync {
async fn skip_messages(&self, topic: &TopicRef, sub: &str, count: SkipCount) -> Result<(), String>;
async fn reset_cursor(&self, topic: &TopicRef, sub: &str, pos: ResetPosition) -> Result<(), String>;
async fn clear_backlog(&self, topic: &TopicRef, sub: &str) -> Result<(), String>;
- async fn peek_messages(&self, topic: &TopicRef, sub: &str, count: u32) -> Result<Vec<PeekedMessage>, String>;
+ async fn peek_messages(
+ &self,
+ topic: &TopicRef,
+ sub: &str,
+ count: u32,
+ options: PeekMessagesOptions,
+ ) -> Result<Vec<PeekedMessage>, String>;
async fn expire_messages(&self, topic: &TopicRef, sub: &str, expire_seconds: i64) -> Result<(), String>;
// ---- Producers / consumers (runtime, read from stats) ----
diff --git a/crates/dbx-core/src/mq/service.rs b/crates/dbx-core/src/mq/service.rs
index ea70398b38..88b262e466 100644
--- a/crates/dbx-core/src/mq/service.rs
+++ b/crates/dbx-core/src/mq/service.rs
@@ -15,14 +15,27 @@ use uuid::Uuid;
const MAX_PEEK_MESSAGES: u32 = 100;
-/// Test connectivity to the message queue admin endpoint. Builds a transient
-/// adapter (not cached) to avoid polluting the registry on failed attempts.
+/// Test connectivity to the message queue admin endpoint. Successful MQ
+/// adapters are cached so agent-backed systems do not cold-start on every
+/// repeated test. Failed builds are not cached by the registry.
pub async fn mq_test_connection_core(state: &AppState, conn_id: &str) -> Result<MqClusterInfo, String> {
let cfg = state.configs.read().await.get(conn_id).cloned().ok_or("Connection not found")?;
let mqc = state.mq_admin_config_for_connection(conn_id, &cfg).await?;
let kafka_launch = resolve_kafka_launch_spec(&mqc, state);
- let adapter = state.mq_registry.build_transient_config(mqc, kafka_launch).await?;
- adapter.test_connection().await
+ let adapter = match state.mq_registry.get_or_build_config(conn_id, mqc, kafka_launch).await {
+ Ok(adapter) => adapter,
+ Err(err) => {
+ state.mq_registry.drop_connection(conn_id).await;
+ return Err(err);
+ }
+ };
+ match adapter.test_connection().await {
+ Ok(info) => Ok(info),
+ Err(err) => {
+ state.mq_registry.drop_connection(conn_id).await;
+ Err(err)
+ }
+ }
}
// ---- Tenants ----
@@ -237,6 +250,7 @@ pub async fn mq_peek_messages_core(
topic: TopicRef,
sub: String,
count: u32,
+ options: Option<PeekMessagesOptions>,
) -> Result<Vec<PeekedMessage>, String> {
if count == 0 {
return Ok(Vec::new());
@@ -245,7 +259,7 @@ pub async fn mq_peek_messages_core(
return Err(format!("Peek message count must be between 1 and {MAX_PEEK_MESSAGES}"));
}
let adapter = get_adapter(state, conn_id).await?;
- adapter.peek_messages(&topic, &sub, count).await
+ adapter.peek_messages(&topic, &sub, count, options.unwrap_or_default()).await
}
pub async fn mq_expire_messages_core(
@@ -666,6 +680,7 @@ mod tests {
},
"sub-a".to_string(),
101,
+ None,
)
.await
.expect_err("peek count above the service limit should fail");
diff --git a/crates/dbx-core/src/mq/types.rs b/crates/dbx-core/src/mq/types.rs
index 00dc51ade0..a504ad94b5 100644
--- a/crates/dbx-core/src/mq/types.rs
+++ b/crates/dbx-core/src/mq/types.rs
@@ -439,6 +439,17 @@ pub struct PeekedMessage {
pub payload_text: Option<String>,
}
+/// Optional hints for reading messages. Pulsar ignores these today; Kafka uses
+/// them to select a partition and starting offset for a non-committing peek.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PeekMessagesOptions {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub partition: Option<i32>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub offset: Option<i64>,
+}
+
// ---------------------------------------------------------------------------
// Policy scope (rate limits / quotas / permissions)
// ---------------------------------------------------------------------------
diff --git a/crates/dbx-core/tests/agent_service.rs b/crates/dbx-core/tests/agent_service.rs
index 38e2c4cda9..0cfde0be58 100644
--- a/crates/dbx-core/tests/agent_service.rs
+++ b/crates/dbx-core/tests/agent_service.rs
@@ -78,7 +78,7 @@ fn agent_list_marks_installed_driver_update_when_registry_version_differs() {
let manager = test_manager("update");
let jar_path = manager.driver_jar_path("h2");
std::fs::create_dir_all(jar_path.parent().unwrap()).unwrap();
- std::fs::write(&jar_path, b"jar").unwrap();
+ write_test_agent_jar(&jar_path);
manager
.save_state(&dbx_core::agent_manager::AgentState {
installed_drivers: [(
@@ -115,7 +115,7 @@ fn agent_list_marks_update_when_installed_managed_jre_version_differs() {
let java_path = manager.jre_java_path(DEFAULT_JRE_KEY);
std::fs::create_dir_all(jar_path.parent().unwrap()).unwrap();
std::fs::create_dir_all(java_path.parent().unwrap()).unwrap();
- std::fs::write(&jar_path, b"jar").unwrap();
+ write_test_agent_jar(&jar_path);
std::fs::write(&java_path, b"java").unwrap();
manager
.save_state(&dbx_core::agent_manager::AgentState {
@@ -146,7 +146,7 @@ fn agent_list_does_not_mark_jre_update_for_system_java_runtime() {
let manager = test_manager("system-java-no-jre-update");
let jar_path = manager.driver_jar_path("dameng");
std::fs::create_dir_all(jar_path.parent().unwrap()).unwrap();
- std::fs::write(&jar_path, b"jar").unwrap();
+ write_test_agent_jar(&jar_path);
manager
.save_state(&dbx_core::agent_manager::AgentState {
java_runtime: JavaRuntimeConfig { mode: JavaRuntimeMode::System, custom_java_path: None },
@@ -222,7 +222,7 @@ fn agent_list_keeps_jre_requirement_for_installed_jar_when_registry_has_native()
let manager = test_manager("installed-jar-registry-native");
let jar_path = manager.driver_jar_path("xugu");
std::fs::create_dir_all(jar_path.parent().unwrap()).unwrap();
- std::fs::write(&jar_path, b"jar").unwrap();
+ write_test_agent_jar(&jar_path);
manager
.save_state(&dbx_core::agent_manager::AgentState {
installed_drivers: [(
@@ -267,7 +267,7 @@ fn agent_list_uses_legacy_default_jre_version_when_checking_updates() {
let java_path = manager.jre_java_path(DEFAULT_JRE_KEY);
std::fs::create_dir_all(jar_path.parent().unwrap()).unwrap();
std::fs::create_dir_all(java_path.parent().unwrap()).unwrap();
- std::fs::write(&jar_path, b"jar").unwrap();
+ write_test_agent_jar(&jar_path);
std::fs::write(&java_path, b"java").unwrap();
manager
.save_state(&dbx_core::agent_manager::AgentState {
@@ -380,17 +380,31 @@ fn local_jar_import_updates_driver_state() {
let manager = test_manager("local-import");
let source = test_path("local-import-source").join("dbx-agent-h2.jar");
std::fs::create_dir_all(source.parent().unwrap()).unwrap();
- std::fs::write(&source, b"jar").unwrap();
+ write_test_agent_jar(&source);
import_agent_jar(&manager, "h2", &source).unwrap();
- assert_eq!(std::fs::read(manager.driver_jar_path("h2")).unwrap(), b"jar");
+ assert_eq!(std::fs::read(manager.driver_jar_path("h2")).unwrap(), std::fs::read(&source).unwrap());
let state = manager.load_state();
let installed = state.installed_drivers.get("h2").unwrap();
assert_eq!(installed.version, "0.1.0-local");
assert_eq!(installed.jre, DEFAULT_JRE_KEY);
}
+#[test]
+fn local_jar_import_rejects_corrupt_jar() {
+ let manager = test_manager("local-import-corrupt");
+ let source = test_path("local-import-corrupt-source").join("dbx-agent-h2.jar");
+ std::fs::create_dir_all(source.parent().unwrap()).unwrap();
+ std::fs::write(&source, b"jar").unwrap();
+
+ let err = import_agent_jar(&manager, "h2", &source).unwrap_err();
+
+ assert!(err.contains("invalid or corrupt"));
+ assert!(!manager.driver_jar_path("h2").exists());
+ assert!(!manager.load_state().installed_drivers.contains_key("h2"));
+}
+
#[tokio::test]
async fn uninstall_driver_removes_artifact_and_state() {
let manager = test_manager("uninstall");
@@ -444,13 +458,32 @@ fn offline_zip_import_emits_progress_and_updates_state() {
.unwrap();
assert_eq!(result.drivers_installed, vec!["h2"]);
- assert_eq!(std::fs::read(manager.driver_jar_path("h2")).unwrap(), b"jar");
+ let installed_jar = std::fs::read(manager.driver_jar_path("h2")).unwrap();
+ assert!(installed_jar.windows(b"Main-Class:".len()).any(|window| window == b"Main-Class:"));
assert_eq!(manager.load_state().installed_drivers.get("h2").unwrap().version, "0.2.0");
let events = events.lock().unwrap();
assert!(events.iter().any(|event| event.step == "driver" && event.db_type.as_deref() == Some("H2")));
}
+#[test]
+fn offline_zip_import_rejects_corrupt_jar() {
+ let manager = test_manager("offline-corrupt-driver");
+ let zip_path = test_path("offline-corrupt-driver-zip").join("agents.zip");
+ std::fs::create_dir_all(zip_path.parent().unwrap()).unwrap();
+ write_offline_driver_zip_with_jar(&zip_path, "h2", "0.2.0", b"jar".to_vec());
+
+ let err = import_agents_from_zip(&manager, &zip_path, |_| {}).unwrap_err();
+
+ assert!(err.contains("invalid or corrupt"));
+ assert!(!manager.driver_jar_path("h2").exists());
+ assert!(!manager.load_state().installed_drivers.contains_key("h2"));
+}
+
fn write_offline_driver_zip(path: &std::path::Path, db_type: &str, version: &str) {
+ write_offline_driver_zip_with_jar(path, db_type, version, test_agent_jar_bytes());
+}
+
+fn write_offline_driver_zip_with_jar(path: &std::path::Path, db_type: &str, version: &str, jar: Vec<u8>) {
let file = std::fs::File::create(path).unwrap();
let mut zip = zip::ZipWriter::new(file);
let options = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
@@ -461,7 +494,7 @@ fn write_offline_driver_zip(path: &std::path::Path, db_type: &str, version: &str
"label": db_type,
"min_app_version": "0.1.0",
"jre": DEFAULT_JRE_KEY,
- "jar": { "url": format!("https://example.com/dbx-agent-{db_type}.jar"), "size": 3 }
+ "jar": { "url": format!("https://example.com/dbx-agent-{db_type}.jar"), "size": jar.len() }
}
}
});
@@ -469,6 +502,20 @@ fn write_offline_driver_zip(path: &std::path::Path, db_type: &str, version: &str
zip.start_file("agent-registry.json", options).unwrap();
std::io::Write::write_all(&mut zip, registry.to_string().as_bytes()).unwrap();
zip.start_file(format!("drivers/dbx-agent-{db_type}.jar"), options).unwrap();
- std::io::Write::write_all(&mut zip, b"jar").unwrap();
+ std::io::Write::write_all(&mut zip, &jar).unwrap();
zip.finish().unwrap();
}
+
+fn write_test_agent_jar(path: &std::path::Path) {
+ std::fs::write(path, test_agent_jar_bytes()).unwrap();
+}
+
+fn test_agent_jar_bytes() -> Vec<u8> {
+ let cursor = std::io::Cursor::new(Vec::new());
+ let mut zip = zip::ZipWriter::new(cursor);
+ let options = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
+ // The production validator rejects corrupt driver artifacts by requiring a real JAR manifest.
+ zip.start_file("META-INF/MANIFEST.MF", options).unwrap();
+ std::io::Write::write_all(&mut zip, b"Manifest-Version: 1.0\nMain-Class: com.dbx.agent.TestAgent\n\n").unwrap();
+ zip.finish().unwrap().into_inner()
+}
diff --git a/crates/dbx-web/src/routes/mq.rs b/crates/dbx-web/src/routes/mq.rs
index 099ba9a78e..9be3c27819 100644
--- a/crates/dbx-web/src/routes/mq.rs
+++ b/crates/dbx-web/src/routes/mq.rs
@@ -173,6 +173,8 @@ pub(crate) struct PeekMessagesReq {
topic: dbx_core::mq::TopicRef,
sub: String,
count: u32,
+ #[serde(default)]
+ options: Option<dbx_core::mq::PeekMessagesOptions>,
}
#[derive(serde::Deserialize)]
@@ -521,10 +523,16 @@ pub async fn peek_messages(
State(state): State<Arc<WebState>>,
Json(req): Json<PeekMessagesReq>,
) -> Result<Json<Vec<dbx_core::mq::PeekedMessage>>, AppError> {
- let result =
- dbx_core::mq::service::mq_peek_messages_core(&state.app, &req.connection_id, req.topic, req.sub, req.count)
- .await
- .map_err(AppError)?;
+ let result = dbx_core::mq::service::mq_peek_messages_core(
+ &state.app,
+ &req.connection_id,
+ req.topic,
+ req.sub,
+ req.count,
+ req.options,
+ )
+ .await
+ .map_err(AppError)?;
Ok(Json(result))
}
diff --git a/src-tauri/src/commands/connection.rs b/src-tauri/src/commands/connection.rs
index c7f93ac2a6..fc75bd1665 100644
--- a/src-tauri/src/commands/connection.rs
+++ b/src-tauri/src/commands/connection.rs
@@ -737,8 +737,17 @@ pub async fn test_connection(state: State<'_, Arc<AppState>>, config: Connection
DatabaseType::MessageQueue => {
let mqc = state.mq_admin_config_for_connection(connection_id, &config).await?;
let kafka_launch = dbx_core::mq::service::resolve_kafka_launch_spec(&mqc, &state);
- let adapter = state.mq_registry.build_transient_config(mqc, kafka_launch).await?;
- adapter.test_connection().await?;
+ let adapter = match state.mq_registry.get_or_build_config(connection_id, mqc, kafka_launch).await {
+ Ok(adapter) => adapter,
+ Err(err) => {
+ state.mq_registry.drop_connection(connection_id).await;
+ return Err(err);
+ }
+ };
+ if let Err(err) = adapter.test_connection().await {
+ state.mq_registry.drop_connection(connection_id).await;
+ return Err(err);
+ }
Ok("Connection successful".to_string())
}
#[cfg(not(feature = "mq-admin"))]
@@ -1022,8 +1031,17 @@ pub async fn connect_db(state: State<'_, Arc<AppState>>, config: ConnectionConfi
DatabaseType::MessageQueue => {
let mqc = state.mq_admin_config_for_connection(&id, &config).await?;
let kafka_launch = dbx_core::mq::service::resolve_kafka_launch_spec(&mqc, &state);
- let adapter = state.mq_registry.build_transient_config(mqc, kafka_launch).await?;
- adapter.test_connection().await?;
+ let adapter = match state.mq_registry.get_or_build_config(&id, mqc, kafka_launch).await {
+ Ok(adapter) => adapter,
+ Err(err) => {
+ state.mq_registry.drop_connection(&id).await;
+ return Err(err);
+ }
+ };
+ if let Err(err) = adapter.test_connection().await {
+ state.mq_registry.drop_connection(&id).await;
+ return Err(err);
+ }
PoolKind::MessageQueue
}
#[cfg(not(feature = "mq-admin"))]
diff --git a/src-tauri/src/commands/mq_cmd.rs b/src-tauri/src/commands/mq_cmd.rs
index 564a9d3c32..9c5ae210ca 100644
--- a/src-tauri/src/commands/mq_cmd.rs
+++ b/src-tauri/src/commands/mq_cmd.rs
@@ -253,8 +253,9 @@ pub async fn mq_peek_messages(
topic: dbx_core::mq::TopicRef,
sub: String,
count: u32,
+ options: Option<dbx_core::mq::PeekMessagesOptions>,
) -> Result<Vec<dbx_core::mq::PeekedMessage>, String> {
- dbx_core::mq::service::mq_peek_messages_core(&state, &connection_id, topic, sub, count).await
+ dbx_core::mq::service::mq_peek_messages_core(&state, &connection_id, topic, sub, count, options).await
}
#[tauri::command]