diff --git a/app/core/download_diagnostics.py b/app/core/download_diagnostics.py new file mode 100644 index 000000000..27f362954 --- /dev/null +++ b/app/core/download_diagnostics.py @@ -0,0 +1,140 @@ +"""Bounded, credential-safe archive diagnostics shared by all managed downloads. + +This is diagnostic evidence, not an installer acceptance or integrity check. +Never store raw signed URLs, ZIP entry lists, arbitrary text files or payloads. +""" + +from __future__ import annotations + +import io +import re +import zipfile +from pathlib import Path +from urllib.parse import urlsplit + +# 限制实际读取量,ZIP64 和带注释的 ZIP 同样经过此预算。 +_MAX_ZIP_INSPECTION_BYTES = 4 * 1024 * 1024 +_MAX_MARKERS = 6 +_MAX_MARKER_BYTES = 256 +_MAX_COMPRESSED_MARKER_BYTES = 4096 +_VERSION = re.compile(r"v?\d{1,4}(?:\.\d{1,4}){1,4}(?:[-.][A-Za-z0-9.-]+)?") +_URL_IN_ERROR = re.compile(r"https?://[^\s<>\"']+", re.IGNORECASE) +_MARKER_NAMES = {"version.txt", "version", "version.json"} + + +class _ZipInspectionLimit(Exception): + """ZIP 诊断超过读取或版本标记预算。""" + + +class _BoundedZipReader(io.FileIO): + """拒绝超额的 ZIP 目录读取,避免解析器先分配超大目录。""" + + def __init__(self, path: Path) -> None: + super().__init__(path, "rb") + self._remaining = _MAX_ZIP_INSPECTION_BYTES + + def read(self, size: int = -1, /) -> bytes: + if size > self._remaining: + raise _ZipInspectionLimit + # zipfile 查找带注释的目录尾时会在文件尾部调用无参 read。 + # 此时读至多剩余预算加一字节,用于区分恰好 EOF 与仍有数据。 + limit = self._remaining + 1 if size < 0 else size + data = super().read(limit) + assert data is not None + self._remaining -= len(data) + if self._remaining < 0: + raise _ZipInspectionLimit + return data + + +def safe_origin(url: str) -> str: + """Only retain protocol and hostname, excluding query, path and credentials.""" + try: + parsed = urlsplit(url) + host = parsed.hostname + if not host: + return "(hidden)" + if ":" in host: + host = f"[{host}]" + return f"{parsed.scheme}://{host}" + except ValueError: + return "(hidden)" + + +def redact_history_error(error: str | None) -> str | None: + """保留错误描述,将其中的下载链接缩减为来源域名。""" + return ( + _URL_IN_ERROR.sub(lambda match: safe_origin(match.group(0)), error) + if error + else error + ) + + +def describe_package(path: Path) -> dict[str, object]: + """Produce small evidence while the package still exists. + + ZIP central directory inspection does not extract files. Non-ZIP payloads + remain classified as opaque; their structure must be supplied by adapters. + """ + result: dict[str, object] = {"schema": 1, "format": "opaque"} + try: + result["bytes"] = path.stat().st_size + except OSError: + result["availability"] = "missing" + return result + + try: + with _BoundedZipReader(path) as stream, zipfile.ZipFile(stream) as archive: + entries = archive.infolist() + roots = set() + markers: list[dict[str, str]] = [] + attempts = 0 + for item in entries: + relative = item.filename.replace("\\", "/") + if relative: + roots.add(relative.partition("/")[0]) + name = relative.rpartition("/")[2].lower() + if ( + name not in _MARKER_NAMES + or item.file_size > _MAX_MARKER_BYTES + or item.compress_size > _MAX_COMPRESSED_MARKER_BYTES + or item.compress_type + not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED) + ): + continue + if attempts >= _MAX_MARKERS: + raise _ZipInspectionLimit + attempts += 1 + try: + with archive.open(item) as reader: + value = reader.read(_MAX_MARKER_BYTES + 1).decode( + "utf-8", errors="replace" + ) + except (OSError, ValueError, RuntimeError, zipfile.BadZipFile): + continue + match = _VERSION.search(value) + if match is not None: + markers.append({"name": name, "version": match.group(0)}) + known_roots = {"update", "March7thAssistant", "March7thAssistant_full"} + result.update( + format="zip", + entries=len(entries), + expanded_bytes=sum(item.file_size for item in entries), + root_count=len(roots), + known_roots=sorted(roots & known_roots), + version_markers=markers, + ) + except _ZipInspectionLimit: + result["format"] = "zip" + except (OSError, ValueError, zipfile.BadZipFile, zipfile.LargeZipFile): + # A 7z/exe/partial file is not automatically a corrupt archive. + try: + with path.open("rb") as stream: + header = stream.read(6) + if header == b"7z\xbc\xaf\x27\x1c": + result["format"] = "7z" + elif header[:2] == b"PK": + result["format"] = "zip-invalid" + except OSError: + pass + return result diff --git a/app/core/downloads.py b/app/core/downloads.py index c90acbe79..0c542b641 100644 --- a/app/core/downloads.py +++ b/app/core/downloads.py @@ -25,14 +25,22 @@ BackgroundTaskState, TaskOutcome, ) +from app.core.download_diagnostics import ( + describe_package, + redact_history_error, + safe_origin, +) from app.models.config.setting import FluxdownRecord from app.models.schema import DownloadRequest, DownloadSnapshot from app.services.common.update import fluxdown as _service_update_fluxdown from app.services.common.update import transport as _service_update_transport from app.utils import fluxdown_cli as _utils_fluxdown_cli +from app.utils import get_logger from app.utils.common.fluxdown_cli import FluxdownCancelUnconfirmed from app.utils.common.update_files import native_path +logger = get_logger("下载历史") + type Progress = Callable[[int, int, float], Awaitable[None]] type Transfer = Callable[[DownloadRequest, Path, Progress], Awaitable[None]] @@ -104,6 +112,68 @@ async def download_file( return size observer = download_observer.get() actual_method = "FluxDown" + started_at = monotonic() + update = Config.setting.Update + frozen_source = source if source is not None else str(update.Source or "") + terminal_written = False + http_diagnostic: dict[str, object] | None = None + original_http_download = http_download or _service_update_fluxdown._httpx_download + + async def inspect_package(path: Path) -> dict[str, object]: + try: + return await asyncio.to_thread(describe_package, path) + except Exception as error: + logger.warning(f"读取下载包诊断失败: {type(error).__name__}") + return {"schema": 1, "availability": "inspection_failed"} + + async def write_attempt_record( + record: _utils_fluxdown_cli.FluxdownDownloadRecord, + *, + http_status: int | None = None, + ) -> None: + nonlocal terminal_written + record.url = safe_origin(record.url) + record.error = redact_history_error(record.error) + if record.status != "fluxdown_fallback": + terminal_written = True + if record.status == "success": + details = ( + http_diagnostic + if http_diagnostic is not None + else await inspect_package(destination) + ) + else: + details = {"schema": 1, "availability": "download_failed"} + if http_status is not None: + details["http_status"] = http_status + details.update( + { + "source": frozen_source[:48] or "unknown", + "downloader": actual_method, + "phase": "download", + } + ) + record.diagnostic = details + try: + await _write_history(record) + except Exception as error: + logger.warning(f"写入下载历史失败: {type(error).__name__}") + + async def record_result(*, size: int, error: Exception | None = None) -> None: + await write_attempt_record( + _utils_fluxdown_cli.FluxdownDownloadRecord( + url=url, + destination=str(destination), + size=size, + duration_ms=int((monotonic() - started_at) * 1000), + status="failed" if error is not None else "success", + error=type(error).__name__ if error is not None else None, + ), + http_status=error.response.status_code + if isinstance(error, httpx.HTTPStatusError) + else None, + ) + if observer is not None: original_progress = progress @@ -118,49 +188,67 @@ async def report(downloaded: int, total: int, speed: float) -> None: download_method.reset(token) progress = report - original_http_download = ( - http_download or _service_update_transport.download_file - ) - async def observed_http_download( - url, destination, *, timeout, proxy=None, progress=None - ): - """HTTP 回退时切换实际下载器标识,报告开始状态并执行内置传输。""" - nonlocal actual_method - actual_method = "httpx" + async def observed_http_download( + url: str, + destination: Path, + *, + timeout: float, + proxy: httpx.Proxy | None = None, + progress: _service_update_transport.DownloadProgress | None = None, + ) -> int: + nonlocal actual_method, http_diagnostic + actual_method = "httpx" + if observer is not None: token = download_method.set(actual_method) try: observer(destination, 0, 0, 0.0) finally: download_method.reset(token) - return await original_http_download( - url, destination, timeout=timeout, proxy=proxy, progress=progress - ) + size = await original_http_download( + url, destination, timeout=timeout, proxy=proxy, progress=progress + ) + # 此时还持有目标文件锁,后续同路径重试不能替换正在检查的包。 + http_diagnostic = await inspect_package(destination) + return size - http_download = observed_http_download - update = Config.setting.Update - return await _service_update_fluxdown.download_file( - url, - destination, - timeout=timeout, - proxy=proxy, - progress=progress, - downloader=downloader, - source=source, - http_download=http_download, - options=_service_update_fluxdown.FluxdownOptions( - downloader=update.Downloader, - source=str(update.Source or ""), - cli_path=str(update.FluxdownPath or ""), - segments=int(update.FluxdownSegments), - server_mode=bool(update.FluxdownServerMode), - cli_search_dirs=( - Config.install_path / "res" / "fluxdown-cli", - Config.resource_path / "fluxdown-cli", + try: + size = await _service_update_fluxdown.download_file( + url, + destination, + timeout=timeout, + proxy=proxy, + progress=progress, + downloader=downloader, + source=source, + http_download=observed_http_download, + options=_service_update_fluxdown.FluxdownOptions( + downloader=update.Downloader, + source=str(update.Source or ""), + cli_path=str(update.FluxdownPath or ""), + segments=int(update.FluxdownSegments), + server_mode=bool(update.FluxdownServerMode), + cli_search_dirs=( + Config.install_path / "res" / "fluxdown-cli", + Config.resource_path / "fluxdown-cli", + ), ), - ), - write_history=_write_history, - ) + write_history=write_attempt_record, + ) + except FluxdownCancelUnconfirmed: + # 停写归属未确认时立即交给调度,不能等待诊断或被取消覆盖。 + raise + except Exception as error: + if not terminal_written: + try: + await record_result(size=0, error=error) + except asyncio.CancelledError: + # 历史提交可取消,但原下载失败仍须传回调用者。 + pass + raise + if not terminal_written: + await record_result(size=size) + return size @dataclass diff --git a/app/models/config/setting.py b/app/models/config/setting.py index 845c68bfa..5c98e70d8 100644 --- a/app/models/config/setting.py +++ b/app/models/config/setting.py @@ -70,6 +70,9 @@ class FluxdownRecord(BaseModel): segments: int | None = Field(default=None, description="分段数") proxy: str | None = Field(default=None, description="使用的代理") checksum: str | None = Field(default=None, description="校验信息") + diagnostic: dict[str, object] | None = Field( + default=None, description="统一下载诊断摘要(不包含凭据和原始压缩包)" + ) status: str | None = Field( default=None, description="状态:success、failed、checksum_fail、fluxdown_fallback", diff --git a/app/utils/common/fluxdown_cli.py b/app/utils/common/fluxdown_cli.py index 00db5223e..df6c5f4ae 100644 --- a/app/utils/common/fluxdown_cli.py +++ b/app/utils/common/fluxdown_cli.py @@ -137,6 +137,7 @@ class FluxdownDownloadRecord: segments: int = 0 proxy: str | None = None checksum: str | None = None + diagnostic: dict[str, object] | None = None status: str = ( "" # success | failed | checksum_fail | interrupted | fluxdown_fallback ) @@ -159,6 +160,7 @@ def to_dict(self) -> dict: "segments": self.segments, "proxy": proxy, "checksum": self.checksum, + "diagnostic": self.diagnostic, "status": self.status, "error": self.error, "timestamp": self.timestamp, diff --git a/changelog.d/common-download-diagnostics.feat.md b/changelog.d/common-download-diagnostics.feat.md new file mode 100644 index 000000000..643f481ca --- /dev/null +++ b/changelog.d/common-download-diagnostics.feat.md @@ -0,0 +1,2 @@ +project: update +新增统一下载包诊断记录,便于排查更新包结构异常 diff --git a/frontend/src/api/models/FluxdownRecord.ts b/frontend/src/api/models/FluxdownRecord.ts index 092ac5e52..83919215a 100644 --- a/frontend/src/api/models/FluxdownRecord.ts +++ b/frontend/src/api/models/FluxdownRecord.ts @@ -34,6 +34,10 @@ export type FluxdownRecord = { * 校验信息 */ checksum?: (string | null); + /** + * 统一下载诊断摘要(不包含凭据和原始压缩包) + */ + diagnostic?: (Record | null); /** * 状态:success、failed、checksum_fail、fluxdown_fallback */ diff --git a/frontend/src/views/setting/components/DownloadHistorySettings.vue b/frontend/src/views/setting/components/DownloadHistorySettings.vue index c5dced157..6a39d372a 100644 --- a/frontend/src/views/setting/components/DownloadHistorySettings.vue +++ b/frontend/src/views/setting/components/DownloadHistorySettings.vue @@ -5,6 +5,7 @@ import { message } from 'ant-design-vue' import type { GlobalConfig, FluxdownRecord } from '@/api' import { useSettingsApi } from '@/composables/useSettingsApi' import SettingRow from '@/components/ui/SettingRow.vue' +import { downloadHistoryExport } from './downloadHistoryExport' const props = defineProps<{ settings: GlobalConfig }>() const { t } = useI18n() @@ -52,13 +53,17 @@ const formatHistorySize = (size?: number | null) => const formatHistoryDuration = (ms?: number | null) => (ms ? `${(ms / 1000).toFixed(1)}s` : '-') -// 失败/回退记录可导出:把这条下载记录存成 JSON 文件 +const canExportHistory = (item: FluxdownRecord) => + Boolean(item.diagnostic || (item.status && item.status !== 'success')) + +// 有诊断摘要或失败信息的单条下载记录可导出为 JSON 文件 const handleExportHistory = async (item: FluxdownRecord) => { try { - const fileName = `fluxdown-download-${(item.timestamp ?? '').replace(/[: ]/g, '-')}.json` + const exported = downloadHistoryExport(item) + const fileName = `fluxdown-download-${(exported.timestamp ?? '').replace(/[: ]/g, '-')}.json` const result = await window.electronAPI.saveTextFile( fileName, - JSON.stringify(item, null, 2), + JSON.stringify(exported, null, 2), [{ name: 'JSON', extensions: ['json'] }], { dialogTitle: t('core.setting.others.historyExportDialogTitle'), @@ -125,7 +130,7 @@ const showUpdateHistory = ref(false) {{ formatHistoryDuration(item.duration_ms) }} — {{ item.error }} { + const privateFields = { + url: 'https://user:secret@downloads.example:6789/private/asset.zip?token=secret', + destination: 'C:\\Users\\private\\asset.zip', + proxy: 'http://127.0.0.1:7890', + error: 'Could not write C:\\Users\\private\\asset.zip via http://127.0.0.1:7890', + checksum: 'unexpected private text', + } + + it('exports legacy failures without exposing private fields', () => { + const item = { ...privateFields, status: 'failed', size: 0 } + expect(JSON.parse(JSON.stringify(downloadHistoryExport(item)))).toEqual({ + status: 'failed', + url: 'https://downloads.example', + size: 0, + }) + expect(item).toMatchObject(privateFields) + }) + + it('preserves safe failure details and an IPv6 origin', () => { + const item = { + ...privateFields, + url: 'https://[2001:db8::1]:8443/private/update.zip?token=secret', + status: 'failed', + error: 'HTTPStatusError', + diagnostic: { schema: 1, availability: 'download_failed', http_status: 403 }, + } + expect(JSON.parse(JSON.stringify(downloadHistoryExport(item)))).toEqual({ + status: 'failed', + url: 'https://[2001:db8::1]', + error_code: 'HTTPStatusError', + diagnostic: { schema: 1, availability: 'download_failed', http_status: 403 }, + }) + }) + + it('exports a successful package summary with only known diagnostic fields', () => { + const item = { + ...privateFields, + timestamp: '2026-11-23 12:00:00', + status: 'success', + size: 420, + diagnostic: { + schema: 1, + format: 'zip', + source: 'https://proxy.example/secret', + known_roots: ['March7thAssistant', 'C:\\Users\\private'], + version_markers: [ + { name: 'version.txt', version: 'v1.2.3', path: privateFields.destination }, + { name: 'version.json', version: privateFields.destination }, + ], + path: privateFields.destination, + }, + } + expect(JSON.parse(JSON.stringify(downloadHistoryExport(item)))).toEqual({ + timestamp: '2026-11-23 12:00:00', + status: 'success', + url: 'https://downloads.example', + size: 420, + diagnostic: { + schema: 1, + format: 'zip', + known_roots: ['March7thAssistant'], + version_markers: [{ name: 'version.txt', version: 'v1.2.3' }], + }, + }) + }) +}) diff --git a/frontend/src/views/setting/components/downloadHistoryExport.ts b/frontend/src/views/setting/components/downloadHistoryExport.ts new file mode 100644 index 000000000..025a5c4ff --- /dev/null +++ b/frontend/src/views/setting/components/downloadHistoryExport.ts @@ -0,0 +1,109 @@ +import type { FluxdownRecord } from '@/api' + +const knownValue = (value: unknown, allowed: readonly string[]) => + typeof value === 'string' && allowed.includes(value) ? value : undefined + +const count = (value: unknown) => + typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined + +const errorCodes = [ + 'HTTPStatusError', + 'ConnectTimeout', + 'ReadTimeout', + 'WriteTimeout', + 'PoolTimeout', + 'ConnectError', + 'ReadError', + 'WriteError', + 'ProxyError', + 'RemoteProtocolError', + 'TimeoutError', + 'PermissionError', + 'FileNotFoundError', +] + +const httpStatus = (value: unknown) => { + const status = count(value) + return status !== undefined && status >= 100 && status <= 599 ? status : undefined +} + +const downloadOrigin = (value?: string | null) => { + try { + const { protocol, hostname } = new URL(value ?? '') + if ((protocol === 'https:' || protocol === 'http:') && hostname) { + return `${protocol}//${hostname}` + } + } catch { + // 旧记录可能只有本地路径或占位符。 + } +} + +const versionMarkers = (value: unknown) => { + if (!Array.isArray(value)) return undefined + return value.slice(0, 6).flatMap((marker: unknown) => { + if (!marker || typeof marker !== 'object' || !('name' in marker) || !('version' in marker)) { + return [] + } + const name = knownValue(marker.name, ['version.txt', 'version', 'version.json']) + const { version } = marker + return name && + typeof version === 'string' && + /^v?\d{1,4}(?:\.\d{1,4}){1,4}(?:[-.][A-Za-z0-9.-]{1,240})?$/.test(version) + ? [{ name, version }] + : [] + }) +} + +export const downloadHistoryExport = (item: FluxdownRecord) => { + const details = item.diagnostic + return { + timestamp: + item.timestamp && /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(item.timestamp) + ? item.timestamp + : undefined, + status: knownValue(item.status, [ + 'success', + 'failed', + 'checksum_fail', + 'interrupted', + 'fluxdown_fallback', + ]), + url: downloadOrigin(item.url), + error_code: knownValue(item.error, errorCodes), + size: count(item.size), + duration_ms: count(item.duration_ms), + segments: count(item.segments), + diagnostic: + details?.schema === 1 + ? { + schema: 1, + phase: knownValue(details.phase, ['download']), + format: knownValue(details.format, ['opaque', 'zip', 'zip-invalid', '7z']), + availability: knownValue(details.availability, [ + 'missing', + 'inspection_failed', + 'download_failed', + ]), + source: knownValue(details.source, [ + 'GitHub', + 'MirrorChyan', + 'AutoSite', + 'CNB', + 'unknown', + ]), + downloader: knownValue(details.downloader, ['FluxDown', 'httpx']), + http_status: httpStatus(details.http_status), + bytes: count(details.bytes), + entries: count(details.entries), + expanded_bytes: count(details.expanded_bytes), + root_count: count(details.root_count), + known_roots: Array.isArray(details.known_roots) + ? ['March7thAssistant', 'March7thAssistant_full', 'update'].filter(root => + details.known_roots.includes(root) + ) + : undefined, + version_markers: versionMarkers(details.version_markers), + } + : undefined, + } +} diff --git a/tests/core/test_download_diagnostics.py b/tests/core/test_download_diagnostics.py new file mode 100644 index 000000000..cafce1664 --- /dev/null +++ b/tests/core/test_download_diagnostics.py @@ -0,0 +1,257 @@ +"""Regression tests for bounded cross-script download diagnostics.""" + +import asyncio +import json +import zipfile + +import httpx +import pytest +from fastapi import FastAPI + +from app.api import setting +from app.config import config_manager +from app.core import Config, download_diagnostics, downloads +from app.core.download_diagnostics import describe_package, safe_origin +from app.models.config import GlobalConfig +from tests.config_support import activate_config + + +def test_signed_urls_are_reduced_to_origin(): + assert ( + safe_origin( + "https://person:secret@example.com/updates/file.zip?cdk=secret&token=123" + ) + == "https://example.com" + ) + assert safe_origin("invalid") == "(hidden)" + assert ( + safe_origin("https://[2001:db8::1]:8443/update.zip?token=private") + == "https://[2001:db8::1]" + ) + + +def test_m7a_nested_root_and_version_marker(tmp_path): + package = tmp_path / "m7a.zip" + with zipfile.ZipFile(package, "w") as archive: + archive.writestr("March7thAssistant/assets/config/version.txt", "v2026.11.17") + archive.writestr("release-notes.txt", "not secret") + data = describe_package(package) + assert data["format"] == "zip" + assert data["root_count"] == 2 + assert data["known_roots"] == ["March7thAssistant"] + assert data["version_markers"] == [ + {"name": "version.txt", "version": "v2026.11.17"} + ] + assert "release-notes.txt" not in str(data) + + +def test_opaque_executable_does_not_claim_invalid_zip(tmp_path): + package = tmp_path / "setup.exe" + package.write_bytes(b"MZ" + b"0" * 20) + assert describe_package(package)["format"] == "opaque" + + +def test_invalid_zip_signature_is_reported_without_extraction(tmp_path): + package = tmp_path / "broken.zip" + package.write_bytes(b"PK" + b"broken") + assert describe_package(package)["format"] == "zip-invalid" + + +def test_large_zip_directory_is_skipped_before_parsing(tmp_path, monkeypatch): + package = tmp_path / "large-directory.zip" + with zipfile.ZipFile(package, "w") as archive: + entry = zipfile.ZipInfo("version.txt") + entry.comment = b"x" * 2000 + archive.writestr(entry, "v1.2.3") + + def forbid_parsing(*args, **kwargs): + pytest.fail("ZIP diagnostics parsed a directory over its byte budget") + + # Use a small budget so the test exercises the same limit without a large fixture. + monkeypatch.setattr( + download_diagnostics, "_MAX_ZIP_INSPECTION_BYTES", 1024, raising=False + ) + monkeypatch.setattr(zipfile.ZipInfo, "__init__", forbid_parsing) + assert describe_package(package) == { + "schema": 1, + "format": "zip", + "bytes": package.stat().st_size, + } + + +def test_unrecognized_version_markers_count_towards_read_limit(tmp_path, monkeypatch): + package = tmp_path / "many-markers.zip" + with zipfile.ZipFile(package, "w") as archive: + for index in range(7): + archive.writestr(f"{index}/version.txt", "unknown") + archive.writestr("last/version.txt", "v1.2.3") + + opened = [] + open_entry = zipfile.ZipFile.open + + def record_open(archive, entry, *args, **kwargs): + opened.append(entry.filename) + return open_entry(archive, entry, *args, **kwargs) + + monkeypatch.setattr(zipfile.ZipFile, "open", record_open) + assert describe_package(package) == { + "schema": 1, + "format": "zip", + "bytes": package.stat().st_size, + } + assert opened == [f"{index}/version.txt" for index in range(6)] + + +@pytest.mark.asyncio +async def test_same_destination_retry_preserves_both_export_records( + tmp_path, monkeypatch, isolated_app_paths +): + monkeypatch.setattr(Config, "setting", await activate_config(GlobalConfig.build())) + monkeypatch.setattr( + downloads._utils_fluxdown_cli, + "_server_data_dir", + lambda _: tmp_path / "fluxdown", + ) + url = "https://example.test/private/package.zip?token=secret" + destination = tmp_path / "package.part" + + async def fail(*args, **kwargs): + request = httpx.Request("GET", url) + raise httpx.HTTPStatusError( + f"download failed: {url}", + request=request, + response=httpx.Response(403, request=request), + ) + + async def succeed(url, destination, **kwargs): + with zipfile.ZipFile(destination, "w") as archive: + archive.writestr("March7thAssistant/version.txt", "v1.2.3") + return destination.stat().st_size + + with pytest.raises(httpx.HTTPStatusError): + await downloads.download_file( + url, destination, timeout=3, downloader="builtin", http_download=fail + ) + size = await downloads.download_file( + url, destination, timeout=3, downloader="builtin", http_download=succeed + ) + + app = FastAPI() + app.include_router(setting.router) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://test" + ) as client: + response = await client.post("/api/setting/get") + assert response.status_code == 200 + history = response.json()["data"]["Update"]["LastUpdateHistory"] + failed, succeeded = history + assert (failed["status"], failed["error"], failed["size"]) == ( + "failed", + "HTTPStatusError", + 0, + ) + assert failed["diagnostic"]["availability"] == "download_failed" + assert failed["diagnostic"]["http_status"] == 403 + assert (succeeded["status"], succeeded["error"], succeeded["size"]) == ( + "success", + None, + size, + ) + assert succeeded["diagnostic"]["version_markers"] == [ + {"name": "version.txt", "version": "v1.2.3"} + ] + for item in history: + assert item["diagnostic"]["downloader"] == "httpx" + assert item["url"] == "https://example.test" + assert item["destination"] == str(destination) + assert "token=secret" not in json.dumps(item) + + +@pytest.mark.asyncio +async def test_fluxdown_package_summary_is_on_its_terminal_record( + tmp_path, monkeypatch, isolated_app_paths +): + config = await activate_config(GlobalConfig.build()) + monkeypatch.setattr(Config, "setting", config) + monkeypatch.setattr( + downloads._utils_fluxdown_cli, + "_server_data_dir", + lambda _: tmp_path / "fluxdown", + ) + await config.update( + GlobalConfig.model_validate({"Update": {"FluxdownServerMode": False}}), + check_visibility=False, + ) + monkeypatch.setattr( + downloads._utils_fluxdown_cli, + "fluxdown_find_cli", + lambda *_, **__: tmp_path / "fluxdown-cli", + ) + + async def fluxdown(url, destination, **kwargs): + destination.write_bytes(b"MZ package") + size = destination.stat().st_size + return size, downloads._utils_fluxdown_cli.FluxdownDownloadRecord( + url=url, + destination=str(destination), + size=size, + duration_ms=31, + segments=4, + status="success", + ) + + monkeypatch.setattr(downloads._utils_fluxdown_cli, "fluxdown_download", fluxdown) + size = await downloads.download_file( + "https://example.test/package?token=secret", + tmp_path / "package", + timeout=3, + downloader="fluxdown", + ) + (record,) = config.Update.LastUpdateHistory + assert (record.status, record.size, record.duration_ms, record.segments) == ( + "success", + size, + 31, + 4, + ) + assert record.url == "https://example.test" + assert record.diagnostic["downloader"] == "FluxDown" + assert record.diagnostic["format"] == "opaque" + + +@pytest.mark.asyncio +async def test_cancel_waiting_for_history_preserves_unconfirmed_writer( + tmp_path, monkeypatch, isolated_app_paths +): + config = await activate_config(GlobalConfig.build()) + monkeypatch.setattr(Config, "setting", config) + cli = downloads._utils_fluxdown_cli + monkeypatch.setattr(cli, "_server_data_dir", lambda _: tmp_path / "fluxdown") + monkeypatch.setattr( + cli, "fluxdown_server_task_safe_to_overwrite", lambda *_, **__: False + ) + monkeypatch.setattr(cli, "fluxdown_server_mark_failure", lambda *_: 1) + history_started = asyncio.Event() + write_history = downloads._write_history + + async def observe_history(record): + history_started.set() + await write_history(record) + + monkeypatch.setattr(downloads, "_write_history", observe_history) + async with config_manager.execution_gate(): + task = asyncio.create_task( + downloads.download_file( + "https://example.test/package", + tmp_path / "package", + timeout=3, + downloader="builtin", + ) + ) + try: + await asyncio.wait_for(history_started.wait(), timeout=2) + finally: + task.cancel() + with pytest.raises(cli.FluxdownCancelUnconfirmed): + await asyncio.wait_for(task, timeout=2) + assert not config.Update.LastUpdateHistory