Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
3e46946
feat(download): add safe bounded package diagnostic inspector
youngslin Nov 16, 2026
b0f705f
feat(download): retain bounded diagnostics in downloadable history
youngslin Nov 16, 2026
0f25e15
feat(download): retain bounded diagnostics in downloadable history
youngslin Nov 16, 2026
19ac145
feat(download): capture package evidence for every common download
youngslin Nov 16, 2026
a89f839
feat(download): report known release root directory names without exp…
youngslin Nov 16, 2026
9d793bd
feat(download): expose central package diagnostics in history export
youngslin Nov 16, 2026
b65854f
feat(download): expose typed diagnostic history field
youngslin Nov 16, 2026
7ef9560
test(download): verify privacy-safe root/marker inspection
youngslin Nov 16, 2026
03297ac
style(download): format diagnostic implementation and tests
youngslin Nov 16, 2026
112db0d
style(download): format diagnostic implementation and tests
youngslin Nov 16, 2026
8bd43aa
style(download): format diagnostic implementation and tests
youngslin Nov 16, 2026
e9965dc
style(download): format diagnostic implementation and tests
youngslin Nov 16, 2026
bd4b635
docs(changelog): announce download diagnostics
youngslin Nov 16, 2026
7310991
fix(download): format diagnostic history export visibility condition
youngslin Nov 16, 2026
1699484
fix(download): enrich terminal history instead of duplicating entries…
youngslin Nov 16, 2026
c12204e
fix(download): preserve every unconfirmed FluxDown cancellation subtype
youngslin Nov 16, 2026
45cc3e9
style(download): follow Ruff formatting for history upsert
youngslin Nov 16, 2026
0ca1fc4
fix(download): 按实际尝试记录下载包诊断
youngslin Nov 23, 2026
7f9d5b5
fix(download): 限制 ZIP 诊断读取并精简历史导出
youngslin Nov 23, 2026
be9ed68
fix(download): 保留可分享的失败信息和 IPv6 下载源
youngslin Nov 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
140 changes: 140 additions & 0 deletions app/core/download_diagnostics.py
Original file line number Diff line number Diff line change
@@ -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
158 changes: 123 additions & 35 deletions app/core/downloads.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]]

Expand Down Expand Up @@ -104,6 +112,68 @@
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

Expand All @@ -117,50 +187,68 @@
finally:
download_method.reset(token)

progress = report

Check warning on line 190 in app/core/downloads.py

View workflow job for this annotation

GitHub Actions / 检查是否删掉了他人近期合入的代码

可能回退了 a617ddd11 的改动

这里删掉了 a617ddd11(DLmaster,2026-11-17 05:34 UTC 合入)加入的 6 行(原第 122、126、128、136、142、162 行)。如果不是有意修改,多半是同步分支时带回了旧版本的文件。
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
Expand Down
3 changes: 3 additions & 0 deletions app/models/config/setting.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 2 additions & 0 deletions app/utils/common/fluxdown_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand All @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions changelog.d/common-download-diagnostics.feat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
project: update
新增统一下载包诊断记录,便于排查更新包结构异常
4 changes: 4 additions & 0 deletions frontend/src/api/models/FluxdownRecord.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ export type FluxdownRecord = {
* 校验信息
*/
checksum?: (string | null);
/**
* 统一下载诊断摘要(不包含凭据和原始压缩包)
*/
diagnostic?: (Record<string, any> | null);
/**
* 状态:success、failed、checksum_fail、fluxdown_fallback
*/
Expand Down
Loading