diff --git a/.gitea/CI_PERFORMANCE.md b/.gitea/CI_PERFORMANCE.md index 4b5732e..6c92ead 100644 --- a/.gitea/CI_PERFORMANCE.md +++ b/.gitea/CI_PERFORMANCE.md @@ -30,6 +30,18 @@ enabled for CI. Do not clear these caches between runs. Each job must have its o checkout; do not share a Flutter `build/` or `.dart_tool/` directory between jobs. With an ephemeral runner, these user directories must be persisted separately. +The Windows compilation job runs `tool/windows/native_cache.py` after locked Pub +resolution. It reads the Velopack version and SHA256 from the resolved deskup +package and persists its ZIP in `%LOCALAPPDATA%/Cutdex/ci-tools/native/`, keyed by +both values. Every reuse verifies the digest; corrupt files are replaced only +after a verified download. OS file locks coordinate concurrent jobs, and atomic +replacement prevents interrupted downloads from becoming cache hits. Temporary +network failures retry at most three times. `DESKUP_VELOPACK_ARCHIVE` points CMake +at the verified local ZIP, where the SDK performs its own hash check again. +An explicitly supplied offline archive is validated and can populate this cache. +Version or hash changes use a separate file; no checkout-local `_deps` directory +is shared. Persist this user cache too when using ephemeral runners. + The local `prepare-flutter` action owns cache setup, Flutter version validation, optional Java configuration and locked dependency resolution for the quality, Android and Windows compilation jobs. `.fvmrc` is the shared local/CI Flutter diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 9d59f1d..3edd9bb 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -109,6 +109,10 @@ jobs: github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} - name: Prepare Flutter environment uses: ./.gitea/actions/prepare-flutter + - name: Reuse verified Velopack native archive + run: | + python tool/windows/native_cache.py + if ($LASTEXITCODE -ne 0) { throw 'Windows native archive cache preparation failed.' } - name: Build production Windows app run: | Remove-Item Env:CUTDEX_WINDOWS_PATH, Env:CUTDEX_WINDOWS_PACKAGE_PATH -ErrorAction SilentlyContinue diff --git a/docs/windows-updates.md b/docs/windows-updates.md index edb236d..d259e9f 100644 --- a/docs/windows-updates.md +++ b/docs/windows-updates.md @@ -68,6 +68,10 @@ python tool/build.py windows --flavor development -- ` Gitea 开发仓库使用 `CUTDEX_WINDOWS_UPDATE_SOURCE=gitea` 和仓库 URL。 仅设置进程环境变量不会配置 Dart 更新源。正式版忽略开发 defines。 原生 SDK 离线缓存仍通过 `DESKUP_VELOPACK_ARCHIVE` 环境变量指定。 +CI 会按已解析 deskup 的版本和 SHA256,将原生 ZIP 缓存到 +`%LOCALAPPDATA%/Cutdex/ci-tools/native/`,后续构建校验后直接复用。 +本地可运行 `python tool/windows/native_cache.py` 预热同一缓存;命令会输出 +可供 `DESKUP_VELOPACK_ARCHIVE` 使用的文件路径。 ```powershell python -m unittest discover -s tool/gitea -p 'test_*.py' diff --git a/tool/windows/native_cache.py b/tool/windows/native_cache.py new file mode 100644 index 0000000..9559357 --- /dev/null +++ b/tool/windows/native_cache.py @@ -0,0 +1,153 @@ +"""Persist the resolved deskup Velopack archive outside CI checkouts.""" +import argparse +from contextlib import contextmanager +from dataclasses import dataclass +from http.client import IncompleteRead +import os +from pathlib import Path +import re +import shutil +import sys +import tempfile +import time +from urllib.error import HTTPError, URLError +from urllib.request import urlopen + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from common.files import file_sha256 +from common.process import cli +from windows_updates import resolved_deskup + + +@dataclass(frozen=True) +class Archive: + version: str + sha256: str + + @property + def name(self): + return f'velopack-{self.version}-{self.sha256}.zip' + + @property + def url(self): + return (f'https://github.com/velopack/velopack/releases/download/{self.version}/' + f'velopack_libc_{self.version}.zip') + + +def resolved_archive(package=None): + package = resolved_deskup() if package is None else Path(package) + source = (package / 'windows/velopack.cmake').read_text(encoding='utf-8') + version = re.search(r'set\(DESKUP_VELOPACK_VERSION\s+"(\d+\.\d+\.\d+)"\)', source) + digest = re.search(r'URL_HASH\s+SHA256=([0-9a-fA-F]{64})(?=\s|\))', source) + if not version or not digest or 'ENV{DESKUP_VELOPACK_ARCHIVE}' not in source: + raise ValueError('Resolved deskup must pin its Velopack version/SHA256 and support a local archive.') + return Archive(version[1], digest[1].lower()) + + +def default_cache_directory(environment): + base = Path(environment['LOCALAPPDATA']) if environment.get('LOCALAPPDATA') else Path.home() / '.cache' + return base / 'Cutdex/ci-tools/native' + + +@contextmanager +def archive_lock(path, timeout=1800): + # OS locks release even when a runner is cancelled; keep the lock file. + with path.open('a+b') as stream: + if stream.tell() == 0: + stream.write(b'0') + stream.flush() + if os.name == 'nt': + import msvcrt + def lock(): + stream.seek(0) + msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1) + def unlock(): + stream.seek(0) + msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1) + else: + import fcntl + def lock(): + fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB) + def unlock(): + fcntl.flock(stream, fcntl.LOCK_UN) + deadline = time.monotonic() + timeout + while True: + try: + lock() + break + except OSError: + if time.monotonic() >= deadline: + raise RuntimeError('Timed out waiting for the native archive cache lock.') from None + time.sleep(0.2) + try: + yield + finally: + unlock() + + +def download_archive(url, destination): + for attempt in range(3): + try: + with urlopen(url, timeout=60) as response, destination.open('wb') as stream: + shutil.copyfileobj(response, stream, length=1024 * 1024) + return + except (URLError, TimeoutError, ConnectionError, IncompleteRead) as error: + if (isinstance(error, HTTPError) and error.code not in {408, 429} and error.code < 500) or attempt == 2: + raise RuntimeError('Native archive download failed after bounded network retries.') from None + print('Native archive download interrupted; retrying.', flush=True) + time.sleep(2 ** attempt) + + +def verified(path, archive): + return path.is_file() and file_sha256(path) == archive.sha256 + + +def ensure_archive(archive, directory, source=None): + directory = Path(directory).resolve() + directory.mkdir(parents=True, exist_ok=True) + destination = directory / archive.name + source = Path(source).resolve() if source else None + if source and not verified(source, archive): + raise ValueError('DESKUP_VELOPACK_ARCHIVE does not match the resolved SDK SHA256.') + with archive_lock(destination.with_suffix('.lock')): + if verified(destination, archive): + print(f'Native archive cache hit: Velopack {archive.version}', flush=True) + return destination + print(f'Native archive cache miss: Velopack {archive.version}', flush=True) + with tempfile.NamedTemporaryFile(dir=directory, prefix=archive.name + '.', suffix='.part', delete=False) as stream: + temporary = Path(stream.name) + try: + if source: + shutil.copyfile(source, temporary) + else: + download_archive(archive.url, temporary) + if not verified(temporary, archive): + raise ValueError('Downloaded native archive SHA256 differs from the resolved SDK.') + temporary.replace(destination) + finally: + temporary.unlink(missing_ok=True) + return destination + + +def prepare(directory=None, environment=None): + environment = os.environ if environment is None else environment + archive = ensure_archive(resolved_archive(), directory or default_cache_directory(environment), + source=environment.get('DESKUP_VELOPACK_ARCHIVE')) + value = archive.as_posix() + if '\n' in value or '\r' in value: + raise ValueError('Native archive cache paths must not contain newlines.') + if environment.get('GITHUB_ENV'): + with Path(environment['GITHUB_ENV']).open('a', encoding='utf-8') as stream: + stream.write(f'DESKUP_VELOPACK_ARCHIVE={value}\n') + print(f'Native archive ready: {value}', flush=True) + return archive + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--cache-directory', type=Path, help='Override the persistent runner-user cache directory.') + prepare(parser.parse_args().cache_directory) + + +if __name__ == '__main__': + sys.exit(cli(main)) diff --git a/tool/windows/test_native_cache_unit.py b/tool/windows/test_native_cache_unit.py new file mode 100644 index 0000000..523f669 --- /dev/null +++ b/tool/windows/test_native_cache_unit.py @@ -0,0 +1,213 @@ +from concurrent.futures import ThreadPoolExecutor +import hashlib +import io +from pathlib import Path +import tempfile +import threading +import subprocess +import sys +import time +import unittest +from unittest.mock import patch +from urllib.error import HTTPError, URLError + +import native_cache as cache + + +class NativeCacheTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.payload = b'Velopack archive bytes' + self.archive = cache.Archive('1.2.161', hashlib.sha256(self.payload).hexdigest()) + + def download(self, url, destination): + self.assertEqual(url, self.archive.url) + destination.write_bytes(self.payload) + + def test_cold_fill_and_warm_hit_do_not_repeat_download(self): + with patch.object(cache, 'download_archive', side_effect=self.download) as download: + path = cache.ensure_archive(self.archive, self.root) + self.assertEqual(cache.ensure_archive(self.archive, self.root), path) + self.assertEqual(download.call_count, 1) + self.assertEqual(path.read_bytes(), self.payload) + self.assertFalse(list(self.root.glob('*.part'))) + + def test_every_hit_is_checked_and_tampered_bytes_are_replaced(self): + with patch.object(cache, 'download_archive', side_effect=self.download) as download: + path = cache.ensure_archive(self.archive, self.root) + path.write_bytes(b'corrupt') + cache.ensure_archive(self.archive, self.root) + self.assertEqual(download.call_count, 2) + self.assertEqual(path.read_bytes(), self.payload) + + def test_failed_integrity_check_never_publishes_or_removes_existing_file(self): + destination = self.root / self.archive.name + destination.write_bytes(b'old corrupt file') + def invalid_download(url, temporary): + temporary.write_bytes(b'wrong payload') + self.assertEqual(destination.read_bytes(), b'old corrupt file') + with patch.object(cache, 'download_archive', side_effect=invalid_download): + with self.assertRaisesRegex(ValueError, 'SHA256 differs'): + cache.ensure_archive(self.archive, self.root) + self.assertEqual(destination.read_bytes(), b'old corrupt file') + self.assertFalse(list(self.root.glob('*.part'))) + + def test_download_failure_cleans_its_partial_file(self): + def failed_download(url, temporary): + temporary.write_bytes(b'partial') + raise RuntimeError('network failure') + with patch.object(cache, 'download_archive', side_effect=failed_download): + with self.assertRaisesRegex(RuntimeError, 'network failure'): + cache.ensure_archive(self.archive, self.root) + self.assertFalse((self.root / self.archive.name).exists()) + self.assertFalse(list(self.root.glob('*.part'))) + + def test_cancelled_run_partial_files_cannot_be_cache_hits(self): + stale = self.root / (self.archive.name + '.cancelled.part') + stale.write_bytes(b'incomplete') + with patch.object(cache, 'download_archive', side_effect=self.download) as download: + cache.ensure_archive(self.archive, self.root) + download.assert_called_once() + self.assertEqual(stale.read_bytes(), b'incomplete') + + def test_version_and_digest_both_isolate_cache_entries(self): + upgraded = cache.Archive('1.2.162', self.archive.sha256) + republished = cache.Archive('1.2.161', 'a' * 64) + self.assertEqual(len({self.archive.name, upgraded.name, republished.name}), 3) + + def test_parallel_fills_share_one_verified_download(self): + entered, release = threading.Event(), threading.Event() + def slow_download(url, temporary): + entered.set() + if not release.wait(5): + raise RuntimeError('test download was not released') + self.download(url, temporary) + with patch.object(cache, 'download_archive', side_effect=slow_download) as download: + with ThreadPoolExecutor(max_workers=2) as workers: + first = workers.submit(cache.ensure_archive, self.archive, self.root) + self.assertTrue(entered.wait(5)) + second = workers.submit(cache.ensure_archive, self.archive, self.root) + release.set() + self.assertEqual(first.result(timeout=5), second.result(timeout=5)) + self.assertEqual(download.call_count, 1) + + def test_lock_timeout_and_exception_release(self): + lock = self.root / 'archive.lock' + with cache.archive_lock(lock): + with self.assertRaisesRegex(RuntimeError, 'cache lock'): + with cache.archive_lock(lock, timeout=0): + self.fail('acquired an already held lock') + with self.assertRaisesRegex(ValueError, 'abort'): + with cache.archive_lock(lock): + raise ValueError('abort') + with cache.archive_lock(lock, timeout=0): + pass + + def test_offline_archive_is_verified_and_populates_persistent_cache(self): + source = self.root / 'offline.zip' + source.write_bytes(self.payload) + with patch.object(cache, 'download_archive') as download: + result = cache.ensure_archive(self.archive, self.root / 'persistent', source) + download.assert_not_called() + self.assertNotEqual(result, source) + self.assertEqual(result.read_bytes(), self.payload) + + def test_cancelled_process_releases_the_cache_lock(self): + lock, marker = self.root / 'archive.lock', self.root / 'locked' + program = ('import native_cache, sys; from pathlib import Path; ' + '\nwith native_cache.archive_lock(Path(sys.argv[1])):' + '\n Path(sys.argv[2]).write_text("locked")' + '\n sys.stdin.read()') + process = subprocess.Popen([sys.executable, '-c', program, str(lock), str(marker)], + cwd=Path(__file__).parent, stdin=subprocess.PIPE, + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + try: + deadline = time.monotonic() + 5 + while not marker.exists() and process.poll() is None and time.monotonic() < deadline: + time.sleep(0.01) + self.assertTrue(marker.exists(), 'test process failed to acquire its lock') + process.terminate() + process.wait(timeout=5) + with cache.archive_lock(lock, timeout=0): + pass + finally: + if process.poll() is None: + process.terminate() + process.communicate(timeout=5) + + def test_bad_explicit_archive_cannot_be_hidden_by_a_good_cache_hit(self): + (self.root / self.archive.name).write_bytes(self.payload) + source = self.root / 'bad.zip' + source.write_bytes(b'bad') + with patch.object(cache, 'download_archive') as download: + with self.assertRaisesRegex(ValueError, 'DESKUP_VELOPACK_ARCHIVE'): + cache.ensure_archive(self.archive, self.root, source) + download.assert_not_called() + + def test_manifest_is_read_from_resolved_sdk_without_a_second_version_pin(self): + windows = self.root / 'windows' + windows.mkdir() + manifest = windows / 'velopack.cmake' + manifest.write_text('set(DESKUP_VELOPACK_VERSION "1.2.162")\n' + f'URL_HASH SHA256={self.archive.sha256.upper()}\n' + 'file(TO_CMAKE_PATH "$ENV{DESKUP_VELOPACK_ARCHIVE}" local)\n') + self.assertEqual(cache.resolved_archive(self.root), cache.Archive('1.2.162', self.archive.sha256)) + for text in ('set(DESKUP_VELOPACK_VERSION "../unsafe")', 'URL_HASH SHA256=bad', ''): + manifest.write_text(text) + with self.assertRaisesRegex(ValueError, 'must pin'): + cache.resolved_archive(self.root) + + def test_temporary_network_errors_retry_with_a_fresh_download_file(self): + destination = self.root / 'download.part' + destination.write_bytes(b'previous attempt') + with patch.object(cache, 'urlopen', side_effect=[URLError('temporary'), io.BytesIO(self.payload)]) as request: + with patch.object(cache.time, 'sleep'): + cache.download_archive(self.archive.url, destination) + self.assertEqual(request.call_count, 2) + self.assertEqual(destination.read_bytes(), self.payload) + + def test_network_retries_are_bounded_and_permanent_errors_fail_immediately(self): + for error, count in [(URLError('unavailable'), 3), + (HTTPError(self.archive.url, 404, 'missing', {}, None), 1), + (HTTPError(self.archive.url, 503, 'busy', {}, None), 3)]: + with self.subTest(count=count): + with patch.object(cache, 'urlopen', side_effect=error) as request: + with patch.object(cache.time, 'sleep'), self.assertRaises(RuntimeError): + cache.download_archive(self.archive.url, self.root / 'download.part') + self.assertEqual(request.call_count, count) + + def test_interrupted_response_is_retried_without_preserving_partial_bytes(self): + class Interrupted(io.BytesIO): + def read(self, size=-1): + if self.tell(): + raise TimeoutError('interrupted response') + return super().read(size) + destination = self.root / 'download.part' + with patch.object(cache, 'urlopen', side_effect=[Interrupted(b'partial'), io.BytesIO(self.payload)]): + with patch.object(cache.time, 'sleep'): + cache.download_archive(self.archive.url, destination) + self.assertEqual(destination.read_bytes(), self.payload) + + def test_exports_only_a_verified_archive_for_subsequent_ci_steps(self): + output = self.root / 'github-env' + output.write_text('EXISTING=value\n') + environment = {'GITHUB_ENV': str(output), 'LOCALAPPDATA': str(self.root)} + with patch.object(cache, 'resolved_archive', return_value=self.archive): + with patch.object(cache, 'download_archive', side_effect=self.download): + archive = cache.prepare(environment=environment) + self.assertEqual(output.read_text(), f'EXISTING=value\nDESKUP_VELOPACK_ARCHIVE={archive.as_posix()}\n') + self.assertEqual(archive.parent, self.root / 'Cutdex/ci-tools/native') + + def test_failed_verification_cannot_export_an_archive(self): + output = self.root / 'github-env' + with patch.object(cache, 'resolved_archive', return_value=self.archive): + with patch.object(cache, 'download_archive', side_effect=lambda url, path: path.write_bytes(b'wrong')): + with self.assertRaises(ValueError): + cache.prepare(self.root, {'GITHUB_ENV': str(output)}) + self.assertFalse(output.exists()) + + +if __name__ == '__main__': + unittest.main()