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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(transfer): show per-table failure details
zipg1e72d28ed378
diff --git a/apps/desktop/src/components/export/ExportProgressPopover.vue b/apps/desktop/src/components/export/ExportProgressPopover.vueindex 7b5f71fdf9..ab225fa768 100644--- a/apps/desktop/src/components/export/ExportProgressPopover.vue+++ b/apps/desktop/src/components/export/ExportProgressPopover.vue@@ -3,13 +3,14 @@ import { computed, ref } from "vue";import { useI18n } from "vue-i18n";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import { Button } from "@/components/ui/button";-import { Loader2, CheckCircle2, XCircle, AlertCircle, X, FileDown, DatabaseBackup, FileCode2, ArrowRightLeft } from "@lucide/vue";+import { Loader2, CheckCircle2, XCircle, AlertCircle, X, FileDown, DatabaseBackup, FileCode2, ArrowRightLeft, ChevronRight } from "@lucide/vue";import { formatDataTransferDuration, useExportTracker, type ExportTask } from "@/composables/useExportTracker";const { t } = useI18n();const { tasks, activeCount, hasActive, clearFinished, cancelTask, removeTask } = useExportTracker();const open = ref(false);const showAll = ref(false);+const expandedFailureTaskIds = ref<string[]>([]);const MAX_VISIBLE = 5;const reversedTasks = computed(() => {@@ -132,6 +133,18 @@ const statusColor = (status: string) => {function toggleShowAll() {showAll.value = !showAll.value;}++function failureDetailsExpanded(exportId: string) {+ return expandedFailureTaskIds.value.includes(exportId);+}++function toggleFailureDetails(exportId: string) {+ expandedFailureTaskIds.value = failureDetailsExpanded(exportId) ? expandedFailureTaskIds.value.filter((id) => id !== exportId) : [...expandedFailureTaskIds.value, exportId];+}++function failureDetailCount(task: ExportTask) {+ return (task.transferFailures?.length ?? 0) + (task.transferFailuresOmitted ?? 0);+}</script><template>@@ -175,6 +188,20 @@ function toggleShowAll() {<span v-if="task.status === 'Error' && task.errorMessage" class="mt-1 block whitespace-normal break-words text-destructive" :title="task.errorMessage">{{ task.errorMessage }}</span>+ <template v-if="task.kind === 'data-transfer' && failureDetailCount(task) > 0">+ <button class="mt-1.5 flex items-center gap-1 text-xs font-medium text-foreground hover:text-primary" :aria-expanded="failureDetailsExpanded(task.exportId)" @click="toggleFailureDetails(task.exportId)">+ <ChevronRight class="h-3.5 w-3.5 shrink-0 transition-transform" :class="{ 'rotate-90': failureDetailsExpanded(task.exportId) }" />+ {{ failureDetailsExpanded(task.exportId) ? t("exportProgress.hideFailureDetails") : t("exportProgress.showFailureDetails", { count: failureDetailCount(task) }) }}+ </button>+ <div v-if="failureDetailsExpanded(task.exportId)" class="mt-1.5 max-h-44 overflow-y-auto rounded border border-destructive/20 bg-destructive/5">+ <div v-for="failure in task.transferFailures" :key="failure.table" class="border-b border-destructive/15 px-2.5 py-2 last:border-b-0">+ <div class="break-all font-mono font-medium text-foreground">{{ failure.table }}</div>+ <div class="mt-0.5 select-text whitespace-pre-wrap break-words text-destructive">{{ failure.error }}</div>+ <div v-if="failure.truncated" class="mt-0.5 text-muted-foreground">{{ t("exportProgress.failureDetailTruncated") }}</div>+ </div>+ <div v-if="task.transferFailuresOmitted" class="px-2.5 py-2 text-muted-foreground">{{ t("exportProgress.failureDetailsOmitted", { count: task.transferFailuresOmitted }) }}</div>+ </div>+ </template></div></div>diff --git a/apps/desktop/src/components/export/__tests__/ExportProgressPopover.spec.ts b/apps/desktop/src/components/export/__tests__/ExportProgressPopover.spec.tsindex c15b1065af..2851ec4629 100644--- a/apps/desktop/src/components/export/__tests__/ExportProgressPopover.spec.ts+++ b/apps/desktop/src/components/export/__tests__/ExportProgressPopover.spec.ts@@ -91,4 +91,72 @@ describe("ExportProgressPopover data transfer duration", () => {expect(document.body.textContent).toContain("Elapsed: 1m 5s");expect(document.body.textContent?.match(/Elapsed:/g)).toHaveLength(1);});++ it("expands complete per-table transfer failure details", async () => {+ const tracker = useExportTracker();+ const task = tracker.addDataTransferTask("failed-transfer", "source to target", 2);+ tracker.updateDataTransferTask(task.exportId, {+ transferId: task.exportId,+ table: "users",+ tableIndex: 0,+ totalTables: 2,+ rowsTransferred: 0,+ totalRows: null,+ status: "error",+ error: "permission denied for relation users",+ terminal: false,+ });+ tracker.updateDataTransferTask(task.exportId, {+ transferId: task.exportId,+ table: "",+ tableIndex: 2,+ totalTables: 2,+ rowsTransferred: 0,+ totalRows: null,+ status: "error",+ error: "1 table(s) failed: users",+ terminal: true,+ });++ await mountPopover();++ const detailsButton = document.body.querySelector<HTMLButtonElement>('button[aria-expanded="false"]');+ expect(detailsButton?.textContent).toContain("Failure details (1)");+ expect(document.body.textContent).not.toContain("permission denied for relation users");++ detailsButton?.click();+ await nextTick();++ expect(detailsButton?.getAttribute("aria-expanded")).toBe("true");+ expect(document.body.textContent).toContain("users");+ expect(document.body.textContent).toContain("permission denied for relation users");+ });++ it("shows the total failure count and omitted-detail notice when the bounded list is full", async () => {+ const tracker = useExportTracker();+ const task = tracker.addDataTransferTask("bounded-failures", "source to target", 101);+ for (let index = 0; index < 101; index += 1) {+ tracker.updateDataTransferTask(task.exportId, {+ transferId: task.exportId,+ table: `table_${index}`,+ tableIndex: index,+ totalTables: 101,+ rowsTransferred: 0,+ totalRows: null,+ status: "error",+ error: `failure ${index}`,+ terminal: false,+ });+ }++ await mountPopover();++ const detailsButton = document.body.querySelector<HTMLButtonElement>('button[aria-expanded="false"]');+ expect(detailsButton?.textContent).toContain("Failure details (101)");+ detailsButton?.click();+ await nextTick();++ expect(document.body.textContent).toContain("1 additional failure detail(s) not shown");+ expect(document.body.textContent).not.toContain("failure 100");+ });});diff --git a/apps/desktop/src/composables/__tests__/useExportTracker.spec.ts b/apps/desktop/src/composables/__tests__/useExportTracker.spec.tsindex 4c8c9deb64..ce1383ca5b 100644--- a/apps/desktop/src/composables/__tests__/useExportTracker.spec.ts+++ b/apps/desktop/src/composables/__tests__/useExportTracker.spec.ts@@ -10,7 +10,7 @@ vi.mock("@/lib/backend/api", () => ({}));import * as api from "@/lib/backend/api";-import { formatDataTransferDuration, useExportTracker } from "@/composables/useExportTracker";+import { formatDataTransferDuration, MAX_TRANSFER_FAILURE_DETAIL_BYTES, MAX_TRANSFER_FAILURE_DETAILS, MAX_TRANSFER_FAILURE_ERROR_BYTES, useExportTracker } from "@/composables/useExportTracker";let now = 0;@@ -161,6 +161,109 @@ describe("data transfer task duration", () => {});});+describe("data transfer failure details", () => {+ it("preserves per-table failures after the terminal summary and deduplicates table updates", () => {+ const tracker = useExportTracker();+ const task = tracker.addDataTransferTask("failure-details", "users and orders", 2);++ tracker.updateDataTransferTask(task.exportId, { ...transferProgress(task.exportId, "error", false), table: "users", error: "permission denied" });+ tracker.updateDataTransferTask(task.exportId, { ...transferProgress(task.exportId, "error", false), table: "orders", error: "table missing" });+ tracker.updateDataTransferTask(task.exportId, { ...transferProgress(task.exportId, "error", false), table: "users", error: "permission denied by policy" });+ tracker.updateDataTransferTask(task.exportId, { ...transferProgress(task.exportId, "error"), table: "", error: "2 table(s) failed: users, orders" });++ expect(task.errorMessage).toBe("2 table(s) failed: users, orders");+ expect(task.transferFailures).toEqual([+ { table: "users", error: "permission denied by policy" },+ { table: "orders", error: "table missing" },+ ]);+ });++ it("bounds many distinct failures and deduplicates retained and omitted table updates", () => {+ const tracker = useExportTracker();+ const task = tracker.addDataTransferTask("many-failures", "many tables", 250);++ for (let index = 0; index < 250; index += 1) {+ tracker.updateDataTransferTask(task.exportId, {+ ...transferProgress(task.exportId, "error", false),+ table: `table_${index}`,+ error: `failure ${index}`,+ });+ }++ expect(task.transferFailures).toHaveLength(MAX_TRANSFER_FAILURE_DETAILS);+ expect(task.transferFailuresOmitted).toBe(150);++ tracker.updateDataTransferTask(task.exportId, {+ ...transferProgress(task.exportId, "error", false),+ table: "table_150",+ error: "updated omitted failure",+ });+ tracker.updateDataTransferTask(task.exportId, {+ ...transferProgress(task.exportId, "error", false),+ table: "table_0",+ error: "updated retained failure",+ });++ expect(task.transferFailuresOmitted).toBe(150);+ expect(task.transferFailures?.[0]).toEqual({ table: "table_0", error: "updated retained failure" });++ tracker.updateDataTransferTask(task.exportId, {+ ...transferProgress(task.exportId, "done"),+ transferFailuresOmitted: 12,+ });++ expect(task.transferFailuresOmitted).toBe(162);+ });++ it("limits individual and total UTF-8 error detail bytes without splitting characters", () => {+ const tracker = useExportTracker();+ const task = tracker.addDataTransferTask("long-failures", "long errors", 40);+ const longError = "错误🙂".repeat(4_000);++ for (let index = 0; index < 40; index += 1) {+ tracker.updateDataTransferTask(task.exportId, {+ ...transferProgress(task.exportId, "error", false),+ table: `long_table_${index}`,+ error: longError,+ });+ }++ const encoder = new TextEncoder();+ const retainedBytes = task.transferFailures!.reduce((total, failure) => {+ expect(encoder.encode(failure.error).length).toBeLessThanOrEqual(MAX_TRANSFER_FAILURE_ERROR_BYTES);+ expect(failure.error.endsWith("\ud83d")).toBe(false);+ expect(failure.truncated).toBe(true);+ return total + encoder.encode(failure.table).length + encoder.encode(failure.error).length;+ }, 0);++ expect(retainedBytes).toBeLessThanOrEqual(MAX_TRANSFER_FAILURE_DETAIL_BYTES);+ expect(task.transferFailuresOmitted).toBeGreaterThan(0);+ });++ it("saturates omitted failure counting after the deduplication cap", () => {+ const tracker = useExportTracker();+ const task = tracker.addDataTransferTask("omitted-cap", "many tables", 4_197);++ for (let index = 0; index < MAX_TRANSFER_FAILURE_DETAILS + 4_097; index += 1) {+ tracker.updateDataTransferTask(task.exportId, {+ ...transferProgress(task.exportId, "error", false),+ table: `table_${index}`,+ error: `failure ${index}`,+ });+ }++ expect(task.transferFailuresOmitted).toBe(4_096);++ tracker.updateDataTransferTask(task.exportId, {+ ...transferProgress(task.exportId, "error", false),+ table: "table_4_196",+ error: "repeated omitted failure",+ });++ expect(task.transferFailuresOmitted).toBe(4_096);+ });+});+describe("formatDataTransferDuration", () => {it("formats millisecond, second, minute, and hour boundaries", () => {expect(formatDataTransferDuration(Number.NaN)).toBe("0 ms");diff --git a/apps/desktop/src/composables/useExportTracker.ts b/apps/desktop/src/composables/useExportTracker.tsindex 6e48e06491..e45a8d0221 100644--- a/apps/desktop/src/composables/useExportTracker.ts+++ b/apps/desktop/src/composables/useExportTracker.ts@@ -5,6 +5,12 @@ import { isTerminalTransferProgress } from "@/lib/backend/transferProgress";export type BackgroundTaskKind = "table-export" | "database-export" | "sql-file" | "data-transfer";export type BackgroundTaskStatus = "Running" | "Writing" | "Done" | "Error" | "Cancelled";+export interface DataTransferFailure {+ table: string;+ error: string;+ truncated?: boolean;+}+export interface ExportTask {exportId: string;kind: BackgroundTaskKind;@@ -32,11 +38,116 @@ export interface ExportTask {targetDatabase?: string;targetSchema?: string;targetTables?: string[];+ transferFailures?: DataTransferFailure[];+ transferFailuresOmitted?: number;+}++export const MAX_TRANSFER_FAILURE_DETAILS = 100;+export const MAX_TRANSFER_FAILURE_DETAIL_BYTES = 128 * 1024;+export const MAX_TRANSFER_FAILURE_ERROR_BYTES = 8 * 1024;+const MAX_TRACKED_OMITTED_FAILURES = 4096;++interface TransferFailureState {+ indexes: Map<string, number>;+ retainedBytes: number;+ omittedHashes: Set<number>;+ localOmittedCount: number;+ replayOmittedCount: number;}const taskMap = reactive<Map<string, ExportTask>>(new Map());const activeTransferRuns = new Set<string>();const taskCancelHandlers = new Map<string, () => void | Promise<void>>();+const transferFailureStates = new Map<string, TransferFailureState>();+const textEncoder = new TextEncoder();++function utf8ByteLength(value: string): number {+ return textEncoder.encode(value).length;+}++function truncateUtf8(value: string, maxBytes: number): { value: string; bytes: number; truncated: boolean } {+ const encodedBytes = utf8ByteLength(value);+ if (encodedBytes <= maxBytes) return { value, bytes: encodedBytes, truncated: false };++ let result = "";+ let bytes = 0;+ for (const character of value) {+ const characterBytes = utf8ByteLength(character);+ if (bytes + characterBytes > maxBytes) break;+ result += character;+ bytes += characterBytes;+ }+ return { value: result, bytes, truncated: true };+}++function failureTableHash(value: string): number {+ let hash = 0x811c9dc5;+ for (let index = 0; index < value.length; index += 1) {+ hash ^= value.charCodeAt(index);+ hash = Math.imul(hash, 0x01000193);+ }+ return hash >>> 0;+}++function getTransferFailureState(task: ExportTask): TransferFailureState {+ let state = transferFailureStates.get(task.exportId);+ if (state) return state;++ const failures = task.transferFailures ?? [];+ state = {+ indexes: new Map(failures.map((failure, index) => [failure.table, index])),+ retainedBytes: failures.reduce((total, failure) => total + utf8ByteLength(failure.table) + utf8ByteLength(failure.error), 0),+ omittedHashes: new Set(),+ localOmittedCount: task.transferFailuresOmitted ?? 0,+ replayOmittedCount: 0,+ };+ transferFailureStates.set(task.exportId, state);+ return state;+}++function syncTransferFailureOmittedCount(task: ExportTask, state: TransferFailureState) {+ task.transferFailuresOmitted = state.localOmittedCount + state.replayOmittedCount;+}++function recordOmittedTransferFailure(task: ExportTask, state: TransferFailureState, table: string) {+ const hash = failureTableHash(table);+ if (state.omittedHashes.has(hash)) return;+ if (state.omittedHashes.size >= MAX_TRACKED_OMITTED_FAILURES) return;+ state.omittedHashes.add(hash);+ state.localOmittedCount += 1;+ syncTransferFailureOmittedCount(task, state);+}++function recordTransferFailure(task: ExportTask, table: string, error: string) {+ task.transferFailures ??= [];+ const state = getTransferFailureState(task);+ const existingIndex = state.indexes.get(table);+ if (existingIndex !== undefined) {+ const existing = task.transferFailures[existingIndex];+ const previousErrorBytes = utf8ByteLength(existing.error);+ const availableBytes = Math.min(MAX_TRANSFER_FAILURE_ERROR_BYTES, MAX_TRANSFER_FAILURE_DETAIL_BYTES - (state.retainedBytes - previousErrorBytes));+ const nextError = truncateUtf8(error, Math.max(0, availableBytes));+ existing.error = nextError.value;+ if (nextError.truncated) existing.truncated = true;+ else delete existing.truncated;+ state.retainedBytes += nextError.bytes - previousErrorBytes;+ return;+ }++ const tableBytes = utf8ByteLength(table);+ const availableBytes = Math.min(MAX_TRANSFER_FAILURE_ERROR_BYTES, MAX_TRANSFER_FAILURE_DETAIL_BYTES - state.retainedBytes - tableBytes);+ if (task.transferFailures.length >= MAX_TRANSFER_FAILURE_DETAILS || availableBytes <= 0) {+ recordOmittedTransferFailure(task, state, table);+ return;+ }++ const retainedError = truncateUtf8(error, availableBytes);+ const failure: DataTransferFailure = { table, error: retainedError.value };+ if (retainedError.truncated) failure.truncated = true;+ state.indexes.set(table, task.transferFailures.length);+ state.retainedBytes += tableBytes + retainedError.bytes;+ task.transferFailures.push(failure);+}function normalizeExportStatus(status: string): BackgroundTaskStatus {if (status === "Writing" || status === "Done" || status === "Error" || status === "Cancelled") return status;@@ -176,6 +287,7 @@ export function useExportTracker() {}function addDataTransferTask(transferId: string, label: string, totalTables: number): ExportTask {+ transferFailureStates.delete(transferId);const task = reactive<ExportTask>({exportId: transferId,kind: "data-transfer",@@ -190,6 +302,8 @@ export function useExportTracker() {totalTables,currentTable: "",startedAt: Date.now(),+ transferFailures: [],+ transferFailuresOmitted: 0,});taskMap.set(transferId, task);return task;@@ -294,6 +408,14 @@ export function useExportTracker() {function updateDataTransferTask(transferId: string, progress: api.TransferProgress) {const task = taskMap.get(transferId);if (!task) return;+ if (progress.transferFailuresOmitted !== undefined) {+ const state = getTransferFailureState(task);+ state.replayOmittedCount = Math.max(state.replayOmittedCount, progress.transferFailuresOmitted);+ syncTransferFailureOmittedCount(task, state);+ }+ if (progress.status === "error" && !progress.terminal && progress.table && progress.error) {+ recordTransferFailure(task, progress.table, progress.error);+ }const nextStatus = normalizeTransferStatus(progress.status, progress.terminal);const hadError = task.status === "Error";task.status = hadError && nextStatus === "Done" ? "Error" : nextStatus;@@ -311,6 +433,7 @@ export function useExportTracker() {function removeTask(exportId: string) {taskMap.delete(exportId);taskCancelHandlers.delete(exportId);+ transferFailureStates.delete(exportId);}function clearFinished() {@@ -318,6 +441,7 @@ export function useExportTracker() {if (task.status === "Done" || task.status === "Error" || task.status === "Cancelled") {taskMap.delete(id);taskCancelHandlers.delete(id);+ transferFailureStates.delete(id);}}}diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 5a2a4b098f..0f0e881347 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -1381,6 +1381,10 @@ export default {tablesCount: "{current} / {total} tables",statementsCount: "{done} succeeded, {failed} failed",elapsed: "Elapsed: {duration}",+ showFailureDetails: "Failure details ({count})",+ hideFailureDetails: "Hide failure details",+ failureDetailTruncated: "Error details were truncated",+ failureDetailsOmitted: "{count} additional failure detail(s) not shown",},welcome: {title: "Database Workspace",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex bd04e8d0f2..e2474c528a 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -1324,6 +1324,10 @@ export default withEnglishFallback({statementsCount: "{done} exitosas, {failed} fallidas",elapsed: "Transcurrido: {duration}",delete: "Eliminar",+ showFailureDetails: "Detalles de fallos ({count})",+ hideFailureDetails: "Ocultar detalles de fallos",+ failureDetailTruncated: "Los detalles del error se han truncado",+ failureDetailsOmitted: "No se muestran {count} detalles de fallos adicionales",},welcome: {title: "Espacio de trabajo de base de datos",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 40b8c5c50f..35ac5c73e3 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -1322,6 +1322,10 @@ export default withEnglishFallback({tablesCount: "{current} / {total} tabelle",statementsCount: "{done} riuscite, {failed} non riuscite",elapsed: "Tempo trascorso: {duration}",+ showFailureDetails: "Dettagli errori ({count})",+ hideFailureDetails: "Nascondi dettagli errori",+ failureDetailTruncated: "I dettagli dell'errore sono stati troncati",+ failureDetailsOmitted: "Altri {count} dettagli di errore non sono visualizzati",},welcome: {title: "Area di Lavoro Database",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex e319e74e7b..4791d2f1ff 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -1323,6 +1323,10 @@ export default withEnglishFallback({tablesCount: "{current} / {total} テーブル",statementsCount: "{done}成功、{failed}失敗",elapsed: "経過時間: {duration}",+ showFailureDetails: "失敗の詳細({count})",+ hideFailureDetails: "失敗の詳細を閉じる",+ failureDetailTruncated: "エラー詳細は省略されました",+ failureDetailsOmitted: "ほか {count} 件の失敗詳細は表示されていません",},welcome: {title: "データベースワークスペース",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex aec68dbe0e..0834dce606 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -1324,6 +1324,10 @@ export default withEnglishFallback({tablesCount: "{current} / {total} tabelas",statementsCount: "{done} com sucesso, {failed} com falha",elapsed: "Decorrido: {duration}",+ showFailureDetails: "Detalhes das falhas ({count})",+ hideFailureDetails: "Ocultar detalhes das falhas",+ failureDetailTruncated: "Os detalhes do erro foram truncados",+ failureDetailsOmitted: "{count} detalhes adicionais de falha não exibidos",},welcome: {title: "Área de Trabalho do Banco de Dados",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 3a98353a2a..192c86a853 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -1382,6 +1382,10 @@ export default withEnglishFallback({tablesCount: "{current} / {total} 张表",statementsCount: "成功 {done},失败 {failed}",elapsed: "耗时:{duration}",+ showFailureDetails: "失败详情({count})",+ hideFailureDetails: "收起失败详情",+ failureDetailTruncated: "错误详情已截断",+ failureDetailsOmitted: "另有 {count} 条失败详情未显示",},welcome: {title: "数据库工作台",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 61472606d3..9c524ab542 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -1323,6 +1323,10 @@ export default withEnglishFallback({tablesCount: "{current} / {total} 張資料表",statementsCount: "{done} 成功,{failed} 失敗",elapsed: "耗時:{duration}",+ showFailureDetails: "失敗詳情({count})",+ hideFailureDetails: "收合失敗詳情",+ failureDetailTruncated: "錯誤詳情已截斷",+ failureDetailsOmitted: "另有 {count} 條失敗詳情未顯示",},welcome: {title: "資料庫工作檯",diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.tsindex acaa4361ba..5f11282c3f 100644--- a/apps/desktop/src/lib/backend/tauri.ts+++ b/apps/desktop/src/lib/backend/tauri.ts@@ -2501,6 +2501,7 @@ export interface TransferProgress {status: "running" | "tableDone" | "done" | "error" | "cancelled";error: string | null;terminal: boolean;+ transferFailuresOmitted?: number;}export async function startTransfer(request: TransferRequest, onProgress: (progress: TransferProgress) => void): Promise<void> {diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rsindex f2da2791e1..cf2359870f 100644--- a/crates/dbx-web/src/main.rs+++ b/crates/dbx-web/src/main.rs@@ -233,6 +233,7 @@ async fn main() {password_hash: RwLock::new(password_hash),sessions: RwLock::new(HashSet::new()),sse_channels: RwLock::new(HashMap::new()),+ transfer_progress_channels: RwLock::new(HashMap::new()),table_import_channels: RwLock::new(HashMap::new()),sql_file_executions: RwLock::new(HashMap::new()),nacos_imports: RwLock::new(HashMap::new()),diff --git a/crates/dbx-web/src/routes/connection.rs b/crates/dbx-web/src/routes/connection.rsindex 70fb0e07eb..3ddd28aade 100644--- a/crates/dbx-web/src/routes/connection.rs+++ b/crates/dbx-web/src/routes/connection.rs@@ -494,6 +494,7 @@ mod tests {password_hash: RwLock::new(None),sessions: RwLock::new(HashSet::new()),sse_channels: RwLock::new(HashMap::new()),+ transfer_progress_channels: RwLock::new(HashMap::new()),table_import_channels: RwLock::new(HashMap::new()),sql_file_executions: RwLock::new(HashMap::new()),nacos_imports: RwLock::new(HashMap::new()),diff --git a/crates/dbx-web/src/routes/mongo.rs b/crates/dbx-web/src/routes/mongo.rsindex d322ac30c3..25b044dca5 100644--- a/crates/dbx-web/src/routes/mongo.rs+++ b/crates/dbx-web/src/routes/mongo.rs@@ -834,6 +834,7 @@ mod tests {password_hash: RwLock::new(None),sessions: RwLock::new(HashSet::new()),sse_channels: RwLock::new(HashMap::new()),+ transfer_progress_channels: RwLock::new(HashMap::new()),table_import_channels: RwLock::new(HashMap::new()),sql_file_executions: RwLock::new(HashMap::new()),nacos_imports: RwLock::new(HashMap::new()),diff --git a/crates/dbx-web/src/routes/mq.rs b/crates/dbx-web/src/routes/mq.rsindex 9ea744c7b7..6a65c85a89 100644--- a/crates/dbx-web/src/routes/mq.rs+++ b/crates/dbx-web/src/routes/mq.rs@@ -1540,6 +1540,7 @@ mod tests {password_hash: RwLock::new(None),sessions: RwLock::new(HashSet::new()),sse_channels: RwLock::new(HashMap::new()),+ transfer_progress_channels: RwLock::new(HashMap::new()),table_import_channels: RwLock::new(HashMap::new()),sql_file_executions: RwLock::new(HashMap::new()),nacos_imports: RwLock::new(HashMap::new()),diff --git a/crates/dbx-web/src/routes/transfer.rs b/crates/dbx-web/src/routes/transfer.rsindex 2900bd65aa..5195fd0c35 100644--- a/crates/dbx-web/src/routes/transfer.rs+++ b/crates/dbx-web/src/routes/transfer.rs@@ -6,10 +6,55 @@ use axum::Json;use dbx_core::transfer::{self, TransferRequest, TransferStatus};use futures::stream::Stream;use serde::Deserialize;+use tokio::time::{sleep, Duration};use crate::error::AppError;+use crate::sse::{TransferProgressChannel, TransferReplayEventKind};use crate::state::WebState;+const COMPLETED_TRANSFER_CHANNEL_TTL: Duration = Duration::from_secs(60);++fn send_transfer_progress(channel: &TransferProgressChannel, progress: &transfer::TransferProgress) {+ if let Ok(json) = serde_json::to_string(progress) {+ let kind = if progress.terminal {+ TransferReplayEventKind::Terminal+ } else if matches!(&progress.status, TransferStatus::Error) {+ TransferReplayEventKind::Failure+ } else {+ TransferReplayEventKind::Progress+ };+ channel.send(json, kind);+ }+}++fn terminal_transfer_error(req: &TransferRequest, error: impl ToString) -> transfer::TransferProgress {+ transfer::TransferProgress {+ transfer_id: req.transfer_id.clone(),+ table: String::new(),+ table_index: 0,+ total_tables: req.tables.len(),+ rows_transferred: 0,+ total_rows: None,+ status: TransferStatus::Error,+ error: Some(error.to_string()),+ terminal: true,+ }+}++async fn finish_transfer_channel(state: &Arc<WebState>, transfer_id: &str, channel: &Arc<TransferProgressChannel>) {+ transfer::clear_cancelled(transfer_id).await;+ let state = state.clone();+ let transfer_id = transfer_id.to_string();+ let channel = channel.clone();+ tokio::spawn(async move {+ sleep(COMPLETED_TRANSFER_CHANNEL_TTL).await;+ let mut channels = state.transfer_progress_channels.write().await;+ if channels.get(&transfer_id).is_some_and(|current| Arc::ptr_eq(current, &channel)) {+ channels.remove(&transfer_id);+ }+ });+}+#[derive(Deserialize)]#[serde(rename_all = "camelCase")]pub struct StartTransferRequest {@@ -45,9 +90,10 @@ pub async fn start_transfer(let transfer_id = req.transfer_id.clone();- // Create a broadcast channel for progress- let (tx, _) = tokio::sync::broadcast::channel::<String>(256);- state.sse_channels.write().await.insert(transfer_id.clone(), tx.clone());+ // Keep bounded replay state so a web EventSource opened after this POST+ // still receives early table failures and the terminal result.+ let progress_channel = Arc::new(TransferProgressChannel::new());+ state.transfer_progress_channels.write().await.insert(transfer_id.clone(), progress_channel.clone());let app = state.app.clone();let state_clone = state.clone();@@ -56,14 +102,16 @@ pub async fn start_transfer(let source_db_type = match transfer::get_db_type(&app, &req.source_connection_id).await {Ok(t) => t,Err(e) => {- let _ = tx.send(serde_json::json!({"error": e}).to_string());+ send_transfer_progress(&progress_channel, &terminal_transfer_error(&req, e));+ finish_transfer_channel(&state_clone, &req.transfer_id, &progress_channel).await;return;}};let target_db_type = match transfer::get_db_type(&app, &req.target_connection_id).await {Ok(t) => t,Err(e) => {- let _ = tx.send(serde_json::json!({"error": e}).to_string());+ send_transfer_progress(&progress_channel, &terminal_transfer_error(&req, e));+ finish_transfer_channel(&state_clone, &req.transfer_id, &progress_channel).await;return;}};@@ -72,7 +120,8 @@ pub async fn start_transfer({Ok(k) => k,Err(e) => {- let _ = tx.send(serde_json::json!({"error": e}).to_string());+ send_transfer_progress(&progress_channel, &terminal_transfer_error(&req, e));+ finish_transfer_channel(&state_clone, &req.transfer_id, &progress_channel).await;return;}};@@ -80,7 +129,8 @@ pub async fn start_transfer({Ok(k) => k,Err(e) => {- let _ = tx.send(serde_json::json!({"error": e}).to_string());+ send_transfer_progress(&progress_channel, &terminal_transfer_error(&req, e));+ finish_transfer_channel(&state_clone, &req.transfer_id, &progress_channel).await;return;}};@@ -105,16 +155,14 @@ pub async fn start_transfer(if matches!(source_db_type, dbx_core::models::connection::DatabaseType::Postgres)&& matches!(target_db_type, dbx_core::models::connection::DatabaseType::Postgres){- let tx_clone = tx.clone();+ let progress_channel_clone = progress_channel.clone();match transfer::transfer_postgres_schema_dependencies(&app,&req,&source_pool_key,&target_pool_key,|progress| {- if let Ok(json) = serde_json::to_string(&progress) {- let _ = tx_clone.send(json);- }+ send_transfer_progress(&progress_channel_clone, &progress);},).await@@ -132,11 +180,8 @@ pub async fn start_transfer(error: None,terminal: true,};- if let Ok(json) = serde_json::to_string(&progress) {- let _ = tx.send(json);- }- transfer::clear_cancelled(&req.transfer_id).await;- state_clone.remove_sse_channel(&req.transfer_id).await;+ send_transfer_progress(&progress_channel, &progress);+ finish_transfer_channel(&state_clone, &req.transfer_id, &progress_channel).await;return;}Err(e) => {@@ -151,11 +196,8 @@ pub async fn start_transfer(error: Some(e),terminal: true,};- if let Ok(json) = serde_json::to_string(&progress) {- let _ = tx.send(json);- }- transfer::clear_cancelled(&req.transfer_id).await;- state_clone.remove_sse_channel(&req.transfer_id).await;+ send_transfer_progress(&progress_channel, &progress);+ finish_transfer_channel(&state_clone, &req.transfer_id, &progress_channel).await;return;}}@@ -174,15 +216,12 @@ pub async fn start_transfer(error: None,terminal: true,};- if let Ok(json) = serde_json::to_string(&progress) {- let _ = tx.send(json);- }- transfer::clear_cancelled(&req.transfer_id).await;- state_clone.remove_sse_channel(&req.transfer_id).await;+ send_transfer_progress(&progress_channel, &progress);+ finish_transfer_channel(&state_clone, &req.transfer_id, &progress_channel).await;return;}- let tx_clone = tx.clone();+ let progress_channel_clone = progress_channel.clone();let mut last_rows_transferred = 0_u64;let mut last_total_rows = None;let result = transfer::transfer_table(@@ -197,9 +236,7 @@ pub async fn start_transfer(|progress| {last_rows_transferred = progress.rows_transferred;last_total_rows = progress.total_rows;- if let Ok(json) = serde_json::to_string(&progress) {- let _ = tx_clone.send(json);- }+ send_transfer_progress(&progress_channel_clone, &progress);},).await;@@ -217,9 +254,7 @@ pub async fn start_transfer(error: None,terminal: false,};- if let Ok(json) = serde_json::to_string(&progress) {- let _ = tx.send(json);- }+ send_transfer_progress(&progress_channel, &progress);}Err(e) => {if e == "Cancelled" {@@ -234,11 +269,8 @@ pub async fn start_transfer(error: None,terminal: true,};- if let Ok(json) = serde_json::to_string(&progress) {- let _ = tx.send(json);- }- transfer::clear_cancelled(&req.transfer_id).await;- state_clone.remove_sse_channel(&req.transfer_id).await;+ send_transfer_progress(&progress_channel, &progress);+ finish_transfer_channel(&state_clone, &req.transfer_id, &progress_channel).await;return;}failed_tables.push(table.clone());@@ -253,9 +285,7 @@ pub async fn start_transfer(error: Some(e),terminal: false,};- if let Ok(json) = serde_json::to_string(&progress) {- let _ = tx.send(json);- }+ send_transfer_progress(&progress_channel, &progress);}}}@@ -263,16 +293,14 @@ pub async fn start_transfer(if matches!(source_db_type, dbx_core::models::connection::DatabaseType::Postgres)&& matches!(target_db_type, dbx_core::models::connection::DatabaseType::Postgres){- let tx_clone = tx.clone();+ let progress_channel_clone = progress_channel.clone();match transfer::transfer_postgres_schema_objects(&app,&req,&source_pool_key,&target_pool_key,|progress| {- if let Ok(json) = serde_json::to_string(&progress) {- let _ = tx_clone.send(json);- }+ send_transfer_progress(&progress_channel_clone, &progress);},).await@@ -290,11 +318,8 @@ pub async fn start_transfer(error: None,terminal: true,};- if let Ok(json) = serde_json::to_string(&progress) {- let _ = tx.send(json);- }- transfer::clear_cancelled(&req.transfer_id).await;- state_clone.remove_sse_channel(&req.transfer_id).await;+ send_transfer_progress(&progress_channel, &progress);+ finish_transfer_channel(&state_clone, &req.transfer_id, &progress_channel).await;return;}Err(e) => {@@ -310,9 +335,7 @@ pub async fn start_transfer(error: Some(e),terminal: false,};- if let Ok(json) = serde_json::to_string(&progress) {- let _ = tx.send(json);- }+ send_transfer_progress(&progress_channel, &progress);}}}@@ -337,12 +360,8 @@ pub async fn start_transfer(},terminal: true,};- if let Ok(json) = serde_json::to_string(&done) {- let _ = tx.send(json);- }-- transfer::clear_cancelled(&req.transfer_id).await;- state_clone.remove_sse_channel(&req.transfer_id).await;+ send_transfer_progress(&progress_channel, &done);+ finish_transfer_channel(&state_clone, &req.transfer_id, &progress_channel).await;});Ok(Json(serde_json::json!({ "transferId": transfer_id })))@@ -383,11 +402,11 @@ pub async fn transfer_progress(State(state): State<Arc<WebState>>,Path(transfer_id): Path<String>,) -> Result<Sse<impl Stream<Item = Result<Event, std::convert::Infallible>>>, AppError> {- let channels = state.sse_channels.read().await;- let tx = channels.get(&transfer_id).ok_or_else(|| AppError::from("Transfer not found".to_string()))?;- let rx = tx.subscribe();+ let channels = state.transfer_progress_channels.read().await;+ let channel =+ channels.get(&transfer_id).cloned().ok_or_else(|| AppError::from("Transfer not found".to_string()))?;drop(channels);- Ok(crate::sse::sse_from_channel(rx))+ Ok(crate::sse::sse_from_transfer_channel(channel))}pub async fn cancel_transfer(diff --git a/crates/dbx-web/src/sse.rs b/crates/dbx-web/src/sse.rsindex c41c659c66..d265153f0d 100644--- a/crates/dbx-web/src/sse.rs+++ b/crates/dbx-web/src/sse.rs@@ -1,8 +1,100 @@use axum::response::sse::{Event, KeepAlive, Sse};use futures::stream::Stream;+use serde_json::Value;+use std::collections::VecDeque;+use std::sync::{Arc, Mutex};use tokio::sync::broadcast::{self, error::RecvError};use tokio::sync::watch;+const TRANSFER_REPLAY_MAX_FAILURES: usize = 256;+const TRANSFER_REPLAY_MAX_BYTES: usize = 2 * 1024 * 1024;++#[derive(Clone, Copy)]+pub enum TransferReplayEventKind {+ Progress,+ Failure,+ Terminal,+}++#[derive(Default)]+struct TransferReplayHistory {+ failures: VecDeque<String>,+ failure_bytes: usize,+ latest: Option<String>,+ omitted_failures: usize,+}++pub struct TransferProgressChannel {+ tx: broadcast::Sender<String>,+ history: Mutex<TransferReplayHistory>,+}++impl TransferProgressChannel {+ pub fn new() -> Self {+ let (tx, _) = broadcast::channel(256);+ Self { tx, history: Mutex::new(TransferReplayHistory::default()) }+ }++ pub fn send(&self, mut data: String, kind: TransferReplayEventKind) {+ let mut history = self.history.lock().unwrap_or_else(|poisoned| poisoned.into_inner());+ match kind {+ TransferReplayEventKind::Progress => {+ history.latest = Some(data.clone());+ }+ TransferReplayEventKind::Terminal => {+ data = attach_omitted_failure_count(data, history.omitted_failures);+ history.latest = Some(data.clone());+ }+ TransferReplayEventKind::Failure => {+ // The failure itself is the current progress until a newer event arrives.+ history.latest = None;+ while !history.failures.is_empty()+ && (history.failures.len() >= TRANSFER_REPLAY_MAX_FAILURES+ || history.failure_bytes.saturating_add(data.len()) > TRANSFER_REPLAY_MAX_BYTES)+ {+ if let Some(removed) = history.failures.pop_front() {+ history.failure_bytes = history.failure_bytes.saturating_sub(removed.len());+ history.omitted_failures = history.omitted_failures.saturating_add(1);+ }+ }+ if data.len() <= TRANSFER_REPLAY_MAX_BYTES {+ history.failure_bytes += data.len();+ history.failures.push_back(data.clone());+ } else {+ history.omitted_failures = history.omitted_failures.saturating_add(1);+ }+ }+ }+ let _ = self.tx.send(data);+ }++ fn subscribe(&self) -> (Vec<String>, broadcast::Receiver<String>) {+ // Subscribe while holding the history lock so an event is either in the+ // replay snapshot or in the live receiver, with no gap between them.+ let history = self.history.lock().unwrap_or_else(|poisoned| poisoned.into_inner());+ let rx = self.tx.subscribe();+ let mut replay = history.failures.iter().cloned().collect::<Vec<_>>();+ if let Some(latest) = &history.latest {+ replay.push(latest.clone());+ }+ (replay, rx)+ }+}++fn attach_omitted_failure_count(data: String, omitted_failures: usize) -> String {+ if omitted_failures == 0 {+ return data;+ }+ let Ok(mut value) = serde_json::from_str::<Value>(&data) else {+ return data;+ };+ let Some(object) = value.as_object_mut() else {+ return data;+ };+ object.insert("transferFailuresOmitted".to_string(), Value::from(omitted_failures as u64));+ serde_json::to_string(&value).unwrap_or(data)+}+pub fn sse_from_channel(rx: broadcast::Receiver<String>,) -> Sse<impl Stream<Item = Result<Event, std::convert::Infallible>>> {@@ -51,3 +143,62 @@ pub fn sse_from_watch(};Sse::new(stream).keep_alive(KeepAlive::default())}++pub fn sse_from_transfer_channel(+ channel: Arc<TransferProgressChannel>,+) -> Sse<impl Stream<Item = Result<Event, std::convert::Infallible>>> {+ let (replay, mut rx) = channel.subscribe();+ let stream = async_stream::stream! {+ for data in replay {+ yield Ok(Event::default().data(data));+ }+ loop {+ match rx.recv().await {+ Ok(data) => yield Ok(Event::default().data(data)),+ Err(RecvError::Lagged(_)) => break,+ Err(RecvError::Closed) => break,+ }+ }+ };+ Sse::new(stream).keep_alive(KeepAlive::default())+}++#[cfg(test)]+mod tests {+ use super::*;+ use axum::body::to_bytes;+ use axum::response::IntoResponse;++ #[tokio::test]+ async fn delayed_transfer_subscription_replays_failure_and_terminal_events() {+ let channel = Arc::new(TransferProgressChannel::new());+ channel.send("early failure".to_string(), TransferReplayEventKind::Failure);+ channel.send("terminal result".to_string(), TransferReplayEventKind::Terminal);++ let response = sse_from_transfer_channel(channel).into_response();+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();+ let body = String::from_utf8(body.to_vec()).unwrap();++ assert!(body.contains("data: early failure"));+ assert!(body.contains("data: terminal result"));+ assert!(body.find("early failure") < body.find("terminal result"));+ }++ #[tokio::test]+ async fn delayed_transfer_subscription_reports_evicted_failure_count() {+ let channel = Arc::new(TransferProgressChannel::new());+ for index in 0..=TRANSFER_REPLAY_MAX_FAILURES {+ channel.send(format!("failure-{index}"), TransferReplayEventKind::Failure);+ }+ channel.send(+ r#"{"transferId":"transfer-1","status":"done","terminal":true}"#.to_string(),+ TransferReplayEventKind::Terminal,+ );++ let response = sse_from_transfer_channel(channel).into_response();+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();+ let body = String::from_utf8(body.to_vec()).unwrap();++ assert!(body.contains(r#""transferFailuresOmitted":1"#));+ }+}diff --git a/crates/dbx-web/src/state.rs b/crates/dbx-web/src/state.rsindex 9a428f5096..a8d8ed956d 100644--- a/crates/dbx-web/src/state.rs+++ b/crates/dbx-web/src/state.rs@@ -5,6 +5,8 @@ use std::sync::Arc;use tokio::sync::{broadcast, watch, Mutex, RwLock};use tokio_util::sync::CancellationToken;+use crate::sse::TransferProgressChannel;+pub struct LoginRateLimit {pub fail_count: u32,pub locked_until: Option<std::time::Instant>,@@ -26,6 +28,7 @@ pub struct WebState {pub password_hash: RwLock<Option<String>>,pub sessions: RwLock<HashSet<String>>,pub sse_channels: RwLock<HashMap<String, broadcast::Sender<String>>>,+ pub transfer_progress_channels: RwLock<HashMap<String, Arc<TransferProgressChannel>>>,pub table_import_channels: RwLock<HashMap<String, watch::Sender<String>>>,pub sql_file_executions: RwLock<HashMap<String, CancellationToken>>,pub nacos_imports: RwLock<HashMap<String, NacosImportContext>>,diff --git a/packages/app-tests/useExportTracker.test.ts b/packages/app-tests/useExportTracker.test.tsindex f9a0d69090..4391c0746d 100644--- a/packages/app-tests/useExportTracker.test.ts+++ b/packages/app-tests/useExportTracker.test.ts@@ -209,6 +209,35 @@ test("marks data transfer failed only on terminal error summary", () => {assert.equal(task.status, "Error");assert.equal(task.errorMessage, "1 table(s) failed: users");assert.equal(task.tableIndex, 2);+ assert.deepEqual(task.transferFailures, [{ table: "users", error: "permission denied" }]);+});++test("keeps distinct table failures and updates duplicate table errors", () => {+ const tracker = useExportTracker();+ const task = tracker.addDataTransferTask("transfer-failure-details", "source → target", 2);++ for (const [table, error] of [+ ["users", "permission denied"],+ ["orders", "target table missing"],+ ["users", "permission denied by policy"],+ ] as const) {+ tracker.updateDataTransferTask(task.exportId, {+ transferId: task.exportId,+ table,+ tableIndex: 0,+ totalTables: 2,+ rowsTransferred: 0,+ totalRows: null,+ status: "error",+ error,+ terminal: false,+ });+ }++ assert.deepEqual(task.transferFailures, [+ { table: "users", error: "permission denied by policy" },+ { table: "orders", error: "target table missing" },+ ]);});test("keeps data transfer row counts when terminal summary does not include rows", () => {