|
| 1 | +"""Module containing the RemoteCache implementation.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import hashlib |
| 6 | +import json |
| 7 | +import logging |
| 8 | +import os |
| 9 | +from dataclasses import dataclass, field |
| 10 | +from pathlib import Path |
| 11 | +from urllib.request import urlopen |
| 12 | + |
| 13 | +from dacite import from_dict |
| 14 | + |
| 15 | +from ..pipeline.cache import PipelineCacheEntry |
| 16 | + |
| 17 | + |
| 18 | +@dataclass(frozen=True) |
| 19 | +class FileEntry: |
| 20 | + """Entry in the manifest for a single cached file.""" |
| 21 | + |
| 22 | + sha256: str |
| 23 | + url: str |
| 24 | + |
| 25 | + |
| 26 | +@dataclass(frozen=True) |
| 27 | +class Manifest: |
| 28 | + """Manifest for cached files stored in GitHub releases.""" |
| 29 | + |
| 30 | + v: int |
| 31 | + files: dict[str, FileEntry] = field(default_factory=dict) |
| 32 | + |
| 33 | + def __post_init__(self): |
| 34 | + if self.v != 0: |
| 35 | + raise ValueError(f"Unsupported manifest version: {self.v} (only v=0 supported)") |
| 36 | + |
| 37 | + def get_file_entry(self, *, full_path: Path, data_dir: Path) -> FileEntry: |
| 38 | + """ |
| 39 | + Return the file entry corresponding to a given full path and data directory. |
| 40 | +
|
| 41 | + Raises: |
| 42 | + KeyError: if the given remote entry does not exist. |
| 43 | + """ |
| 44 | + # Use .as_posix() to ensure forward slashes for cross-platform compatibility |
| 45 | + # Manifest keys should always use forward slashes regardless of OS |
| 46 | + key = full_path.relative_to(data_dir).as_posix() |
| 47 | + try: |
| 48 | + return self.files[key] |
| 49 | + except KeyError as exc: |
| 50 | + raise KeyError(f"no remotely-cached file for {key}") from exc |
| 51 | + |
| 52 | + |
| 53 | +def iqb_github_load_manifest(manifest_file: Path) -> Manifest: |
| 54 | + """Load manifest from the given file, or return empty manifest if not found.""" |
| 55 | + if not manifest_file.exists(): |
| 56 | + return Manifest(v=0, files={}) |
| 57 | + |
| 58 | + with open(manifest_file) as filep: |
| 59 | + data = json.load(filep) |
| 60 | + |
| 61 | + return from_dict(Manifest, data) |
| 62 | + |
| 63 | + |
| 64 | +class IQBGitHubRemoteCache: |
| 65 | + """ |
| 66 | + Remote cache for query results using GitHub releases. |
| 67 | +
|
| 68 | + This class implements the pipeline.RemoteCache protocol. |
| 69 | + """ |
| 70 | + |
| 71 | + def __init__(self, manifest: Manifest) -> None: |
| 72 | + self.manifest = manifest |
| 73 | + |
| 74 | + def sync(self, entry: PipelineCacheEntry) -> bool: |
| 75 | + """ |
| 76 | + Sync remote cache entry to disk and return whether |
| 77 | + we successfully synced it or not. Emits logging messages |
| 78 | + explaining what it is doing and warning about issues |
| 79 | + occurred while trying to sync from the remote. |
| 80 | + """ |
| 81 | + try: |
| 82 | + logging.info(f"ghremote: syncing {entry}... start") |
| 83 | + self._sync(entry) |
| 84 | + logging.info(f"ghremote: syncing {entry}... ok") |
| 85 | + return True |
| 86 | + except Exception as exc: |
| 87 | + logging.warning(f"ghremote: syncing {entry}... failure: {exc}") |
| 88 | + return False |
| 89 | + |
| 90 | + def _sync(self, entry: PipelineCacheEntry): |
| 91 | + # Lookup files in the manifest using pipeline-provided paths |
| 92 | + # so we don't need to revalidate them again. |
| 93 | + parquet_entry = self.manifest.get_file_entry( |
| 94 | + full_path=entry.data_parquet_file_path(), |
| 95 | + data_dir=entry.data_dir, |
| 96 | + ) |
| 97 | + json_entry = self.manifest.get_file_entry( |
| 98 | + full_path=entry.stats_json_file_path(), |
| 99 | + data_dir=entry.data_dir, |
| 100 | + ) |
| 101 | + |
| 102 | + # Sync both entries given preference to the JSON since it's smaller |
| 103 | + # and leads to less wasted bandwidth if the parquet doesn't exist. |
| 104 | + _sync_file_entry(json_entry, entry.stats_json_file_path()) |
| 105 | + _sync_file_entry(parquet_entry, entry.data_parquet_file_path()) |
| 106 | + |
| 107 | + |
| 108 | +def _sync_file_entry(entry: FileEntry, dest_path: Path): |
| 109 | + """Sync the given FileEntry with the file cached in a GitHub release.""" |
| 110 | + # Determine whether we need to download again |
| 111 | + exists = dest_path.exists() |
| 112 | + if not exists or entry.sha256 != _compute_sha256(dest_path): |
| 113 | + # If old file exists, remove it |
| 114 | + if exists: |
| 115 | + os.unlink(dest_path) |
| 116 | + |
| 117 | + # Download into the destination file directly |
| 118 | + logging.info(f"ghremote: fetching {entry}... start") |
| 119 | + dest_path.parent.mkdir(parents=True, exist_ok=True) |
| 120 | + with urlopen(entry.url) as response, open(dest_path, "wb") as fp: |
| 121 | + while chunk := response.read(8192): |
| 122 | + fp.write(chunk) |
| 123 | + logging.info(f"ghremote: fetching {entry}... ok") |
| 124 | + |
| 125 | + # Make sure the sha256 matches |
| 126 | + logging.info(f"ghremote: validating {entry}... start") |
| 127 | + sha256 = _compute_sha256(dest_path) |
| 128 | + if sha256 != entry.sha256: |
| 129 | + os.unlink(dest_path) |
| 130 | + raise ValueError(f"SHA256 mismatch: expected {entry.sha256}, got {sha256}") |
| 131 | + logging.info(f"ghremote: validating {entry}... ok") |
| 132 | + |
| 133 | + |
| 134 | +def _compute_sha256(path: Path) -> str: |
| 135 | + """Compute SHA256 hash of a file.""" |
| 136 | + sha256 = hashlib.sha256() |
| 137 | + with open(path, "rb") as fp: |
| 138 | + while chunk := fp.read(8192): |
| 139 | + sha256.update(chunk) |
| 140 | + return sha256.hexdigest() |
0 commit comments