fix(kafka): improve mq admin compatibility

This commit is contained in:
miracle authored and GitHub committed 2026-07-02 12:58:33 +08:00
1 parent e4e4fa8482
commit 72a7207283
24 files changed
+1050 -170

No files matched your search

@@ -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>
@@ -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"
@@ -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>
@@ -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 ? "刷新中..." : "刷新" }}
@@ -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,
+21 -3
View File
@@ -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 {