From ab37165baf2c323f668a68c2fd87af1171032f4a Mon Sep 17 00:00:00 2001 From: Your Name Date: Sun, 28 Jun 2026 22:16:12 +0800 Subject: [PATCH] Improve delta update failure logging --- CHANGELOG.md | 1 + douyin/core/version.py | 2 +- douyin/updater/force_update.py | 94 +++++++++++++++++++++++++++------- pyproject.toml | 2 +- tests/test_auto_update.py | 49 ++++++++++++++++++ 5 files changed, 128 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c61a0ad..26f820b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ ## [Unreleased] +## [V3.3.9] — 2026-06-28 ### Fixed - 自动更新差量包下载、校验或启动失败时自动回退完整安装包,避免旧版本反复卡在失败的 delta 更新上。 diff --git a/douyin/core/version.py b/douyin/core/version.py index d881be4..e65c9b4 100644 --- a/douyin/core/version.py +++ b/douyin/core/version.py @@ -10,7 +10,7 @@ from typing import Optional APP_NAME = "douyin_guaji" -APP_VERSION = "V3.3.8" +APP_VERSION = "V3.3.9" APP_BUILD_DATE = "2026-06-28" # 兼容旧代码与测试:提供 VERSION / RELEASE_DATE 别名 diff --git a/douyin/updater/force_update.py b/douyin/updater/force_update.py index fe36ed8..b3e8f90 100644 --- a/douyin/updater/force_update.py +++ b/douyin/updater/force_update.py @@ -10,6 +10,7 @@ import subprocess import sys import zipfile from dataclasses import dataclass, replace +from datetime import datetime, timezone from pathlib import Path from typing import Any, Callable from urllib.parse import urljoin, urlparse @@ -507,6 +508,25 @@ def _delta_log_path(version: str) -> Path: return log_dir / f"delta-{safe_version}.log" +def _update_client_log_path() -> Path: + log_dir = Path(path_config.get_logs_dir()) / "updates" + log_dir.mkdir(parents=True, exist_ok=True) + return log_dir / "update-client.log" + + +def _append_update_log(event: str, **fields: Any) -> None: + try: + payload = { + "time": datetime.now(timezone.utc).isoformat(), + "event": event, + **fields, + } + with _update_client_log_path().open("a", encoding="utf-8") as f: + f.write(json.dumps(payload, ensure_ascii=False, default=str) + "\n") + except Exception: + pass + + def launch_delta_update(delta_path: Path, version: str) -> None: install_root = _install_root() work_dir = delta_path.parent / f"{delta_path.stem}.apply" @@ -520,22 +540,30 @@ def launch_delta_update(delta_path: Path, version: str) -> None: f"$work = {_ps_quote(str(work_dir))}; " f"$log = {_ps_quote(str(log_path))}; " "New-Item -ItemType Directory -Force -Path (Split-Path $log) | Out-Null; " - "if (Test-Path $work) { Remove-Item -LiteralPath $work -Recurse -Force }; " - "New-Item -ItemType Directory -Force -Path $work | Out-Null; " - "Expand-Archive -LiteralPath $zip -DestinationPath $work -Force; " - "$manifest = Get-Content -LiteralPath (Join-Path $work 'manifest.json') -Raw | ConvertFrom-Json; " - "foreach ($rel in $manifest.delete) { " - " $target = Join-Path $root $rel; " - " if (Test-Path -LiteralPath $target) { Remove-Item -LiteralPath $target -Recurse -Force } " - "}; " - "foreach ($file in $manifest.files) { " - " $src = Join-Path (Join-Path $work 'files') $file.path; " - " $dst = Join-Path $root $file.path; " - " New-Item -ItemType Directory -Force -Path (Split-Path $dst) | Out-Null; " - " Copy-Item -LiteralPath $src -Destination $dst -Force " - "}; " - "'delta update applied' | Out-File -LiteralPath $log -Encoding utf8 -Append; " - "Remove-Item -LiteralPath $work -Recurse -Force" + "try { " + " ('delta update started ' + (Get-Date -Format o) + ' zip=' + $zip + ' root=' + $root) | Out-File -LiteralPath $log -Encoding utf8 -Append; " + " if (Test-Path $work) { Remove-Item -LiteralPath $work -Recurse -Force }; " + " New-Item -ItemType Directory -Force -Path $work | Out-Null; " + " Expand-Archive -LiteralPath $zip -DestinationPath $work -Force; " + " $manifest = Get-Content -LiteralPath (Join-Path $work 'manifest.json') -Raw | ConvertFrom-Json; " + " foreach ($rel in $manifest.delete) { " + " $target = Join-Path $root $rel; " + " if (Test-Path -LiteralPath $target) { Remove-Item -LiteralPath $target -Recurse -Force } " + " }; " + " foreach ($file in $manifest.files) { " + " $src = Join-Path (Join-Path $work 'files') $file.path; " + " $dst = Join-Path $root $file.path; " + " New-Item -ItemType Directory -Force -Path (Split-Path $dst) | Out-Null; " + " Copy-Item -LiteralPath $src -Destination $dst -Force " + " }; " + " 'delta update applied' | Out-File -LiteralPath $log -Encoding utf8 -Append; " + " Remove-Item -LiteralPath $work -Recurse -Force; " + " exit 0 " + "} catch { " + " ('delta update failed ' + (Get-Date -Format o) + ' error=' + $_.Exception.Message) | Out-File -LiteralPath $log -Encoding utf8 -Append; " + " if ($_.ScriptStackTrace) { $_.ScriptStackTrace | Out-File -LiteralPath $log -Encoding utf8 -Append }; " + " exit 1 " + "}" ) subprocess.Popen( [ @@ -623,7 +651,15 @@ def perform_forced_update( ) delta = _matching_delta(manifest, current_version, latest_version) - if delta and not _should_skip_delta_after_previous_attempt(settings, delta, current_version, latest_version): + skip_delta = bool(delta and _should_skip_delta_after_previous_attempt(settings, delta, current_version, latest_version)) + if delta and skip_delta: + _append_update_log( + "delta_skip_after_previous_started_attempt", + current_version=current_version, + latest_version=latest_version, + delta_filename=delta.get("filename") or delta.get("url"), + ) + if delta and not skip_delta: raw_delta_url = str(delta.get("url") or "").strip() delta_sha = str(delta.get("sha256") or "").strip().lower() if raw_delta_url and (not settings.require_sha256 or re.fullmatch(r"[0-9a-fA-F]{64}", delta_sha)): @@ -633,6 +669,13 @@ def perform_forced_update( delta_name = _safe_delta_name(delta, delta_url, latest_version) delta_path = settings.download_dir / delta_name delta_path.parent.mkdir(parents=True, exist_ok=True) + _append_update_log( + "delta_download_start", + current_version=current_version, + latest_version=latest_version, + url=delta_url, + path=str(delta_path), + ) download_file(delta_url, delta_path, settings.timeout_seconds) if delta_sha: actual_sha = _sha256(delta_path) @@ -644,6 +687,13 @@ def perform_forced_update( raise UpdateError(f"差量包 sha256 校验失败: expected={delta_sha} actual={actual_sha}") validate_delta_package(delta_path, current_version=current_version, latest_version=latest_version) _mark_delta_attempt_started(settings, delta, current_version, latest_version, delta_path) + _append_update_log( + "delta_launch_start", + current_version=current_version, + latest_version=latest_version, + path=str(delta_path), + sha256=delta_sha, + ) launch_delta_update(delta_path, latest_version) return UpdateResult( "delta_update_started", @@ -652,7 +702,14 @@ def perform_forced_update( version=latest_version, delta_path=delta_path, ) - except Exception: + except Exception as exc: + _append_update_log( + "delta_failed_fallback_full", + current_version=current_version, + latest_version=latest_version, + delta_filename=delta.get("filename") or delta.get("url"), + error=f"{type(exc).__name__}: {exc}", + ) _write_delta_attempt_state( settings, { @@ -660,6 +717,7 @@ def perform_forced_update( "key": _delta_attempt_key(delta, current_version, latest_version), "from_version": current_version, "to_version": latest_version, + "error": f"{type(exc).__name__}: {exc}", }, ) diff --git a/pyproject.toml b/pyproject.toml index 575d47d..785c496 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,7 +3,7 @@ # 这里的 version 由 tools/dev/bump_version.py 与 version.py 同步维护。 # 注意:为兼容 PEP 440,这里去掉 "V" 前缀,仅保留数字部分(如 V3.3.3 → 3.3.3)。 name = "douyin_guaji" -version = "3.3.8" +version = "3.3.9" description = "基于 ADB + OCR + 像素检测 + 模板匹配的抖音直播间福袋自动挂机工具" readme = "README.md" requires-python = ">=3.10" diff --git a/tests/test_auto_update.py b/tests/test_auto_update.py index 3b1cd17..b094fdb 100644 --- a/tests/test_auto_update.py +++ b/tests/test_auto_update.py @@ -253,6 +253,55 @@ def test_forced_update_falls_back_to_full_installer_when_delta_download_fails(tm assert launched[0][0] == str(tmp_path / "DouyinGuaji-3.3.4-Setup.exe") +def test_forced_update_logs_delta_failure_before_full_fallback(tmp_path, monkeypatch): + from douyin.core import path_config + from douyin.updater.force_update import UpdateSettings, perform_forced_update + + full_payload = b"full installer" + full_sha = hashlib.sha256(full_payload).hexdigest() + logs_dir = tmp_path / "logs" + monkeypatch.setattr(path_config, "get_logs_dir", lambda: str(logs_dir)) + settings = UpdateSettings(enabled=True, manifest_url="https://example.test/update.json", download_dir=tmp_path) + + def fetch_manifest(url: str, timeout: float) -> dict: + return { + "version": "3.3.4", + "url": "https://example.test/DouyinGuaji-3.3.4-Setup.exe", + "filename": "DouyinGuaji-3.3.4-Setup.exe", + "sha256": full_sha, + "delta": { + "from_version": "3.3.3", + "to_version": "3.3.4", + "url": "https://example.test/DouyinGuaji-3.3.3_to_3.3.4_delta.zip", + "filename": "DouyinGuaji-3.3.3_to_3.3.4_delta.zip", + "sha256": "1" * 64, + }, + } + + def download(url: str, dest: Path, timeout: float) -> None: + if url.endswith("_delta.zip"): + raise OSError("network interrupted") + dest.write_bytes(full_payload) + + result = perform_forced_update( + settings, + current_version="3.3.3", + fetch_manifest=fetch_manifest, + download_file=download, + launch_installer=lambda cmd: None, + launch_delta_update=lambda path, version: pytest.fail("should not launch broken delta"), + ) + + log_path = logs_dir / "updates" / "update-client.log" + lines = [json.loads(line) for line in log_path.read_text(encoding="utf-8").splitlines()] + + assert result.status == "update_started" + assert any(item["event"] == "delta_download_start" for item in lines) + failed = [item for item in lines if item["event"] == "delta_failed_fallback_full"] + assert failed + assert "network interrupted" in failed[0]["error"] + + def test_forced_update_skips_delta_after_previous_started_attempt_still_old_version(tmp_path): from douyin.updater.force_update import UpdateSettings, perform_forced_update