|
| 1 | +"""Cache usage command.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import json |
| 6 | +import re |
| 7 | +from dataclasses import dataclass, field |
| 8 | +from pathlib import Path |
| 9 | + |
| 10 | +import click |
| 11 | +from rich.console import Console |
| 12 | +from rich.table import Table |
| 13 | + |
| 14 | +from ..pipeline.cache import ( |
| 15 | + PIPELINE_CACHE_DATA_FILENAME, |
| 16 | + PIPELINE_CACHE_STATS_FILENAME, |
| 17 | + data_dir_or_default, |
| 18 | +) |
| 19 | +from .cache import cache |
| 20 | + |
| 21 | +_TS_RE = re.compile(r"^\d{8}T\d{6}Z$") |
| 22 | +_DATASET_RE = re.compile(r"^[a-z0-9_]+$") |
| 23 | + |
| 24 | + |
| 25 | +@dataclass |
| 26 | +class _DatasetStats: |
| 27 | + """Per-dataset raw statistics.""" |
| 28 | + |
| 29 | + name: str |
| 30 | + parquet_size: int |
| 31 | + bq_bytes_billed: int |
| 32 | + query_duration_seconds: float |
| 33 | + |
| 34 | + |
| 35 | +@dataclass |
| 36 | +class _PeriodStats: |
| 37 | + """Aggregated statistics for a (start, end) time period.""" |
| 38 | + |
| 39 | + start_ts: str |
| 40 | + end_ts: str |
| 41 | + datasets: list[_DatasetStats] = field(default_factory=list) |
| 42 | + |
| 43 | + @property |
| 44 | + def total_parquet_size(self) -> int: |
| 45 | + return sum(d.parquet_size for d in self.datasets) |
| 46 | + |
| 47 | + @property |
| 48 | + def total_bq_bytes_billed(self) -> int: |
| 49 | + return sum(d.bq_bytes_billed for d in self.datasets) |
| 50 | + |
| 51 | + @property |
| 52 | + def total_query_duration(self) -> float: |
| 53 | + return sum(d.query_duration_seconds for d in self.datasets) |
| 54 | + |
| 55 | + |
| 56 | +def _read_stats_json(stats_path: Path) -> tuple[int, float]: |
| 57 | + """Read stats.json and return (total_bytes_billed, query_duration_seconds). |
| 58 | +
|
| 59 | + Tolerates missing files, corrupt JSON, and null field values by |
| 60 | + returning zeros for any value that cannot be read. |
| 61 | + """ |
| 62 | + if not stats_path.exists(): |
| 63 | + return 0, 0.0 |
| 64 | + try: |
| 65 | + data = json.loads(stats_path.read_text()) |
| 66 | + except (json.JSONDecodeError, OSError): |
| 67 | + return 0, 0.0 |
| 68 | + bq_bytes = data.get("total_bytes_billed") |
| 69 | + duration = data.get("query_duration_seconds") |
| 70 | + return ( |
| 71 | + int(bq_bytes) if bq_bytes is not None else 0, |
| 72 | + float(duration) if duration is not None else 0.0, |
| 73 | + ) |
| 74 | + |
| 75 | + |
| 76 | +def _scan_periods(data_dir: Path) -> list[_PeriodStats]: |
| 77 | + """Walk cache/v1/{start}/{end}/{dataset}/ and collect statistics.""" |
| 78 | + cache_root = data_dir / "cache" / "v1" |
| 79 | + if not cache_root.is_dir(): |
| 80 | + return [] |
| 81 | + |
| 82 | + periods: dict[tuple[str, str], _PeriodStats] = {} |
| 83 | + |
| 84 | + for start_dir in sorted(cache_root.iterdir()): |
| 85 | + if not start_dir.is_dir() or not _TS_RE.match(start_dir.name): |
| 86 | + continue |
| 87 | + for end_dir in sorted(start_dir.iterdir()): |
| 88 | + if not end_dir.is_dir() or not _TS_RE.match(end_dir.name): |
| 89 | + continue |
| 90 | + for dataset_dir in sorted(end_dir.iterdir()): |
| 91 | + if not dataset_dir.is_dir() or not _DATASET_RE.match(dataset_dir.name): |
| 92 | + continue |
| 93 | + parquet_path = dataset_dir / PIPELINE_CACHE_DATA_FILENAME |
| 94 | + if not parquet_path.exists(): |
| 95 | + continue |
| 96 | + parquet_size = parquet_path.stat().st_size |
| 97 | + stats_path = dataset_dir / PIPELINE_CACHE_STATS_FILENAME |
| 98 | + bq_bytes, duration = _read_stats_json(stats_path) |
| 99 | + key = (start_dir.name, end_dir.name) |
| 100 | + if key not in periods: |
| 101 | + periods[key] = _PeriodStats(start_ts=key[0], end_ts=key[1]) |
| 102 | + periods[key].datasets.append( |
| 103 | + _DatasetStats( |
| 104 | + name=dataset_dir.name, |
| 105 | + parquet_size=parquet_size, |
| 106 | + bq_bytes_billed=bq_bytes, |
| 107 | + query_duration_seconds=duration, |
| 108 | + ) |
| 109 | + ) |
| 110 | + |
| 111 | + return [periods[k] for k in sorted(periods)] |
| 112 | + |
| 113 | + |
| 114 | +def _format_bytes(n: int) -> str: |
| 115 | + """Format a byte count using SI-like suffixes.""" |
| 116 | + if n == 0: |
| 117 | + return "0 B" |
| 118 | + for unit in ("B", "KB", "MB", "GB", "TB"): |
| 119 | + if abs(n) < 1024: |
| 120 | + if n == int(n): |
| 121 | + return f"{int(n)} {unit}" |
| 122 | + return f"{n:.1f} {unit}" |
| 123 | + n_f = n / 1024 |
| 124 | + n = n_f # type: ignore[assignment] |
| 125 | + return f"{n:.1f} PB" |
| 126 | + |
| 127 | + |
| 128 | +def _format_duration(seconds: float) -> str: |
| 129 | + """Format a duration in seconds to a human-readable string.""" |
| 130 | + if seconds == 0: |
| 131 | + return "0s" |
| 132 | + if seconds < 60: |
| 133 | + return f"{seconds:.1f}s" |
| 134 | + minutes = int(seconds // 60) |
| 135 | + remaining = seconds - minutes * 60 |
| 136 | + return f"{minutes}m {remaining:.1f}s" |
| 137 | + |
| 138 | + |
| 139 | +def _format_period(start_ts: str, end_ts: str) -> str: |
| 140 | + """Format a pair of RFC3339-ish timestamps for display. |
| 141 | +
|
| 142 | + Converts '20241001T000000Z' to '2024-10-01' style. |
| 143 | + """ |
| 144 | + start = f"{start_ts[:4]}-{start_ts[4:6]}-{start_ts[6:8]}" |
| 145 | + end = f"{end_ts[:4]}-{end_ts[4:6]}-{end_ts[6:8]}" |
| 146 | + return f"{start} .. {end}" |
| 147 | + |
| 148 | + |
| 149 | +def _build_table(periods: list[_PeriodStats]) -> Table: |
| 150 | + """Construct a Rich Table from the scanned period stats.""" |
| 151 | + table = Table() |
| 152 | + table.add_column("Period", style="cyan") |
| 153 | + table.add_column("Datasets", justify="right") |
| 154 | + table.add_column("Parquet Size", justify="right") |
| 155 | + table.add_column("BQ Bytes Billed", justify="right") |
| 156 | + table.add_column("Query Duration", justify="right") |
| 157 | + |
| 158 | + total_datasets = 0 |
| 159 | + total_parquet = 0 |
| 160 | + total_bq = 0 |
| 161 | + total_duration = 0.0 |
| 162 | + |
| 163 | + for period in periods: |
| 164 | + count = len(period.datasets) |
| 165 | + total_datasets += count |
| 166 | + total_parquet += period.total_parquet_size |
| 167 | + total_bq += period.total_bq_bytes_billed |
| 168 | + total_duration += period.total_query_duration |
| 169 | + table.add_row( |
| 170 | + _format_period(period.start_ts, period.end_ts), |
| 171 | + str(count), |
| 172 | + _format_bytes(period.total_parquet_size), |
| 173 | + _format_bytes(period.total_bq_bytes_billed), |
| 174 | + _format_duration(period.total_query_duration), |
| 175 | + ) |
| 176 | + |
| 177 | + table.add_section() |
| 178 | + table.add_row( |
| 179 | + "[bold]Total[/bold]", |
| 180 | + f"[bold]{total_datasets}[/bold]", |
| 181 | + f"[bold]{_format_bytes(total_parquet)}[/bold]", |
| 182 | + f"[bold]{_format_bytes(total_bq)}[/bold]", |
| 183 | + f"[bold]{_format_duration(total_duration)}[/bold]", |
| 184 | + ) |
| 185 | + |
| 186 | + return table |
| 187 | + |
| 188 | + |
| 189 | +@cache.command() |
| 190 | +@click.option("-d", "--dir", "data_dir", default=None, help="Data directory (default: .iqb)") |
| 191 | +def usage(data_dir: str | None) -> None: |
| 192 | + """Show cache disk and BigQuery usage statistics.""" |
| 193 | + resolved = data_dir_or_default(data_dir) |
| 194 | + periods = _scan_periods(resolved) |
| 195 | + if not periods: |
| 196 | + click.echo("No cached data found.") |
| 197 | + return |
| 198 | + console = Console() |
| 199 | + console.print(_build_table(periods)) |
0 commit comments