223 lines
10 KiB
Python
223 lines
10 KiB
Python
#!/usr/bin/env python3
|
|
"""CI-only Cargo cache bookkeeping; never manufactures build/provenance receipts.
|
|
|
|
Cargo compares checkout source mtimes with cached dep-info/build-script timestamps.
|
|
A fresh checkout otherwise invalidates unchanged workspace and vendored crates.
|
|
Restore a recorded timestamp only for the same path, SHA-256, kind and mode; a
|
|
changed input keeps its real mtime. WebRTC is handled only AFTER xtask deps has
|
|
rebuilt/verified it, so identical republished headers/archives can retain their
|
|
original timestamps without trusting cached dependency provenance.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import stat
|
|
import subprocess
|
|
import time
|
|
import tomllib
|
|
|
|
ROOT = pathlib.Path.cwd().resolve()
|
|
STATE = ROOT / '.android-ci'
|
|
RECEIPT = STATE / 'application-cache-inputs.json'
|
|
PENDING = STATE / 'application-cache-pending.json'
|
|
|
|
|
|
def digest(path):
|
|
with path.open('rb') as source:
|
|
return hashlib.file_digest(source, 'sha256').hexdigest()
|
|
|
|
|
|
def tracked_paths():
|
|
return [os.fsdecode(name) for name in subprocess.check_output(
|
|
['git', 'ls-files', '-z']).split(b'\0') if name]
|
|
|
|
|
|
def compatibility():
|
|
# Content changes belong to Cargo's fingerprints and the input snapshot, not
|
|
# the restore prefix. Only configuration that changes the build contract is
|
|
# a compatibility boundary. In particular, dependency versions/features and
|
|
# source/dependency drivers are deliberately absent here.
|
|
target_dir = pathlib.Path(os.environ['CARGO_TARGET_DIR']).resolve()
|
|
if target_dir != STATE / 'cargo-target':
|
|
raise ValueError('Application cache requires the isolated .android-ci/cargo-target')
|
|
names = {'.gitea/android-ci-tools.json', 'rust-toolchain.toml',
|
|
'.gitea/setup-android-ci.sh', '.gitea/build-android-variant.sh',
|
|
'.gitea/android-rustc-low-memory.sh',
|
|
'platform/android/gradle/wrapper/gradle-wrapper.properties'}
|
|
profiles = {}
|
|
for name in tracked_paths():
|
|
path = pathlib.PurePosixPath(name)
|
|
if path.name in ('config', 'config.toml') and path.parent.name == '.cargo':
|
|
names.add(name)
|
|
if path.name == 'Cargo.toml':
|
|
profile = tomllib.loads((ROOT / name).read_text()).get('profile')
|
|
if profile:
|
|
profiles[name] = profile
|
|
environment = {
|
|
name: os.environ.get(name, '') for name in (
|
|
'TARGET', 'TEAMSPEACH_ANDROID_LOW_MEMORY', 'CARGO_TARGET_DIR',
|
|
'RUSTFLAGS', 'CARGO_ENCODED_RUSTFLAGS', 'RUSTC_WRAPPER',
|
|
'RUSTC_WORKSPACE_WRAPPER', 'RUSTUP_TOOLCHAIN', 'CARGO_HOME',
|
|
'RUSTUP_HOME', 'HOME', 'LLVM_HOME', 'LIBCLANG_PATH',
|
|
'ANDROID_SDK_ROOT', 'ANDROID_NDK_ROOT', 'ANDROID_API_LEVEL',
|
|
'SKIA_SOURCE_DIR', 'SKIA_GN_COMMAND', 'SKIA_NINJA_COMMAND',
|
|
'SKIA_FORCE_BUILD')}
|
|
environment.update({name: value for name, value in os.environ.items()
|
|
if name.startswith(('CARGO_PROFILE_', 'CARGO_TARGET_'))})
|
|
return {
|
|
'files': {name: digest(ROOT / name) for name in sorted(names)},
|
|
'profiles': profiles, 'environment': environment,
|
|
'rustc': subprocess.check_output(['rustc', '-vV'], text=True),
|
|
'cargo': subprocess.check_output(['cargo', '-V'], text=True),
|
|
'profile': 'release', 'variant': 'harness',
|
|
}
|
|
|
|
|
|
def identity(inputs):
|
|
fingerprint = hashlib.sha256(json.dumps(inputs, sort_keys=True).encode()).hexdigest()
|
|
environment = inputs['environment']
|
|
mode = 'low-memory' if environment['TEAMSPEACH_ANDROID_LOW_MEMORY'] == 'true' else 'normal'
|
|
return f"android-application-linux-x64-{environment['TARGET']}-release-{mode}-harness-v2-{fingerprint}"
|
|
|
|
|
|
def record(path):
|
|
info = path.lstat()
|
|
mode = stat.S_IMODE(info.st_mode)
|
|
if stat.S_ISREG(info.st_mode):
|
|
kind, value = 'file', digest(path)
|
|
elif stat.S_ISDIR(info.st_mode):
|
|
kind = 'directory'
|
|
value = hashlib.sha256(json.dumps(sorted(os.listdir(path))).encode()).hexdigest()
|
|
else:
|
|
# Never follow checkout/cache symlinks, including symlinked ancestors.
|
|
raise ValueError(f'Unsupported cache input: {path}')
|
|
return {'kind': kind, 'sha256': value, 'mode': mode, 'mtime_ns': info.st_mtime_ns}
|
|
|
|
|
|
def collect(names):
|
|
result = {}
|
|
for name in sorted(set(names)):
|
|
path = ROOT / name
|
|
if not path.exists():
|
|
continue
|
|
if not path.resolve().is_relative_to(ROOT) or any(parent.is_symlink() for parent in (path, *path.parents)):
|
|
raise ValueError(f'Unconfined cache input: {name}')
|
|
result[name] = record(path)
|
|
return result
|
|
|
|
|
|
def load(contract, path=RECEIPT):
|
|
if path == RECEIPT and not path.exists():
|
|
return {'inputs': {}, 'completed_ns': 0}
|
|
data = json.loads(path.read_text())
|
|
recorded = data.get('compatibility', {})
|
|
comparable = {**recorded, 'environment': dict(recorded.get('environment', {}))}
|
|
# Scheduling is not an artifact compatibility boundary. Accept the earlier
|
|
# explicit four-job receipt only after all actual tool/profile inputs match.
|
|
comparable['environment'].pop('CMAKE_BUILD_PARALLEL_LEVEL', None)
|
|
if (data['schema'] != 2 or comparable != contract
|
|
or data['identity'] != identity(recorded) or data['workspace'] != str(ROOT)):
|
|
# v1's opaque content identity cannot prove configuration compatibility
|
|
# after a manifest change. Start a new cache generation, never guess.
|
|
raise ValueError('Application cache compatibility/workspace mismatch (requires v2 receipt)')
|
|
return data
|
|
|
|
|
|
def cargo_timestamps():
|
|
# These are Cargo's real host/target build-start stamps, not target/ at the
|
|
# repository root (which contains the separately verified WebRTC tree).
|
|
target = STATE / 'cargo-target'
|
|
paths = [*target.glob('*/.fingerprint/*/invoked.timestamp'),
|
|
*target.glob('*/*/.fingerprint/*/invoked.timestamp')]
|
|
return {str(path.relative_to(ROOT)): path.stat().st_mtime_ns for path in paths}
|
|
|
|
|
|
def report_cargo_timestamps(previous):
|
|
current = cargo_timestamps()
|
|
recorded = previous.get('cargo_timestamps', {})
|
|
changed = sum(current.get(name) != stamp for name, stamp in recorded.items())
|
|
print(f'Cargo target: {STATE / "cargo-target"}; restored build-start stamps: '
|
|
f'{len(current)}; missing/retimed since snapshot: {changed}; '
|
|
f'cached completion ns: {previous["completed_ns"]}', flush=True)
|
|
if changed:
|
|
print('Cargo output timestamps changed during cache transport; Cargo may rebuild. '
|
|
'Build output timestamps are never rewritten.', flush=True)
|
|
|
|
|
|
def save(path, inputs, contract):
|
|
STATE.mkdir(exist_ok=True)
|
|
temporary = path.with_suffix('.tmp')
|
|
stamps = cargo_timestamps() if path == RECEIPT else {}
|
|
temporary.write_text(json.dumps({'schema': 2, 'identity': identity(contract),
|
|
'compatibility': contract,
|
|
'workspace': str(ROOT), 'inputs': inputs,
|
|
'completed_ns': time.time_ns(),
|
|
'cargo_timestamps': stamps}, sort_keys=True))
|
|
temporary.replace(path)
|
|
|
|
|
|
def restore(current, previous):
|
|
restored = 0
|
|
for name, item in current.items():
|
|
old = previous['inputs'].get(name)
|
|
if old is None or any(item[key] != old[key] for key in ('kind', 'sha256', 'mode')):
|
|
# Changed/new inputs must postdate the previous compilation. Reject
|
|
# clock regressions rather than making stale outputs appear fresh.
|
|
if previous['completed_ns'] and item['mtime_ns'] <= previous['completed_ns']:
|
|
raise ValueError(f'Changed input predates cached compilation: {name}; refuse stale Cargo reuse')
|
|
continue
|
|
if old['mtime_ns'] > item['mtime_ns']:
|
|
raise ValueError(f'Cached input timestamp is in the future: {name}')
|
|
path = ROOT / name
|
|
os.utime(path, ns=(path.stat().st_atime_ns, old['mtime_ns']), follow_symlinks=False)
|
|
item['mtime_ns'] = old['mtime_ns']
|
|
restored += 1
|
|
print(f'Restored {restored}/{len(current)} content-matched input timestamps', flush=True)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('action', choices=('key', 'sources', 'dependencies', 'snapshot'))
|
|
action = parser.parse_args().action
|
|
contract = compatibility()
|
|
if action == 'key':
|
|
with open(os.environ['GITHUB_OUTPUT'], 'a') as out:
|
|
out.write(f'key={identity(contract)}\n')
|
|
previous = {**contract, 'environment': {**contract['environment'], 'CMAKE_BUILD_PARALLEL_LEVEL': '4'}}
|
|
out.write(f'previous-parallelism-key={identity(previous)}\n')
|
|
return
|
|
previous = load(contract)
|
|
if action == 'sources':
|
|
report_cargo_timestamps(previous)
|
|
names = set(tracked_paths())
|
|
# Cargo's directory rerun rules also inspect directory mtimes. Preserve
|
|
# those only if their exact child-name inventory and mode still match.
|
|
for name in tuple(names):
|
|
names.update(str(parent) for parent in pathlib.Path(name).parents if parent != pathlib.Path('.'))
|
|
current = collect(names)
|
|
restore(current, previous)
|
|
save(PENDING, current, contract)
|
|
elif action == 'dependencies':
|
|
base = pathlib.Path('target/native-deps') / os.environ['TARGET'] / 'webrtc'
|
|
if not base.is_dir():
|
|
raise ValueError('Verified WebRTC artifact tree is missing')
|
|
current = collect([str(base), *(str(path) for path in base.rglob('*'))])
|
|
restore(current, previous)
|
|
pending = load(contract, PENDING)['inputs']
|
|
pending.update(current)
|
|
save(PENDING, pending, contract)
|
|
else:
|
|
pending = load(contract, PENDING)['inputs']
|
|
current = collect(pending)
|
|
# Only retain inputs whose bytes/mode/mtime stayed stable throughout the
|
|
# build. A generated or concurrently edited file is never backdated.
|
|
stable = {name: item for name, item in current.items() if item == pending[name]}
|
|
save(RECEIPT, stable, contract)
|
|
print(f'Recorded {len(stable)} stable application/dependency inputs', flush=True)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|