Files
cutdex/tool/windows/native_cache.py
T
lingjhf 0ecf920669
Gitea CI / Check code and tests (push) Successful in 6m26s
Gitea CI / Build Windows x64 app (push) Successful in 3m23s
Gitea CI / Build Android APK (push) Successful in 4m14s
Gitea CI / Audit and package Windows x64 (push) Successful in 1m24s
Gitea CI / Assemble and validate CI artifacts (push) Successful in 49s
Gitea CI / Gitea CI passed (push) Successful in 2s
perf(ci): 缓存已校验的 Velopack 原生依赖 (#10)
2026-10-06 16:43:14 +00:00

154 lines
5.8 KiB
Python

"""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))