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(updater): improve download cancellation and stall handling

rihkddd27d1ad53ce13
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vue
index d3842874ca..d6c8e220ba 100644
--- a/apps/desktop/src/App.vue
+++ b/apps/desktop/src/App.vue
@@ -152,6 +152,7 @@ const {
checkUpdates,
openLatestRelease,
downloadAndInstallUpdate,
+ cancelDownload,
installDownloadedUpdate,
restartApp,
} = useAppUpdater({
@@ -2518,6 +2519,7 @@ onUnmounted(() => {
:active-task-count="activeUpdateTaskCount"
@open-latest-release="openLatestRelease"
@download-and-install="downloadAndInstallUpdate"
+ @cancel-download="cancelDownload"
@install-downloaded="installDownloadedUpdate"
@restart="restartApp"
/>
diff --git a/apps/desktop/src/components/layout/UpdateDialog.spec.ts b/apps/desktop/src/components/layout/UpdateDialog.spec.ts
index 00b7c70835..f8a0d8c5c9 100644
--- a/apps/desktop/src/components/layout/UpdateDialog.spec.ts
+++ b/apps/desktop/src/components/layout/UpdateDialog.spec.ts
@@ -40,6 +40,7 @@ async function mountDialog(activeTaskCount: number, initialState: Partial<Dialog
...initialState,
});
const downloadAndInstall = vi.fn();
+ const cancelDownload = vi.fn();
const container = document.createElement("div");
document.body.append(container);
const app = createApp(
@@ -82,6 +83,7 @@ async function mountDialog(activeTaskCount: number, initialState: Partial<Dialog
updateReady: state.updateReady,
activeTaskCount,
"onDownload-and-install": downloadAndInstall,
+ "onCancel-download": cancelDownload,
"onInstall-downloaded": handleInstallDownloaded,
});
},
@@ -92,7 +94,7 @@ async function mountDialog(activeTaskCount: number, initialState: Partial<Dialog
app.mount(container);
await flushDialog();
- return { state, downloadAndInstall, installDownloaded };
+ return { state, downloadAndInstall, cancelDownload, installDownloaded };
}
function buttonWithText(text: string): HTMLButtonElement | undefined {
@@ -171,6 +173,17 @@ describe("UpdateDialog active task guard", () => {
});
describe("UpdateDialog close protection", () => {
+ it("cancels the background download when the close button is clicked", async () => {
+ const { state, cancelDownload } = await mountDialog(0, { isDownloadingUpdate: true, downloadProgress: 42 });
+
+ const closeButton = document.body.querySelector<HTMLButtonElement>('[data-slot="dialog-close"]');
+ closeButton?.click();
+ await flushDialog();
+
+ expect(cancelDownload).toHaveBeenCalledOnce();
+ expect(state.open).toBe(false);
+ });
+
it("allows closing while a downloaded update is idle", async () => {
const { state } = await mountDialog(0, { updateDownloaded: true, downloadProgress: 100 });
@@ -232,7 +245,7 @@ describe("UpdateDialog close protection", () => {
expect(downloadAndInstall).not.toHaveBeenCalled();
});
- it("keeps the successful install flow protected", async () => {
+ it("allows dismissing after a successful install while restart remains available", async () => {
const installDownloaded = vi.fn(async () => {});
const { state, downloadAndInstall } = await mountDialog(0, { updateDownloaded: true }, installDownloaded);
@@ -242,9 +255,9 @@ describe("UpdateDialog close protection", () => {
expect(state.updateDownloaded).toBe(false);
expect(state.updateReady).toBe(true);
expect(buttonWithText("Restart")).toBeDefined();
- expect(buttonWithText("Cancel")).toBeUndefined();
+ expect(buttonWithText("Cancel")).toBeDefined();
await pressEscape();
- expect(state.open).toBe(true);
+ expect(state.open).toBe(false);
expect(installDownloaded).toHaveBeenCalledOnce();
expect(downloadAndInstall).not.toHaveBeenCalled();
});
diff --git a/apps/desktop/src/components/layout/UpdateDialog.vue b/apps/desktop/src/components/layout/UpdateDialog.vue
index df17264530..3c547cb9ab 100644
--- a/apps/desktop/src/components/layout/UpdateDialog.vue
+++ b/apps/desktop/src/components/layout/UpdateDialog.vue
@@ -24,6 +24,7 @@ const props = defineProps<{
const emit = defineEmits<{
"open-latest-release": [];
"download-and-install": [];
+ "cancel-download": [];
"install-downloaded": [];
restart: [];
}>();
@@ -32,8 +33,24 @@ const { t } = useI18n();
const isDesktop = isTauriRuntime();
const renderedNotes = ref("");
-// Keep a downloaded package retryable after install errors; only active transitions must trap the dialog.
-const isCloseBlocked = computed(() => props.isDownloadingUpdate || props.isInstallingUpdate || props.updateReady);
+// Only active file replacement (installation) must trap the dialog.
+const isCloseBlocked = computed(() => props.isInstallingUpdate);
+
+function handleCancel() {
+ handleOpenChange(false);
+}
+
+function handleOpenChange(nextOpen: boolean) {
+ if (nextOpen) {
+ open.value = true;
+ return;
+ }
+ if (isCloseBlocked.value) return;
+ if (props.isDownloadingUpdate) {
+ emit("cancel-download");
+ }
+ open.value = false;
+}
function handleReleaseNotesClick(event: MouseEvent) {
const target = event.target as HTMLElement;
@@ -65,7 +82,7 @@ watch(
</script>
<template>
- <Dialog v-model:open="open">
+ <Dialog :open="open" @update:open="handleOpenChange">
<DialogContent
class="sm:max-w-[520px]"
:show-close-button="!isCloseBlocked"
@@ -118,7 +135,7 @@ watch(
</div>
</div>
<DialogFooter>
- <Button v-if="!isCloseBlocked" variant="outline" @click="open = false">{{ t("dangerDialog.cancel") }}</Button>
+ <Button v-if="!isCloseBlocked" variant="outline" @click="handleCancel">{{ t("dangerDialog.cancel") }}</Button>
<template v-if="updateInfo?.update_available">
<Button variant="outline" @click="emit('open-latest-release')">{{ t("updates.openRelease") }}</Button>
<template v-if="canDownloadAndInstallUpdate(updateInfo, isDesktop)">
diff --git a/apps/desktop/src/composables/__tests__/useAppUpdater.spec.ts b/apps/desktop/src/composables/__tests__/useAppUpdater.spec.ts
new file mode 100644
index 0000000000..6020e1203c
--- /dev/null
+++ b/apps/desktop/src/composables/__tests__/useAppUpdater.spec.ts
@@ -0,0 +1,118 @@
+// @vitest-environment happy-dom
+
+import { createApp, defineComponent, h, type App } from "vue";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import i18n from "@/i18n";
+import { useAppUpdater } from "@/composables/useAppUpdater";
+
+const apiMock = vi.hoisted(() => ({
+ cancelUpdateDownload: vi.fn<() => Promise<void>>(),
+ downloadUpdate: vi.fn<() => Promise<void>>(),
+ installDownloadedUpdate: vi.fn<() => Promise<void>>(),
+}));
+const listenMock = vi.hoisted(() => vi.fn());
+
+vi.mock("@/lib/backend/api", () => apiMock);
+vi.mock("@/lib/backend/tauriRuntime", () => ({
+ isTauriRuntime: () => true,
+}));
+vi.mock("@/composables/useToast", () => ({
+ useToast: () => ({ toast: vi.fn() }),
+}));
+vi.mock("@/stores/settingsStore", () => ({
+ useSettingsStore: () => ({ editorSettings: { updateDownloadSource: "official" } }),
+}));
+vi.mock("@tauri-apps/api/event", () => ({
+ listen: listenMock,
+}));
+
+interface Deferred<T> {
+ promise: Promise<T>;
+ resolve: (value: T | PromiseLike<T>) => void;
+ reject: (reason?: unknown) => void;
+}
+
+function deferred<T>(): Deferred<T> {
+ let resolve!: Deferred<T>["resolve"];
+ let reject!: Deferred<T>["reject"];
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ return { promise, resolve, reject };
+}
+
+let app: App | undefined;
+let container: HTMLDivElement | undefined;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ listenMock.mockResolvedValue(vi.fn());
+ apiMock.installDownloadedUpdate.mockResolvedValue();
+});
+
+afterEach(() => {
+ app?.unmount();
+ container?.remove();
+ app = undefined;
+ container = undefined;
+});
+
+describe("useAppUpdater download attempts", () => {
+ it("waits for cancellation and ignores stale completion from the previous attempt", async () => {
+ const firstDownload = deferred<void>();
+ const secondDownload = deferred<void>();
+ const cancellation = deferred<void>();
+ apiMock.downloadUpdate.mockImplementationOnce(() => firstDownload.promise).mockImplementationOnce(() => secondDownload.promise);
+ apiMock.cancelUpdateDownload.mockReturnValueOnce(cancellation.promise);
+
+ let updater!: ReturnType<typeof useAppUpdater>;
+ container = document.createElement("div");
+ document.body.append(container);
+ app = createApp(
+ defineComponent({
+ setup() {
+ updater = useAppUpdater();
+ return () => h("div");
+ },
+ }),
+ );
+ app.use(i18n);
+ app.mount(container);
+ updater.updateInfo.value = {
+ current_version: "0.5.69",
+ latest_version: "0.5.70",
+ update_available: true,
+ release_name: "DBX v0.5.70",
+ release_url: "https://github.com/t8y2/dbx/releases/tag/v0.5.70",
+ release_notes: "",
+ };
+
+ const firstAttempt = updater.downloadAndInstallUpdate();
+ await vi.waitFor(() => expect(apiMock.downloadUpdate).toHaveBeenCalledTimes(1));
+
+ const cancelAttempt = updater.cancelDownload();
+ expect(updater.isDownloadingUpdate.value).toBe(false);
+
+ const retryAttempt = updater.downloadAndInstallUpdate();
+ await Promise.resolve();
+ expect(apiMock.downloadUpdate).toHaveBeenCalledTimes(1);
+ expect(updater.isDownloadingUpdate.value).toBe(true);
+
+ cancellation.resolve();
+ await cancelAttempt;
+ await vi.waitFor(() => expect(apiMock.downloadUpdate).toHaveBeenCalledTimes(2));
+
+ firstDownload.reject(new Error("Download canceled by user."));
+ await firstAttempt;
+ expect(updater.isDownloadingUpdate.value).toBe(true);
+ expect(updater.downloadProgress.value).toBe(0);
+
+ secondDownload.resolve();
+ await retryAttempt;
+
+ expect(apiMock.installDownloadedUpdate).toHaveBeenCalledOnce();
+ expect(updater.isDownloadingUpdate.value).toBe(false);
+ expect(updater.updateReady.value).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/composables/useAppUpdater.ts b/apps/desktop/src/composables/useAppUpdater.ts
index 113e58d9b0..eca4449369 100644
--- a/apps/desktop/src/composables/useAppUpdater.ts
+++ b/apps/desktop/src/composables/useAppUpdater.ts
@@ -68,6 +68,8 @@ export function useAppUpdater(options: UseAppUpdaterOptions = {}) {
const activeTaskCount = computed(() => Math.max(0, Math.trunc(options.getActiveTaskCount?.() ?? 0)));
const hasUpdateAvailable = computed(() => updateInfo.value?.update_available === true);
const latestReleaseUrl = "https://github.com/t8y2/dbx/releases/latest";
+ let activeDownloadAttempt = 0;
+ let pendingCancellation: Promise<void> | undefined;
function openUrl(url: string) {
if (isTauriRuntime()) {
@@ -104,10 +106,16 @@ export function useAppUpdater(options: UseAppUpdaterOptions = {}) {
function formatUpdateError(message: string): string {
const lower = message.toLowerCase();
+ if (lower.includes("canceled") || lower.includes("cancelled")) {
+ return t("updates.downloadCanceled");
+ }
if (lower.includes("403") || lower.includes("rate limit")) {
return t("updates.rateLimited");
}
- return t("updates.failed", { error: message });
+ if (lower.includes("stalled") || lower.includes("timeout") || lower.includes("all available mirrors") || lower.includes("error sending request") || lower.includes("failed to download")) {
+ return t("updates.networkOrMirrorFailed");
+ }
+ return t("updates.downloadFailed", { error: message });
}
function openLatestRelease() {
@@ -128,30 +136,30 @@ export function useAppUpdater(options: UseAppUpdaterOptions = {}) {
return;
}
if (blockUpdateForActiveTasks()) return;
+ const attempt = ++activeDownloadAttempt;
isDownloadingUpdate.value = true;
downloadProgress.value = 0;
let unlisten: (() => void) | undefined;
const latestVersion = updateInfo.value?.latest_version;
- let failureMessageKey = "updates.downloadFailed";
try {
+ await pendingCancellation;
+ if (attempt !== activeDownloadAttempt) return;
const { listen } = await import("@tauri-apps/api/event");
unlisten = await listen<UpdateDownloadProgress>("update-download-progress", (event) => {
+ if (attempt !== activeDownloadAttempt) return;
const total = event.payload.total ?? 0;
downloadProgress.value = total > 0 ? Math.round((event.payload.downloaded / total) * 100) : 0;
});
const result = await downloadAndInstallUpdateWhenIdle({
getActiveTaskCount: () => activeTaskCount.value,
download: async () => {
- try {
- await api.downloadUpdate(normalizeUpdateDownloadSource(settingsStore.editorSettings.updateDownloadSource), latestVersion);
- downloadProgress.value = 100;
- updateDownloaded.value = true;
- } finally {
- isDownloadingUpdate.value = false;
- }
+ await api.downloadUpdate(normalizeUpdateDownloadSource(settingsStore.editorSettings.updateDownloadSource), latestVersion);
+ if (attempt !== activeDownloadAttempt) throw new Error("Download canceled by user.");
+ downloadProgress.value = 100;
+ updateDownloaded.value = true;
+ isDownloadingUpdate.value = false;
},
install: async () => {
- failureMessageKey = "updates.installFailed";
await installPendingUpdate();
},
});
@@ -159,10 +167,20 @@ export function useAppUpdater(options: UseAppUpdaterOptions = {}) {
blockUpdateForActiveTasks();
}
} catch (e: any) {
- toast(t(failureMessageKey, { error: e?.message || String(e) }), 5000);
+ if (attempt !== activeDownloadAttempt) return;
+ downloadProgress.value = 0;
+ const rawMsg = e?.message || String(e);
+ console.error("[DBX update error]", rawMsg);
+ const lower = rawMsg.toLowerCase();
+ if (lower.includes("canceled") || lower.includes("cancelled")) {
+ return;
+ }
+ toast(formatUpdateError(rawMsg), 5000);
} finally {
unlisten?.();
- isDownloadingUpdate.value = false;
+ if (attempt === activeDownloadAttempt) {
+ isDownloadingUpdate.value = false;
+ }
}
}
@@ -203,6 +221,25 @@ export function useAppUpdater(options: UseAppUpdaterOptions = {}) {
}
}
+ async function cancelDownload() {
+ if (isDownloadingUpdate.value) {
+ activeDownloadAttempt += 1;
+ isDownloadingUpdate.value = false;
+ downloadProgress.value = 0;
+ if (isTauriRuntime()) {
+ const cancellation = api.cancelUpdateDownload().catch(() => {});
+ pendingCancellation = cancellation;
+ try {
+ await cancellation;
+ } finally {
+ if (pendingCancellation === cancellation) {
+ pendingCancellation = undefined;
+ }
+ }
+ }
+ }
+ }
+
return {
checkingUpdates,
updateInfo,
@@ -221,6 +258,7 @@ export function useAppUpdater(options: UseAppUpdaterOptions = {}) {
formatUpdateError,
openLatestRelease,
downloadAndInstallUpdate,
+ cancelDownload,
installDownloadedUpdate,
restartApp,
};
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 5cb5ddeda3..9e414b5631 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -75,6 +75,8 @@ export default {
windows7ManualUpdate: "Windows 7 requires the dedicated WebView2 109 offline installer. Open the release page and download the Windows 7 package to update.",
downloading: "Downloading {progress}%",
downloadFailed: "Update download failed: {error}",
+ downloadCanceled: "Update download canceled.",
+ networkOrMirrorFailed: "Network connection timed out or download mirrors are currently unreachable. Please check your connection or click 'Open Release' to download manually.",
installing: "Installing update...",
installFailed: "Update installation failed: {error}",
restart: "Exit & Restart",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 3ef4ae85d0..a2a700f0a2 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -77,6 +77,8 @@ export default withEnglishFallback({
windows7ManualUpdate: "Windows 7 requiere el instalador sin conexión dedicado de WebView2 109. Abre la página de lanzamiento y descarga el paquete para Windows 7.",
downloading: "Descargando {progress}%",
downloadFailed: "Error al descargar la actualización: {error}",
+ downloadCanceled: "Descarga de actualización cancelada.",
+ networkOrMirrorFailed: "El tiempo de espera de la conexión de red se ha agotado o los espejos de descarga no están disponibles. Compruebe su red o haga clic en 'Abrir lanzamiento' para descargar manualmente.",
installing: "Instalando actualización...",
installFailed: "Error al instalar la actualización: {error}",
restart: "Salir y reiniciar",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index fe1296a80a..30d22e317a 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -76,6 +76,8 @@ export default withEnglishFallback({
windows7ManualUpdate: "Windows 7 richiede il programma di installazione offline dedicato WebView2 109. Apri la pagina della release e scarica il pacchetto per Windows 7.",
downloading: "Download in corso {progress}%",
downloadFailed: "Download dell'aggiornamento non riuscito: {error}",
+ downloadCanceled: "Download dell'aggiornamento annullato.",
+ networkOrMirrorFailed: "Connessione di rete scaduta o server mirror temporaneamente non disponibili. Controlla la rete o fai clic su 'Apri Release' per scaricare manualmente.",
installing: "Installazione dell'aggiornamento...",
installFailed: "Installazione dell'aggiornamento non riuscita: {error}",
restart: "Esci e Riavvia",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 634e858600..fd9dc14a0c 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -77,6 +77,8 @@ export default withEnglishFallback({
windows7ManualUpdate: "Windows 7 では専用の WebView2 109 オフラインインストーラーが必要です。リリースページから Windows 7 用パッケージをダウンロードして更新してください。",
downloading: "ダウンロード中 {progress}%",
downloadFailed: "アップデートのダウンロードに失敗しました: {error}",
+ downloadCanceled: "アップデートのダウンロードがキャンセルされました。",
+ networkOrMirrorFailed: "ネットワーク接続がタイムアウトしたか、ミラーサーバーにアクセスできません。ネットワークを確認するか、「リリースページを開く」をクリックして手動でダウンロードしてください。",
installing: "アップデートをインストール中...",
installFailed: "アップデートのインストールに失敗しました: {error}",
restart: "終了して再起動",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 3d9a6936f4..3d7b3e5185 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -77,6 +77,8 @@ export default withEnglishFallback({
windows7ManualUpdate: "Windows 7은 전용 WebView2 109 오프라인 설치 프로그램이 필요합니다. 릴리스 페이지를 열어 Windows 7 패키지를 다운로드하여 업데이트하세요.",
downloading: "다운로드 중 {progress}%",
downloadFailed: "업데이트 다운로드에 실패했습니다: {error}",
+ downloadCanceled: "업데이트 다운로드가 취소되었습니다.",
+ networkOrMirrorFailed: "네트워크 연결 시간이 초과되었거나 다운로드 미러에 연결할 수 없습니다. 네트워크를 확인하거나 '릴리스 열기'를 클릭하여 수동으로 다운로드하세요.",
installing: "업데이트 설치 중...",
installFailed: "업데이트 설치에 실패했습니다: {error}",
restart: "종료 후 다시 시작",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 96db3293da..0a1c5988eb 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -77,6 +77,8 @@ export default withEnglishFallback({
windows7ManualUpdate: "O Windows 7 requer o instalador offline dedicado do WebView2 109. Abra a página da versão e baixe o pacote para Windows 7.",
downloading: "Baixando {progress}%",
downloadFailed: "Falha ao baixar a atualização: {error}",
+ downloadCanceled: "Download da atualização cancelado.",
+ networkOrMirrorFailed: "O tempo de conexão esgotou ou os espelhos de download estão indisponíveis. Verifique sua rede ou clique em 'Abrir Lançamento' para baixar manualmente.",
installing: "Instalando atualização...",
installFailed: "Falha ao instalar a atualização: {error}",
restart: "Sair e Reiniciar",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 1acade3c75..7d93deafa3 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -77,6 +77,8 @@ export default withEnglishFallback({
windows7ManualUpdate: "Windows 7 需要使用专用的 WebView2 109 离线安装包更新。请打开下载页并下载 Windows 7 安装包。",
downloading: "下载中 {progress}%",
downloadFailed: "更新下载失败:{error}",
+ downloadCanceled: "已取消更新下载。",
+ networkOrMirrorFailed: "网络连接超时或所有镜像源暂不可用。请检查网络状态,或点击“打开下载页”手动下载。",
installing: "正在安装更新...",
installFailed: "更新安装失败:{error}",
restart: "退出并重启",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index d8587ed523..5bd0cf575a 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -77,6 +77,8 @@ export default withEnglishFallback({
windows7ManualUpdate: "Windows 7 需要使用專用的 WebView2 109 離線安裝套件更新。請開啟下載頁並下載 Windows 7 安裝套件。",
downloading: "下載中 {progress}%",
downloadFailed: "更新下載失敗:{error}",
+ downloadCanceled: "已取消更新下載。",
+ networkOrMirrorFailed: "網路連接超時或所有鏡像源暫不可用。請檢查網路狀態,或點擊“開啟下載頁”手動下載。",
installing: "正在安裝更新...",
installFailed: "更新安裝失敗:{error}",
restart: "結束並重新啟動",
diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.ts
index badee5209c..95896650bb 100644
--- a/apps/desktop/src/lib/backend/api.ts
+++ b/apps/desktop/src/lib/backend/api.ts
@@ -592,6 +592,7 @@ export const checkForUpdates = forward("checkForUpdates");
export const fetchChangelog = forward("fetchChangelog");
export const getSystemProxyUrl = forward("getSystemProxyUrl");
export const downloadUpdate = forward("downloadUpdate");
+export const cancelUpdateDownload = forward("cancelUpdateDownload");
export const installDownloadedUpdate = forward("installDownloadedUpdate");
export const getAppVersion = forward("getAppVersion");
export const getAppSupportInfo = forward("getAppSupportInfo");
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index de81244647..33136e2206 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -3261,6 +3261,8 @@ export async function downloadUpdate(_source: UpdateDownloadSource, _latestVersi
throw new Error("In-app update downloads are only available in the desktop app.");
}
+export async function cancelUpdateDownload(): Promise<void> {}
+
export async function installDownloadedUpdate(): Promise<void> {
throw new Error("In-app update installation is only available in the desktop app.");
}
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index e99ad295c8..e6a28e952e 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -1885,6 +1885,10 @@ export async function downloadUpdate(source: UpdateDownloadSource, latestVersion
return invoke("download_update", { source, latestVersion });
}
+export async function cancelUpdateDownload(): Promise<void> {
+ return invoke("cancel_update_download");
+}
+
export async function installDownloadedUpdate(): Promise<void> {
return invoke("install_downloaded_update");
}
diff --git a/src-tauri/src/commands/update.rs b/src-tauri/src/commands/update.rs
index 2647576268..e0247fd1a8 100644
--- a/src-tauri/src/commands/update.rs
+++ b/src-tauri/src/commands/update.rs
@@ -1,3 +1,4 @@
+use std::future::Future;
use std::sync::{
atomic::{AtomicU64, Ordering},
Arc, Mutex,
@@ -19,6 +20,8 @@ const R2_LATEST_RELEASE_DOWNLOAD_PREFIX: &str = "https://dl.dbxio.com/releases/l
const CNB_RELEASE_DOWNLOAD_PREFIX: &str = "https://cnb.cool/dbxio.com/dbx/-/releases/download/";
const GITHUB_RELEASE_DOWNLOAD_PREFIX: &str = "https://github.com/t8y2/dbx/releases/download/";
const UPDATE_DOWNLOAD_PROGRESS_EVENT: &str = "update-download-progress";
+const DOWNLOAD_CANCELED_ERROR: &str = "Download canceled by user.";
+const DOWNLOAD_STALL_TIMEOUT: Duration = Duration::from_secs(15);
const MAX_PORTABLE_ARCHIVE_BYTES: usize = 512 * 1024 * 1024;
const MAX_PORTABLE_SIGNATURE_BYTES: usize = 64 * 1024;
const IS_WINDOWS_7_TARGET: bool = cfg!(target_vendor = "win7");
@@ -37,7 +40,7 @@ pub struct UpdateDownloadProgress {
}
enum PendingUpdate {
- Downloading,
+ Downloading(Arc<DownloadCancellation>),
Installing,
Ready(ReadyUpdate),
}
@@ -53,30 +56,86 @@ struct PortableAssetCandidate {
signature_url: String,
}
+#[derive(Debug)]
+struct DownloadCancellation {
+ canceled: tokio::sync::watch::Sender<bool>,
+}
+
+impl Default for DownloadCancellation {
+ fn default() -> Self {
+ let (canceled, _) = tokio::sync::watch::channel(false);
+ Self { canceled }
+ }
+}
+
+impl DownloadCancellation {
+ fn cancel(&self) {
+ self.canceled.send_replace(true);
+ }
+
+ fn is_canceled(&self) -> bool {
+ *self.canceled.borrow()
+ }
+
+ async fn canceled(&self) {
+ let mut canceled = self.canceled.subscribe();
+ if *canceled.borrow() {
+ return;
+ }
+ while canceled.changed().await.is_ok() {
+ if *canceled.borrow_and_update() {
+ return;
+ }
+ }
+ }
+}
+
#[derive(Default)]
pub struct PendingUpdateState {
pending: Mutex<Option<PendingUpdate>>,
}
impl PendingUpdateState {
- fn begin_download(&self) -> Result<(), String> {
+ fn begin_download(&self) -> Result<Arc<DownloadCancellation>, String> {
let mut pending = self.pending.lock().map_err(|_| "Update state is unavailable.".to_string())?;
if pending.is_some() {
return Err("An update is already downloading or ready to install.".to_string());
}
- *pending = Some(PendingUpdate::Downloading);
- Ok(())
+ let cancellation = Arc::new(DownloadCancellation::default());
+ *pending = Some(PendingUpdate::Downloading(Arc::clone(&cancellation)));
+ Ok(cancellation)
}
- fn finish_download(&self, update: ReadyUpdate) -> Result<(), String> {
+ fn finish_download(&self, cancellation: &Arc<DownloadCancellation>, update: ReadyUpdate) -> Result<(), String> {
let mut pending = self.pending.lock().map_err(|_| "Update state is unavailable.".to_string())?;
+ let is_current = matches!(
+ pending.as_ref(),
+ Some(PendingUpdate::Downloading(current))
+ if Arc::ptr_eq(current, cancellation) && !cancellation.is_canceled()
+ );
+ if !is_current {
+ return Err(DOWNLOAD_CANCELED_ERROR.to_string());
+ }
*pending = Some(PendingUpdate::Ready(update));
Ok(())
}
- fn cancel_download(&self) {
+ fn finish_failed_download(&self, cancellation: &Arc<DownloadCancellation>) -> Result<(), String> {
+ let mut pending = self.pending.lock().map_err(|_| "Update state is unavailable.".to_string())?;
+ let is_current = matches!(
+ pending.as_ref(),
+ Some(PendingUpdate::Downloading(current)) if Arc::ptr_eq(current, cancellation)
+ );
+ if is_current {
+ *pending = None;
+ }
+ Ok(())
+ }
+
+ pub fn cancel_download(&self) {
if let Ok(mut pending) = self.pending.lock() {
- if matches!(pending.as_ref(), Some(PendingUpdate::Downloading)) {
+ if let Some(PendingUpdate::Downloading(cancellation)) = pending.as_ref() {
+ cancellation.cancel();
*pending = None;
}
}
@@ -153,18 +212,6 @@ impl UpdateDownloadSource {
}
}
- fn r2_fallback_url(&self, url: &str) -> Result<Option<String>, String> {
- if matches!(self, Self::Official) || url.starts_with(R2_LATEST_RELEASE_DOWNLOAD_PREFIX) {
- return Ok(None);
- }
- let filename = url
- .rsplit('/')
- .next()
- .filter(|name| !name.is_empty())
- .ok_or_else(|| format!("Unsupported update download URL for {} source: {url}", self.label()))?;
- Ok(Some(format!("{R2_LATEST_RELEASE_DOWNLOAD_PREFIX}{filename}")))
- }
-
fn portable_asset_candidates(
&self,
latest_version: &str,
@@ -188,6 +235,55 @@ impl UpdateDownloadSource {
.map(|archive_url| PortableAssetCandidate { signature_url: format!("{archive_url}.sig"), archive_url })
.collect())
}
+
+ fn installer_asset_candidates(&self, download_url: &str, latest_version: Option<&str>) -> Vec<String> {
+ let filename = download_url.rsplit('/').next().filter(|name| !name.is_empty()).unwrap_or("");
+
+ let tag = latest_version.map(tag_version).unwrap_or_else(|| {
+ if let Some(pos) = download_url.find("/releases/download/") {
+ let rest = &download_url[pos + "/releases/download/".len()..];
+ if let Some(tag_end) = rest.find('/') {
+ return rest[..tag_end].to_string();
+ }
+ }
+ "".to_string()
+ });
+
+ let raw_candidates = match self {
+ Self::Official => {
+ let mut urls = Vec::new();
+ if !filename.is_empty() {
+ urls.push(format!("{R2_LATEST_RELEASE_DOWNLOAD_PREFIX}{filename}"));
+ }
+ urls.push(download_url.to_string());
+ if !tag.is_empty() && !filename.is_empty() {
+ urls.push(format!("{GITHUB_RELEASE_DOWNLOAD_PREFIX}{tag}/{filename}"));
+ }
+ urls
+ }
+ Self::Cnb => {
+ let mut urls = Vec::new();
+ if let Ok(Some(rewritten)) = self.rewrite_download_url(download_url) {
+ urls.push(rewritten);
+ } else if !tag.is_empty() && !filename.is_empty() {
+ urls.push(format!("{CNB_RELEASE_DOWNLOAD_PREFIX}{tag}/{filename}"));
+ }
+ if !filename.is_empty() {
+ urls.push(format!("{R2_LATEST_RELEASE_DOWNLOAD_PREFIX}{filename}"));
+ }
+ urls.push(download_url.to_string());
+ urls
+ }
+ };
+
+ let mut unique = Vec::new();
+ for url in raw_candidates {
+ if !unique.contains(&url) {
+ unique.push(url);
+ }
+ }
+ unique
+ }
}
fn tag_version(version: &str) -> String {
@@ -228,6 +324,11 @@ pub async fn get_system_proxy_url() -> Option<String> {
tauri::async_runtime::spawn_blocking(dbx_core::update::system_proxy_url).await.ok().flatten()
}
+#[tauri::command]
+pub fn cancel_update_download(state: tauri::State<'_, PendingUpdateState>) {
+ state.cancel_download();
+}
+
#[tauri::command]
pub async fn download_update(
app: AppHandle,
@@ -246,20 +347,20 @@ pub async fn download_update(
} else {
None
};
- state.begin_download()?;
+ let cancellation = state.begin_download()?;
let result = if let Some(version) = portable_version {
- download_portable_update_inner(&app, &source, &version)
+ download_portable_update_inner(&app, &source, &version, &cancellation)
.await
.map(|archive| ReadyUpdate::Portable { archive, version })
} else {
- download_update_inner(&app, &source, latest_version.as_deref())
+ download_update_inner(&app, &source, latest_version.as_deref(), &cancellation)
.await
.map(|(update, bytes)| ReadyUpdate::Installer { update: Box::new(update), bytes })
};
match result {
- Ok(update) => state.finish_download(update),
+ Ok(update) => state.finish_download(&cancellation, update),
Err(error) => {
- state.cancel_download();
+ state.finish_failed_download(&cancellation)?;
Err(error)
}
}
@@ -269,6 +370,7 @@ async fn download_update_inner(
app: &AppHandle,
source: &UpdateDownloadSource,
latest_version: Option<&str>,
+ cancellation: &Arc<DownloadCancellation>,
) -> Result<(Update, Vec<u8>), String> {
let endpoint_urls = source.endpoints(latest_version)?;
println!("[DBX updater] checking from {} endpoints: {}", source.label(), endpoint_urls.join(", "));
@@ -286,46 +388,89 @@ async fn download_update_inner(
let updater = builder.build().map_err(|e| format!("Failed to create updater: {e}"))?;
let update = updater.check().await.map_err(|e| format!("Failed to check updates: {e}"))?;
- let Some(mut update) = update else {
+ let Some(update) = update else {
return Err("No update available.".to_string());
};
- if let Some(download_url) = source.rewrite_download_url(update.download_url.as_str())? {
- update.download_url = download_url.parse().map_err(|e| format!("Invalid CNB update download URL: {e}"))?;
- }
- if !update_url_is_available(update.download_url.as_str()).await {
- if let Some(fallback_url) = source.r2_fallback_url(update.download_url.as_str())? {
- println!("[DBX updater] {} asset unavailable; falling back to R2: {fallback_url}", source.label());
- update.download_url = fallback_url.parse().map_err(|e| format!("Invalid R2 update download URL: {e}"))?;
+
+ let candidates = source.installer_asset_candidates(update.download_url.as_str(), latest_version);
+ println!("[DBX updater] candidates for installer download: {:?}", candidates);
+
+ let mut failures = Vec::new();
+
+ for candidate_url in candidates {
+ if cancellation.is_canceled() {
+ return Err(DOWNLOAD_CANCELED_ERROR.to_string());
+ }
+ println!("[DBX updater] downloading installer update from {candidate_url}");
+ let parsed_url = match reqwest::Url::parse(&candidate_url) {
+ Ok(url) => url,
+ Err(e) => {
+ failures.push(format!("{candidate_url}: Invalid URL ({e})"));
+ continue;
+ }
+ };
+
+ let downloaded = Arc::new(AtomicU64::new(0));
+ let finished_downloaded = Arc::clone(&downloaded);
+ let progress_app_chunk = app.clone();
+ let progress_app_finish = app.clone();
+
+ let (progress_tx, progress_rx) = tokio::sync::mpsc::channel::<()>(16);
+
+ let download_result = {
+ let mut candidate_update = update.clone();
+ candidate_update.download_url = parsed_url.clone();
+
+ let download_fut = async move {
+ candidate_update
+ .download(
+ move |chunk_len, total| {
+ let downloaded = downloaded
+ .fetch_add(chunk_len as u64, Ordering::Relaxed)
+ .saturating_add(chunk_len as u64);
+ let _ = progress_app_chunk
+ .emit(UPDATE_DOWNLOAD_PROGRESS_EVENT, UpdateDownloadProgress { downloaded, total });
+ let _ = progress_tx.try_send(());
+ },
+ move || {
+ let downloaded = finished_downloaded.load(Ordering::Relaxed);
+ let _ = progress_app_finish.emit(
+ UPDATE_DOWNLOAD_PROGRESS_EVENT,
+ UpdateDownloadProgress { downloaded, total: Some(downloaded) },
+ );
+ },
+ )
+ .await
+ .map_err(|error| format!("Failed to download update: {error}"))
+ };
+
+ wait_for_progressing_download(download_fut, progress_rx, cancellation, DOWNLOAD_STALL_TIMEOUT).await
+ };
+
+ match download_result {
+ Ok(bytes) => {
+ let mut ready_update = update.clone();
+ ready_update.download_url = parsed_url;
+ return Ok((ready_update, bytes));
+ }
+ Err(error) => {
+ if cancellation.is_canceled() || error.contains("canceled") {
+ return Err(DOWNLOAD_CANCELED_ERROR.to_string());
+ }
+ println!("[DBX updater] installer candidate failed ({candidate_url}): {error}");
+ failures.push(format!("{candidate_url}: {error}"));
+ }
}
}
- println!("[DBX updater] downloading from {} URL: {}", source.label(), update.download_url);
-
- let downloaded = Arc::new(AtomicU64::new(0));
- let finished_downloaded = Arc::clone(&downloaded);
- let bytes = update
- .download(
- |chunk_len, total| {
- let downloaded =
- downloaded.fetch_add(chunk_len as u64, Ordering::Relaxed).saturating_add(chunk_len as u64);
- let _ = app.emit(UPDATE_DOWNLOAD_PROGRESS_EVENT, UpdateDownloadProgress { downloaded, total });
- },
- || {
- let downloaded = finished_downloaded.load(Ordering::Relaxed);
- let _ = app.emit(
- UPDATE_DOWNLOAD_PROGRESS_EVENT,
- UpdateDownloadProgress { downloaded, total: Some(downloaded) },
- );
- },
- )
- .await
- .map_err(|e| format!("Failed to download update: {e}"))?;
- Ok((update, bytes))
+
+ Err(format!("Failed to download update after trying all available mirrors. {}", failures.join("; ")))
}
async fn download_portable_update_inner(
app: &AppHandle,
source: &UpdateDownloadSource,
latest_version: &Version,
+ cancellation: &Arc<DownloadCancellation>,
) -> Result<Vec<u8>, String> {
let latest_version_text = latest_version.to_string();
let candidates = source.portable_asset_candidates(&latest_version_text, std::env::consts::ARCH)?;
@@ -333,14 +478,29 @@ async fn download_portable_update_inner(
let mut failures = Vec::new();
for candidate in candidates {
+ if cancellation.is_canceled() {
+ return Err(DOWNLOAD_CANCELED_ERROR.to_string());
+ }
println!("[DBX updater] downloading portable update from {}", candidate.archive_url);
let result = async {
- let signature =
- download_bounded_bytes(&client, &candidate.signature_url, MAX_PORTABLE_SIGNATURE_BYTES, None).await?;
+ let signature = download_bounded_bytes(
+ &client,
+ &candidate.signature_url,
+ MAX_PORTABLE_SIGNATURE_BYTES,
+ None,
+ cancellation,
+ )
+ .await?;
let signature = String::from_utf8(signature)
.map_err(|error| format!("Portable update signature is not valid UTF-8: {error}"))?;
- let archive =
- download_bounded_bytes(&client, &candidate.archive_url, MAX_PORTABLE_ARCHIVE_BYTES, Some(app)).await?;
+ let archive = download_bounded_bytes(
+ &client,
+ &candidate.archive_url,
+ MAX_PORTABLE_ARCHIVE_BYTES,
+ Some(app),
+ cancellation,
+ )
+ .await?;
update_portable::verify_portable_archive(&archive, &signature, latest_version, std::env::consts::ARCH)?;
Ok::<Vec<u8>, String>(archive)
}
@@ -349,6 +509,9 @@ async fn download_portable_update_inner(
match result {
Ok(archive) => return Ok(archive),
Err(error) => {
+ if cancellation.is_canceled() || error.contains("canceled") {
+ return Err(DOWNLOAD_CANCELED_ERROR.to_string());
+ }
println!("[DBX updater] portable update candidate failed: {error}");
failures.push(format!("{}: {error}", candidate.archive_url));
}
@@ -359,8 +522,10 @@ async fn download_portable_update_inner(
}
fn portable_update_http_client() -> Result<reqwest::Client, String> {
- let mut builder =
- reqwest::Client::builder().connect_timeout(Duration::from_secs(15)).timeout(Duration::from_secs(15 * 60));
+ let mut builder = reqwest::Client::builder()
+ .connect_timeout(Duration::from_secs(15))
+ .read_timeout(Duration::from_secs(15))
+ .timeout(Duration::from_secs(15 * 60));
if let Some(proxy_url) = dbx_core::update::system_proxy_url() {
let proxy = reqwest::Proxy::all(&proxy_url).map_err(|error| format!("Invalid system proxy URL: {error}"))?;
builder = builder.proxy(proxy);
@@ -373,14 +538,26 @@ async fn download_bounded_bytes(
url: &str,
max_bytes: usize,
progress_app: Option<&AppHandle>,
+ cancellation: &DownloadCancellation,
) -> Result<Vec<u8>, String> {
- let mut response = client
- .get(url)
- .send()
- .await
+ if cancellation.is_canceled() {
+ return Err(DOWNLOAD_CANCELED_ERROR.to_string());
+ }
+
+ let request_fut = client.get(url).send();
+ let response_res = wait_for_download_step(
+ request_fut,
+ cancellation,
+ DOWNLOAD_STALL_TIMEOUT,
+ format!("Connection stalled while connecting to {url}"),
+ )
+ .await?;
+
+ let mut response = response_res
.map_err(|error| format!("Failed to request {url}: {error}"))?
.error_for_status()
.map_err(|error| format!("Failed to download {url}: {error}"))?;
+
let total = response.content_length();
if total.is_some_and(|total| total > max_bytes as u64) {
return Err(format!("Update asset exceeds the {max_bytes} byte limit."));
@@ -390,9 +567,27 @@ async fn download_bounded_bytes(
let _ = app.emit(UPDATE_DOWNLOAD_PROGRESS_EVENT, UpdateDownloadProgress { downloaded: 0, total });
}
let mut bytes = Vec::with_capacity(total.unwrap_or(0).min(max_bytes as u64) as usize);
- while let Some(chunk) =
- response.chunk().await.map_err(|error| format!("Failed while downloading {url}: {error}"))?
- {
+
+ loop {
+ if cancellation.is_canceled() {
+ return Err(DOWNLOAD_CANCELED_ERROR.to_string());
+ }
+
+ let chunk_fut = response.chunk();
+ let chunk_res = wait_for_download_step(
+ chunk_fut,
+ cancellation,
+ DOWNLOAD_STALL_TIMEOUT,
+ format!("Download stalled: no data received for 15 seconds from {url}"),
+ )
+ .await?;
+
+ let chunk = match chunk_res {
+ Ok(Some(chunk)) => chunk,
+ Ok(None) => break,
+ Err(error) => return Err(format!("Failed while downloading {url}: {error}")),
+ };
+
if bytes.len().saturating_add(chunk.len()) > max_bytes {
return Err(format!("Update asset exceeds the {max_bytes} byte limit."));
}
@@ -405,6 +600,47 @@ async fn download_bounded_bytes(
Ok(bytes)
}
+async fn wait_for_progressing_download<T>(
+ download: impl Future<Output = Result<T, String>>,
+ mut progress: tokio::sync::mpsc::Receiver<()>,
+ cancellation: &DownloadCancellation,
+ stall_timeout: Duration,
+) -> Result<T, String> {
+ tokio::pin!(download);
+ let stall = tokio::time::sleep(stall_timeout);
+ tokio::pin!(stall);
+ let mut progress_open = true;
+
+ loop {
+ tokio::select! {
+ biased;
+ _ = cancellation.canceled() => return Err(DOWNLOAD_CANCELED_ERROR.to_string()),
+ result = &mut download => return result,
+ update = progress.recv(), if progress_open => {
+ if update.is_some() {
+ stall.as_mut().reset(tokio::time::Instant::now() + stall_timeout);
+ } else {
+ progress_open = false;
+ }
+ }
+ _ = &mut stall => return Err("Download stalled: no data received for 15 seconds".to_string()),
+ }
+ }
+}
+
+async fn wait_for_download_step<T>(
+ step: impl Future<Output = T>,
+ cancellation: &DownloadCancellation,
+ stall_timeout: Duration,
+ timeout_error: String,
+) -> Result<T, String> {
+ tokio::select! {
+ biased;
+ _ = cancellation.canceled() => Err(DOWNLOAD_CANCELED_ERROR.to_string()),
+ result = tokio::time::timeout(stall_timeout, step) => result.map_err(|_| timeout_error),
+ }
+}
+
#[tauri::command]
pub fn install_downloaded_update(app: AppHandle, state: tauri::State<'_, PendingUpdateState>) -> Result<(), String> {
let ready = state.take_ready()?;
@@ -439,26 +675,15 @@ fn schedule_portable_update_exit(app: AppHandle) {
});
}
-async fn update_url_is_available(url: &str) -> bool {
- let client = match reqwest::Client::builder().timeout(std::time::Duration::from_secs(10)).build() {
- Ok(client) => client,
- Err(_) => return false,
- };
- // Request only the first byte because some release hosts do not implement HEAD consistently.
- client
- .get(url)
- .header(reqwest::header::RANGE, "bytes=0-0")
- .send()
- .await
- .is_ok_and(|response| response.status().is_success())
-}
-
#[cfg(test)]
mod tests {
use super::{
- requires_manual_update, tag_version, UpdateDownloadSource, CNB_RELEASE_DOWNLOAD_PREFIX,
- GITHUB_RELEASE_DOWNLOAD_PREFIX, OFFICIAL_UPDATE_ENDPOINTS, R2_LATEST_RELEASE_DOWNLOAD_PREFIX,
+ requires_manual_update, tag_version, wait_for_download_step, wait_for_progressing_download,
+ DownloadCancellation, PendingUpdateState, UpdateDownloadSource, CNB_RELEASE_DOWNLOAD_PREFIX,
+ DOWNLOAD_CANCELED_ERROR, GITHUB_RELEASE_DOWNLOAD_PREFIX, OFFICIAL_UPDATE_ENDPOINTS,
+ R2_LATEST_RELEASE_DOWNLOAD_PREFIX,
};
+ use std::{future::pending, sync::Arc, time::Duration};
#[test]
fn all_windows_7_builds_require_manual_updates() {
@@ -504,14 +729,6 @@ mod tests {
assert_eq!(download_url, None);
}
- #[test]
- fn builds_r2_fallback_for_mirror_asset() {
- let fallback = UpdateDownloadSource::Cnb
- .r2_fallback_url("https://cnb.cool/dbxio.com/dbx/-/releases/download/v0.5.44/DBX_0.5.44_x64.dmg")
- .unwrap();
- assert_eq!(fallback, Some(format!("{R2_LATEST_RELEASE_DOWNLOAD_PREFIX}DBX_0.5.44_x64.dmg")));
- }
-
#[test]
fn builds_signed_official_portable_asset_candidates() {
let candidates = UpdateDownloadSource::Official.portable_asset_candidates("0.5.64", "x86_64").unwrap();
@@ -539,4 +756,96 @@ mod tests {
format!("{R2_LATEST_RELEASE_DOWNLOAD_PREFIX}DBX_0.5.64_arm64-portable.zip")
);
}
+
+ #[test]
+ fn builds_installer_asset_candidates_for_cnb_source() {
+ let candidates = UpdateDownloadSource::Cnb.installer_asset_candidates(
+ "https://github.com/t8y2/dbx/releases/download/v0.5.64/DBX_0.5.64_aarch64.dmg",
+ Some("0.5.64"),
+ );
+ assert_eq!(candidates.len(), 3);
+ assert_eq!(candidates[0], "https://cnb.cool/dbxio.com/dbx/-/releases/download/v0.5.64/DBX_0.5.64_aarch64.dmg");
+ assert_eq!(candidates[1], format!("{R2_LATEST_RELEASE_DOWNLOAD_PREFIX}DBX_0.5.64_aarch64.dmg"));
+ assert_eq!(candidates[2], "https://github.com/t8y2/dbx/releases/download/v0.5.64/DBX_0.5.64_aarch64.dmg");
+ }
+
+ #[test]
+ fn builds_installer_asset_candidates_for_official_source() {
+ let candidates = UpdateDownloadSource::Official.installer_asset_candidates(
+ "https://github.com/t8y2/dbx/releases/download/v0.5.64/DBX_0.5.64_aarch64.dmg",
+ Some("0.5.64"),
+ );
+ assert_eq!(candidates.len(), 2);
+ assert_eq!(candidates[0], format!("{R2_LATEST_RELEASE_DOWNLOAD_PREFIX}DBX_0.5.64_aarch64.dmg"));
+ assert_eq!(candidates[1], "https://github.com/t8y2/dbx/releases/download/v0.5.64/DBX_0.5.64_aarch64.dmg");
+ assert!(!candidates.iter().any(|url| url.contains("cnb.cool")));
+ }
+
+ #[test]
+ fn retry_uses_an_independent_cancellation_token() {
+ let state = PendingUpdateState::default();
+ let first = state.begin_download().unwrap();
+
+ state.cancel_download();
+ let second = state.begin_download().unwrap();
+
+ assert!(first.is_canceled());
+ assert!(!second.is_canceled());
+ }
+
+ #[test]
+ fn stale_attempt_cannot_clear_an_active_retry() {
+ let state = PendingUpdateState::default();
+ let first = state.begin_download().unwrap();
+ state.cancel_download();
+ let second = state.begin_download().unwrap();
+
+ state.finish_failed_download(&first).unwrap();
+
+ assert!(state.begin_download().is_err());
+ assert!(!second.is_canceled());
+ }
+
+ #[tokio::test]
+ async fn cancel_wakes_installer_download_without_waiting_for_stall_timeout() {
+ let cancellation = Arc::new(DownloadCancellation::default());
+ let task_cancellation = Arc::clone(&cancellation);
+ let (_progress_tx, progress_rx) = tokio::sync::mpsc::channel(1);
+ let task = tokio::spawn(async move {
+ wait_for_progressing_download(
+ pending::<Result<(), String>>(),
+ progress_rx,
+ &task_cancellation,
+ Duration::from_secs(30),
+ )
+ .await
+ });
+
+ tokio::task::yield_now().await;
+ cancellation.cancel();
+
+ let result = tokio::time::timeout(Duration::from_secs(1), task).await.unwrap().unwrap();
+ assert_eq!(result.unwrap_err(), DOWNLOAD_CANCELED_ERROR);
+ }
+
+ #[tokio::test]
+ async fn cancel_wakes_portable_network_read_without_waiting_for_timeout() {
+ let cancellation = Arc::new(DownloadCancellation::default());
+ let task_cancellation = Arc::clone(&cancellation);
+ let task = tokio::spawn(async move {
+ wait_for_download_step(
+ pending::<()>(),
+ &task_cancellation,
+ Duration::from_secs(30),
+ "network timeout".to_string(),
+ )
+ .await
+ });
+
+ tokio::task::yield_now().await;
+ cancellation.cancel();
+
+ let result = tokio::time::timeout(Duration::from_secs(1), task).await.unwrap().unwrap();
+ assert_eq!(result.unwrap_err(), DOWNLOAD_CANCELED_ERROR);
+ }
}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index f926435b21..2ab7e9fb34 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -2054,6 +2054,7 @@ pub fn run() {
commands::update::fetch_changelog,
commands::update::get_system_proxy_url,
commands::update::download_update,
+ commands::update::cancel_update_download,
commands::update::install_downloaded_update,
commands::transfer::start_transfer,
commands::transfer::preview_transfer_ownership,