Cotton code
157 lines · 6.4 KB · PythonRaw
"""Shared, content-addressed packages: verified bytes are reused; cache misses are fetched."""import fcntlimport hashlibimport jsonimport osfrom pathlib import Pathimport shutilimport subprocessimport tempfileimport timeCHUNK_BYTES = 4 * 1024 * 1024MAX_BYTES = 512 * 1024 * 1024ATTEMPTS = 3DEADLINE_SECONDS = 600def verify(path, expected):    digest = hashlib.sha256()    with path.open('rb') as stream:        while chunk := stream.read(1024 * 1024):            digest.update(chunk)    actual = digest.hexdigest()    if actual != expected:        raise ValueError(f'SHA-256 mismatch for {path.name}: expected {expected}, got {actual}')    return actualdef cache_root(value=None):    return Path(value or os.environ.get('COTTON_DATASET_CACHE') or                str(Path.home() / '.cache/cottondb/datasets/packages')).expanduser().resolve()def asset_path(cache, kind, pin):    digest = pin.get('package_sha256', '')    if len(digest) != 64 or any(c not in '0123456789abcdef' for c in digest):        raise ValueError(f'{kind}.sqlite has no valid pinned package SHA-256')    return cache / digest / f'{kind}.sqlite'def preflight(cache, kinds, pins):    failures = []    missing = []    for kind in kinds:        asset = asset_path(cache, kind, pins[kind])        try:            verify(asset, pins[kind]['package_sha256'])        except FileNotFoundError:            missing.append(kind)        except (OSError, ValueError) as error:            failures.append(f'{kind}.sqlite sha256={pins[kind]["package_sha256"]} at {asset}: {error}')    if failures:        raise ValueError('step 0 datasets: ' + '; '.join(failures))    return missingdef publish(source, destination, digest):    destination.parent.mkdir(parents=True, exist_ok=True)    with tempfile.TemporaryDirectory(dir=destination.parent) as work:        staged = Path(work) / destination.name        shutil.copyfile(source, staged)        verify(staged, digest)        staged.chmod(0o444)        staged.replace(destination)def fetch_chunk(repo, url, chunk, start, end, timeout):    result = subprocess.run(['pnpm', '--silent', 'forge', 'api', 'GET', url,                             '--range', f'{start}-{end}', '--output', str(chunk)],                            cwd=repo, env={**os.environ, 'FORGE_REPO': 'decemberfm/cottondb'},                            text=True, stdout=subprocess.PIPE, check=True, timeout=timeout)    return json.loads(result.stdout)['total']def acquire(repo, url, destination, digest, fetch=fetch_chunk, deadline=DEADLINE_SECONDS):    # Complete chunks persist under the SHA namespace across process/cut retries.    part = destination.with_suffix('.sqlite.part')    chunk = destination.with_suffix('.sqlite.chunk')    expires = time.monotonic() + deadline    while True:        if part.exists():            try:                verify(part, digest)                part.chmod(0o444)                part.replace(destination)                return            except ValueError:                pass        start = part.stat().st_size if part.exists() else 0        if start >= MAX_BYTES:            raise ValueError(f'{destination.name}: partial package exceeds size bound')        last = None        for attempt in range(ATTEMPTS):            remaining = expires - time.monotonic()            if remaining <= 0:                raise TimeoutError(f'{destination.name}: preparation exceeded {deadline}s; resume {part}')            try:                total = fetch(repo, url, chunk, start, start + CHUNK_BYTES - 1, min(45, remaining))                size = chunk.stat().st_size                if not (0 < size <= CHUNK_BYTES and start + size <= total <= MAX_BYTES):                    raise ValueError('invalid asset range size')                with part.open('ab') as output, chunk.open('rb') as incoming:                    shutil.copyfileobj(incoming, output)                    output.flush()                    os.fsync(output.fileno())                print(f"{destination.name}: cached {start + size}/{total} bytes", flush=True)                if start + size == total:                    try:                        verify(part, digest)                    except ValueError:                        part.unlink()                        raise RuntimeError(f"{destination.name}: downloaded package SHA-256 mismatch")                    part.chmod(0o444)                    part.replace(destination)                    return                break            except (OSError, ValueError, subprocess.SubprocessError) as error:                last = error                if attempt + 1 == ATTEMPTS:                    raise RuntimeError(f'{destination.name}: {ATTEMPTS} range attempts failed; resume {part}: {error}') from error            finally:                chunk.unlink(missing_ok=True)        if last is not None and not part.exists():            raise RuntimeError(f'{destination.name}: package was not verified: {last}')def prepare(repo, cache, kinds, pins, local):    for kind in kinds:        pin = pins[kind]        destination = asset_path(cache, kind, pin)        destination.parent.mkdir(parents=True, exist_ok=True)        # One writer per asset; fail boundedly rather than waiting behind a hung fetch.        with destination.with_suffix('.lock').open('a') as lock:            expires = time.monotonic() + 60            while True:                try:                    fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)                    break                except BlockingIOError:                    if time.monotonic() >= expires:                        raise TimeoutError(f'{kind}.sqlite: cache preparation lock held for 60s')                    time.sleep(0.1)            try:                verify(destination, pin['package_sha256'])                print(f'{kind}: shared cache verified')                continue            except FileNotFoundError:                pass            candidate = local / f'{kind}.sqlite'            try:                verify(candidate, pin['package_sha256'])            except (OSError, ValueError):                url = pin.get('package_path') or pins['package_root'].rstrip('/') + f'/{kind}.sqlite'                acquire(repo, url, destination, pin['package_sha256'])            else:                publish(candidate, destination, pin['package_sha256'])            print(f'{kind}: shared cache prepared {pin["package_sha256"]}')