160 lines
6.8 KiB
Python
160 lines
6.8 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
|
|
|
|
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 identity():
|
|
names = {name for name in tracked_paths() if pathlib.PurePosixPath(name).name == 'Cargo.toml'}
|
|
names.update(('Cargo.lock', 'rust-toolchain.toml', '.cargo/config.toml',
|
|
'.gitea/android-ci-tools.json', '.gitea/setup-android-ci.sh',
|
|
'.gitea/build-android-variant.sh', '.gitea/android-rustc-low-memory.sh',
|
|
'.gitea/android-application-cache.py', 'xtask/src/build_native.rs',
|
|
'xtask/src/deps.rs', '.gitea/prepare-android-dependency-cache.py'))
|
|
policy = json.loads((ROOT / 'native/native-deps.lock.json').read_text())
|
|
policy.pop('builds', None)
|
|
inputs = {name: digest(ROOT / name) for name in sorted(names)}
|
|
inputs['dependency-policy'] = policy
|
|
inputs['target'] = os.environ['TARGET']
|
|
inputs['low-memory'] = os.environ['TEAMSPEACH_ANDROID_LOW_MEMORY']
|
|
inputs['profile'] = 'release'
|
|
inputs['variant'] = 'harness'
|
|
for name in ('RUSTFLAGS', 'CARGO_ENCODED_RUSTFLAGS', 'RUSTC_WRAPPER', 'RUSTC_WORKSPACE_WRAPPER'):
|
|
inputs[name] = os.environ.get(name, '')
|
|
fingerprint = hashlib.sha256(json.dumps(inputs, sort_keys=True).encode()).hexdigest()
|
|
mode = 'low-memory' if inputs['low-memory'] == 'true' else 'normal'
|
|
return f"android-application-linux-x64-{inputs['target']}-release-{mode}-harness-v1-{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():
|
|
if not RECEIPT.exists():
|
|
return {'inputs': {}, 'completed_ns': 0}
|
|
data = json.loads(RECEIPT.read_text())
|
|
if data['schema'] != 1 or data['identity'] != identity() or data['workspace'] != str(ROOT):
|
|
raise ValueError('Application cache input identity/workspace mismatch')
|
|
return data
|
|
|
|
|
|
def save(path, inputs):
|
|
STATE.mkdir(exist_ok=True)
|
|
temporary = path.with_suffix('.tmp')
|
|
temporary.write_text(json.dumps({'schema': 1, 'identity': identity(),
|
|
'workspace': str(ROOT), 'inputs': inputs,
|
|
'completed_ns': time.time_ns()}, 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
|
|
if action == 'key':
|
|
with open(os.environ['GITHUB_OUTPUT'], 'a') as out:
|
|
out.write(f'key={identity()}\n')
|
|
return
|
|
previous = load()
|
|
if action == 'sources':
|
|
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)
|
|
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 = json.loads(PENDING.read_text())['inputs']
|
|
pending.update(current)
|
|
save(PENDING, pending)
|
|
else:
|
|
pending = json.loads(PENDING.read_text())['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)
|
|
print(f'Recorded {len(stable)} stable application/dependency inputs', flush=True)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|