-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgha_explorer.py
More file actions
executable file
·5854 lines (5145 loc) · 236 KB
/
Copy pathgha_explorer.py
File metadata and controls
executable file
·5854 lines (5145 loc) · 236 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "textual>=8.0,<9",
# "plotext>=6.0.0,<7",
# "rich>=13.0.0",
# ]
# ///
"""
GHA Explorer — a TUI for exploring GitHub Actions workflow timing.
Usage:
uvx gha-explorer [--repo owner/name] [--theme NAME]
# or from a checkout: ./gha_explorer.py
Incrementally fetches successful workflow runs for a repo straight from the
GitHub REST API (no `gh` needed — see `resolve_token()` for how it signs in),
caching results in SQLite. On subsequent launches, cached data displays
immediately and only new runs are fetched from the API.
Data (cache.db, log) lives in a per-user directory — see `data_dir()`; override
with GHA_EXPLORER_HOME. INFO+ log lines also stream to the in-app Status tab.
"""
from __future__ import annotations
import json
import logging
import math
import os
import re
import shutil
import sqlite3
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import webbrowser
from bisect import bisect_left
from collections import deque
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field, replace
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from statistics import mean, median, stdev
from rich.console import Group as RichGroup
from rich.style import Style as RichStyle
from rich.text import Text as RichText
from textual import events, on, work
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Horizontal, Vertical, VerticalScroll
from textual.message import Message
from textual.reactive import reactive
from textual.screen import ModalScreen, Screen
from textual.theme import Theme
from textual.widgets import (
Button,
Checkbox,
ContentSwitcher,
DataTable,
Footer,
Input,
Label,
OptionList,
RadioButton,
RadioSet,
RichLog,
SelectionList,
Static,
Tab,
Tabs,
TextArea,
)
from textual.widgets.option_list import Option
from textual.widgets.selection_list import Selection
from textual.worker import Worker, WorkerState, get_current_worker
# ---------------------------------------------------------------------------
# Data directory — where cache.db and the log live
# ---------------------------------------------------------------------------
__version__ = "0.1.8"
DB_FILENAME = "gha-explorer.db" # runs cache + settings + notes
LEGACY_DB_FILENAME = "cache.db" # original (pre-release) name, renamed on first launch
PATHS_FILENAME = "paths.json" # {"db_path": ...} — can't live inside the DB it points at
def data_dir() -> Path:
"""Per-user data directory.
1. $GHA_EXPLORER_HOME if set.
2. The script's own directory if a cache.db already sits there (a checkout
that has been used before — keeps existing setups working).
3. Platform default: $XDG_DATA_HOME/gha-explorer (~/.local/share/gha-explorer)
or %LOCALAPPDATA%/gha-explorer on Windows. This is what `uvx` installs use,
since the package itself lives in an ephemeral environment.
"""
env = os.environ.get("GHA_EXPLORER_HOME")
if env:
return Path(env).expanduser()
here = Path(__file__).resolve().parent
if (here / DB_FILENAME).exists() or (here / LEGACY_DB_FILENAME).exists():
return here
if sys.platform == "win32":
base = Path(os.environ.get("LOCALAPPDATA") or (Path.home() / "AppData" / "Local"))
else:
base = Path(os.environ.get("XDG_DATA_HOME") or (Path.home() / ".local" / "share"))
return base / "gha-explorer"
DATA_DIR = data_dir()
DATA_DIR.mkdir(parents=True, exist_ok=True)
PATHS_FILE = DATA_DIR / PATHS_FILENAME
def _read_paths() -> dict:
try:
return json.loads(PATHS_FILE.read_text(encoding="utf-8")) if PATHS_FILE.exists() else {}
except Exception:
return {}
def resolve_db_path() -> Path:
"""$GHA_EXPLORER_DB, else paths.json, else <data dir>/gha-explorer.db.
A pre-release cache.db in the data dir is renamed to the new name (with its
-wal/-shm siblings) the first time no gha-explorer.db exists.
"""
env = os.environ.get("GHA_EXPLORER_DB")
if env:
return Path(env).expanduser()
stored = _read_paths().get("db_path")
if stored:
return Path(stored).expanduser()
default = DATA_DIR / DB_FILENAME
legacy = DATA_DIR / LEGACY_DB_FILENAME
if not default.exists() and legacy.exists():
for suffix in ("", "-wal", "-shm"):
src = Path(str(legacy) + suffix)
if src.exists():
src.rename(str(default) + suffix)
return default
def set_db_path(path: Path) -> None:
"""Remember a custom DB location and switch to it (connections reconnect lazily)."""
global CACHE_DB
path = path.expanduser()
path.parent.mkdir(parents=True, exist_ok=True)
PATHS_FILE.write_text(json.dumps({"db_path": str(path)}, indent=2), encoding="utf-8")
CACHE_DB = path
def reveal_in_file_manager(path: Path) -> None:
"""Show the file in Finder / Explorer / the desktop's file manager."""
if sys.platform == "darwin":
subprocess.Popen(["open", "-R", str(path)])
elif sys.platform == "win32":
subprocess.Popen(["explorer", f"/select,{path}"])
else:
subprocess.Popen(["xdg-open", str(path.parent)])
FILE_MANAGER_NAME = {"darwin": "Finder", "win32": "Explorer"}.get(sys.platform, "file manager")
# ---------------------------------------------------------------------------
# Logging — file (DEBUG) + in-memory ring buffer (INFO) drained by the UI
# ---------------------------------------------------------------------------
LOG_FILE = DATA_DIR / "gha_explorer.log"
logging.basicConfig(
filename=str(LOG_FILE),
encoding="utf-8", # log lines contain → — ·; Windows' default code page can't encode them
level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
log = logging.getLogger("gha_explorer")
class UILogHandler(logging.Handler):
"""Buffers log records so the Status tab can display them.
deque.append/popleft are thread-safe, so worker threads can log freely and
the UI drains on its own timer — no cross-thread widget access.
"""
def __init__(self, maxlen: int = 1000) -> None:
super().__init__(level=logging.INFO)
self.records: deque[tuple[datetime, str, str]] = deque(maxlen=maxlen)
def emit(self, record: logging.LogRecord) -> None:
try:
self.records.append(
(datetime.fromtimestamp(record.created), record.levelname, record.getMessage())
)
except Exception:
pass
UI_LOG = UILogHandler()
logging.getLogger().addHandler(UI_LOG)
# ---------------------------------------------------------------------------
# Theme — dark with lavender accents. Plot colors derive from the active
# Textual theme so `--theme catppuccin-mocha` etc. restyle the charts too.
# ---------------------------------------------------------------------------
LAVENDER = {
"background": "#14121C",
"surface": "#1B1826",
"panel": "#242034",
"primary": "#B4A3F7",
"secondary": "#8B7AD9",
"accent": "#D4C4FF",
"foreground": "#E8E4F3",
"success": "#86D9A6",
"warning": "#F0C674",
"error": "#F07178",
}
GHA_THEME = Theme(
name="gha-lavender",
dark=True,
**LAVENDER,
variables={
"footer-key-foreground": LAVENDER["accent"],
"footer-description-foreground": "#A9A3BD",
"block-cursor-background": LAVENDER["primary"],
"block-cursor-foreground": LAVENDER["background"],
"block-cursor-text-style": "bold",
"block-cursor-blurred-background": "#3A3450",
"block-cursor-blurred-foreground": LAVENDER["foreground"],
"border": LAVENDER["secondary"],
"border-blurred": "#3A3450",
"scrollbar": "#3A3450",
"scrollbar-hover": LAVENDER["secondary"],
"scrollbar-active": LAVENDER["primary"],
# Track = pane background. Terminal fonts whose █ doesn't fill the cell leave a
# sliver of track colour beside the thumb, which reads as a second, offset bar.
"scrollbar-background": LAVENDER["background"],
"scrollbar-background-hover": LAVENDER["background"],
"scrollbar-background-active": LAVENDER["background"],
"scrollbar-corner-color": LAVENDER["background"],
"input-cursor-background": LAVENDER["primary"],
"input-selection-background": "#8B7AD9 35%",
"link-color": LAVENDER["accent"],
},
)
def _hex_to_rgb(hex_color: str) -> tuple[int, int, int]:
h = hex_color.lstrip("#")
return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
@dataclass
class PlotPalette:
"""RGB tuples for plotext, derived from the active Textual theme."""
axes: tuple[int, int, int]
series: list[tuple[int, int, int]]
primary_hex: str
success_hex: str
error_hex: str
warning_hex: str
muted_hex: str
@classmethod
def from_theme(cls, theme: Theme) -> PlotPalette:
primary = theme.primary
accent = theme.accent or primary
success = theme.success or "#86D9A6"
warning = theme.warning or "#F0C674"
error = theme.error or "#F07178"
secondary = theme.secondary or primary
return cls(
axes=_hex_to_rgb("#7E7599") if theme.name == GHA_THEME.name else _hex_to_rgb(secondary),
series=[_hex_to_rgb(c) for c in (accent, success, warning, "#7DC4F0", error, secondary)],
primary_hex=primary,
success_hex=success,
error_hex=error,
warning_hex=warning,
muted_hex="#A9A3BD",
)
DEFAULT_PALETTE = PlotPalette.from_theme(GHA_THEME)
# ---------------------------------------------------------------------------
# Sync stats — shared between the fetch thread and the UI
# ---------------------------------------------------------------------------
@dataclass
class SyncStats:
"""Live counters for the current sync. Written by worker threads, read by the UI.
Individual attribute writes are atomic under the GIL; `snapshot()` takes the
lock so the UI sees a consistent view.
"""
phase: str = "idle" # idle | cache | forward | details | backfill | done | error | rate-limited
message: str = ""
done: int = 0
total: int = 0
api_calls: int = 0
api_errors: int = 0
rate_limit_retries: int = 0
new_runs: int = 0
windows_done: int = 0
current_window: str = ""
started_at: float | None = None
finished_at: float | None = None
last_error: str = ""
rate_limit: dict | None = None # {"limit", "remaining", "reset", "used"} for the core bucket
rate_limit_checked_at: float | None = None
rate_limit_source: str = "" # "headers" (authoritative) or "poll" (/rate_limit, which can lag or lie)
rate_limit_wait_until: float | None = None # epoch seconds while a worker is waiting for the reset
stop_requested: bool = False # set when the app exits so waiting workers give up promptly
# First-sync panel: which steps ran, how long each took, what's left to estimate
first_load: bool = False
phase_started_at: float | None = None
step_elapsed: dict = field(default_factory=dict) # phase -> seconds spent so far
listed_runs: int = 0 # runs found by the listing phase (this sync)
backfill_total: int = 0 # estimated number of 90-day windows to walk
# Budget cap: a normal sync spends at most half the hour's remaining requests on
# job timings (newest runs first); what doesn't fit is deferred to the next sync.
detail_budget: int | None = None # None = uncapped (shift+R)
detail_budget_left: int = 0
deferred_runs: int = 0
history_pending: bool = False # older history skipped this sync because the allowance is spent
resume_at: float | None = None # epoch: when the deferred remainder can continue
_lock: threading.Lock = field(default_factory=threading.Lock, repr=False, compare=False)
def reset_for_sync(self) -> None:
with self._lock:
self.phase = "cache"
self.message = ""
self.done = self.total = 0
self.new_runs = self.windows_done = 0
self.current_window = ""
self.started_at = time.monotonic()
self.phase_started_at = self.started_at
self.finished_at = None
self.last_error = ""
self.first_load = False
self.step_elapsed = {}
self.listed_runs = 0
self.backfill_total = 0
self.detail_budget = None
self.detail_budget_left = 0
self.deferred_runs = 0
self.history_pending = False
self.resume_at = None
def set_phase(self, phase: str, message: str = "") -> None:
with self._lock:
now = time.monotonic()
if self.phase_started_at is not None:
self.step_elapsed[self.phase] = self.step_elapsed.get(self.phase, 0.0) + (now - self.phase_started_at)
if phase != self.phase:
self.done = self.total = 0 # progress counters belong to a phase
self.phase = phase
self.message = message
self.phase_started_at = now
log.info("%s", message or phase)
def set_progress(self, done: int, total: int) -> None:
with self._lock:
self.done, self.total = done, total
def snapshot(self) -> dict:
with self._lock:
snap = {k: v for k, v in self.__dict__.items() if not k.startswith("_")}
snap["step_elapsed"] = dict(self.step_elapsed)
return snap
STATS = SyncStats()
# ---------------------------------------------------------------------------
# Data layer
# ---------------------------------------------------------------------------
MAX_WORKERS = 8
RUN_LIST_LIMIT = 1000 # hard cap of `gh run list --limit`
BACKFILL_WINDOW_DAYS = 90
MAX_BACKFILL_WINDOWS = 80 # ~20 years; safety valve only
GAP_DAYS = 7 # a hole this long between cached runs is checked against the API once
TIME_RANGES: dict[str, timedelta | None] = {
"1d": timedelta(days=1),
"1m": timedelta(days=30),
"3m": timedelta(days=90),
"6m": timedelta(days=180),
"1y": timedelta(days=365),
"all": None,
}
CACHE_DB = resolve_db_path()
CONFIG_FILE = DATA_DIR / "config.json" # legacy; imported into the settings table once
_db_local = threading.local()
def _init_schema(conn: sqlite3.Connection) -> None:
conn.execute("""
CREATE TABLE IF NOT EXISTS run_jobs (
run_id INTEGER PRIMARY KEY,
repo TEXT NOT NULL,
raw_run TEXT NOT NULL,
raw_jobs TEXT NOT NULL,
fetched_at TEXT NOT NULL
)
""")
conn.execute("CREATE INDEX IF NOT EXISTS idx_run_jobs_repo ON run_jobs(repo)")
conn.execute("""
CREATE TABLE IF NOT EXISTS sync_meta (
repo TEXT PRIMARY KEY,
backfill_complete INTEGER NOT NULL DEFAULT 0,
last_sync_at TEXT
)
""")
# Sticky UI state: scope is a repo name (per-repo filters) or GLOBAL_SCOPE
conn.execute("""
CREATE TABLE IF NOT EXISTS settings (
scope TEXT NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL,
PRIMARY KEY (scope, key)
)
""")
# Notes pinned to a point in time, drawn as vertical markers on the trend charts
conn.execute("""
CREATE TABLE IF NOT EXISTS notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo TEXT NOT NULL,
at TEXT NOT NULL,
text TEXT NOT NULL,
created_at TEXT NOT NULL
)
""")
conn.execute("CREATE INDEX IF NOT EXISTS idx_notes_repo ON notes(repo, at)")
# notes.jobs: NULL = all jobs, else JSON list of job names the note applies to
cols = {row[1] for row in conn.execute("PRAGMA table_info(notes)").fetchall()}
if "jobs" not in cols:
conn.execute("ALTER TABLE notes ADD COLUMN jobs TEXT")
if "color" not in cols:
conn.execute("ALTER TABLE notes ADD COLUMN color TEXT") # hex; NULL = default (theme error red)
conn.commit()
def _cache_conn() -> sqlite3.Connection:
"""One connection per thread, WAL mode, schema ensured once per connection.
Reconnects if the DB path changed since this thread last connected."""
conn = getattr(_db_local, "conn", None)
if conn is not None and getattr(_db_local, "path", None) != str(CACHE_DB):
try:
conn.close()
except Exception:
pass
conn = None
if conn is None:
CACHE_DB.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(str(CACHE_DB), timeout=30)
conn.execute("PRAGMA journal_mode=WAL")
_init_schema(conn)
_db_local.conn = conn
_db_local.path = str(CACHE_DB)
return conn
def switch_db(new_path: Path) -> str:
"""Point the app at another DB file. If it doesn't exist yet, the current DB is
copied there (after a WAL checkpoint) so renaming/moving is painless. The old
file is left in place. Returns a short description of what happened."""
new_path = new_path.expanduser()
if new_path.exists() and new_path.resolve() == CACHE_DB.resolve():
return "Already using that database."
copied = False
if not new_path.exists() and CACHE_DB.exists():
try:
_cache_conn().execute("PRAGMA wal_checkpoint(TRUNCATE)")
except Exception:
log.debug("checkpoint before copy failed", exc_info=True)
new_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(CACHE_DB, new_path)
copied = True
old = CACHE_DB
set_db_path(new_path)
log.info("Switched database %s -> %s (%s)", old, new_path, "copied" if copied else "existing file")
return (f"Copied the current database to {new_path} and switched to it. The old file at {old} was left in place."
if copied else f"Switched to the existing database at {new_path}.")
def cache_get_jobs(run_id: int) -> tuple[dict, list[dict]] | None:
"""Look up by run_id only — run IDs are globally unique in GitHub."""
row = _cache_conn().execute(
"SELECT raw_run, raw_jobs FROM run_jobs WHERE run_id = ?", (run_id,)
).fetchone()
if row:
return json.loads(row[0]), json.loads(row[1])
return None
def cache_put_jobs(repo: str, run_id: int, raw_run: dict, raw_jobs: list[dict]) -> None:
conn = _cache_conn()
with conn:
conn.execute(
"INSERT OR REPLACE INTO run_jobs (repo, run_id, raw_run, raw_jobs, fetched_at) VALUES (?, ?, ?, ?, ?)",
(repo, run_id, json.dumps(raw_run), json.dumps(raw_jobs), datetime.now(timezone.utc).isoformat()),
)
def cache_get_all_ids(repo: str) -> set[int]:
rows = _cache_conn().execute("SELECT run_id FROM run_jobs WHERE repo = ?", (repo,)).fetchall()
return {row[0] for row in rows}
def cache_load_all(repo: str) -> list[RunData]:
"""Load all cached runs for a repo from SQLite, oldest first."""
rows = _cache_conn().execute(
"SELECT raw_run, raw_jobs, fetched_at FROM run_jobs WHERE repo = ?", (repo,)
).fetchall()
runs = []
for raw_run_json, raw_jobs_json, fetched_at in rows:
try:
run = build_run_data(json.loads(raw_run_json), json.loads(raw_jobs_json))
try:
run.fetched_at = datetime.fromisoformat(fetched_at)
if run.fetched_at.tzinfo is None:
run.fetched_at = run.fetched_at.replace(tzinfo=timezone.utc)
except (TypeError, ValueError):
pass
runs.append(run)
except Exception:
log.debug("Skipping corrupt cache row", exc_info=True)
runs.sort(key=lambda r: r.created_at)
return runs
def cache_summary(repo: str) -> dict:
"""Row counts + date span for the status card."""
conn = _cache_conn()
repo_rows, oldest, newest = conn.execute(
"SELECT COUNT(*), MIN(json_extract(raw_run, '$.createdAt')), MAX(json_extract(raw_run, '$.createdAt')) "
"FROM run_jobs WHERE repo = ?",
(repo,),
).fetchone()
total_rows, repos = conn.execute("SELECT COUNT(*), COUNT(DISTINCT repo) FROM run_jobs").fetchone()
meta = conn.execute(
"SELECT backfill_complete, last_sync_at FROM sync_meta WHERE repo = ?", (repo,)
).fetchone()
notes_count = conn.execute("SELECT COUNT(*) FROM notes WHERE repo = ?", (repo,)).fetchone()[0]
size = 0
for suffix in ("", "-wal"):
p = Path(str(CACHE_DB) + suffix)
if p.exists():
size += p.stat().st_size
return {
"repo_rows": repo_rows or 0,
"oldest": (oldest or "")[:10],
"newest": (newest or "")[:10],
"total_rows": total_rows or 0,
"repos": repos or 0,
"db_bytes": size,
"backfill_complete": bool(meta and meta[0]),
"last_sync_at": (meta[1] if meta else None),
"notes": notes_count,
}
def meta_get_backfill_complete(repo: str) -> bool:
row = _cache_conn().execute(
"SELECT backfill_complete FROM sync_meta WHERE repo = ?", (repo,)
).fetchone()
return bool(row and row[0])
def meta_set(repo: str, backfill_complete: bool | None = None) -> None:
conn = _cache_conn()
with conn:
conn.execute(
"INSERT INTO sync_meta (repo, backfill_complete, last_sync_at) VALUES (?, 0, NULL) "
"ON CONFLICT(repo) DO NOTHING",
(repo,),
)
conn.execute("UPDATE sync_meta SET last_sync_at = ? WHERE repo = ?",
(datetime.now(timezone.utc).isoformat(), repo))
if backfill_complete is not None:
conn.execute("UPDATE sync_meta SET backfill_complete = ? WHERE repo = ?",
(int(backfill_complete), repo))
@dataclass
class StepTiming:
name: str
duration_s: float
@dataclass
class JobTiming:
name: str
base_name: str # display name: the raw job name, or its group name once grouped
matrix_key: str | None # member name when the job belongs to a multi-member group, else None
duration_s: float
started_at: datetime
completed_at: datetime
steps: list[StepTiming] = field(default_factory=list)
@dataclass
class RunData:
run_id: int
branch: str
title: str
created_at: datetime
total_duration_s: float
workflow: str = ""
jobs: list[JobTiming] = field(default_factory=list)
fetched_at: datetime | None = None # when this run entered the cache
def parse_dt(s: str) -> datetime:
return datetime.fromisoformat(s.replace("Z", "+00:00"))
def duration_s(start: str, end: str) -> float:
return max(0, (parse_dt(end) - parse_dt(start)).total_seconds())
def _shard_sort_key(key: str) -> list[object]:
"""Natural sort: 'Playwright (2)' before 'Playwright (10)'."""
return [(0, int(part)) if part.isdigit() else (1, part.lower()) for part in re.split(r"(\d+)", key)]
# ---------------------------------------------------------------------------
# GitHub REST API client + sign-in (stdlib urllib; `gh` is optional)
# ---------------------------------------------------------------------------
GITHUB_API = "https://api.github.com"
# Public client ID of the "GHA Explorer" OAuth app. Device flow only — there is
# no client secret, so it is safe to ship in source.
GITHUB_OAUTH_CLIENT_ID = "Ov23liOAZ82yZCtwbZOr"
GITHUB_OAUTH_SCOPE = "repo" # needed to read Actions data on private repos
AUTH_FILE = DATA_DIR / "auth.json"
USER_AGENT = f"gha-explorer/{__version__}"
class GitHubAPIError(Exception):
"""Any failed API call (HTTP error, network error, exhausted rate-limit retries)."""
def __init__(self, message: str, status: int | None = None) -> None:
super().__init__(message)
self.status = status
class AuthError(GitHubAPIError):
"""401 — no token, or the token is invalid/revoked. The UI reacts by signing in again."""
class RateLimitError(GitHubAPIError):
"""The hourly budget is gone and we could not (or were told not to) wait for the reset."""
class SyncStopped(Exception):
"""The app is exiting; the sync gives up wherever it is (the cache keeps what landed)."""
def _check_stop() -> None:
if STATS.stop_requested:
raise SyncStopped()
def _sleep_unless_stopped(seconds: float) -> None:
"""time.sleep that returns early (raising SyncStopped) when the app is quitting."""
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
_check_stop()
time.sleep(min(0.5, deadline - time.monotonic()))
RATE_LIMIT_MAX_WAIT_S = 70 * 60 # core resets hourly; anything longer means the reset header is wrong
def _note_rate_limit_headers(headers) -> None:
"""Record the core bucket from a real response. These headers are authoritative;
the /rate_limit endpoint has been seen reporting 5000/5000 for a token whose
requests were simultaneously returning remaining=0."""
try:
if headers is None or headers.get("X-RateLimit-Resource", "core") != "core":
return
limit, remaining = headers.get("X-RateLimit-Limit"), headers.get("X-RateLimit-Remaining")
if limit is None or remaining is None:
return
STATS.rate_limit = {
"limit": int(limit), "remaining": int(remaining),
"reset": int(headers.get("X-RateLimit-Reset", "0") or 0),
"used": int(headers.get("X-RateLimit-Used", "0") or 0),
}
STATS.rate_limit_checked_at = time.monotonic()
STATS.rate_limit_source = "headers"
except (TypeError, ValueError):
pass
def fmt_reset(reset_epoch: float) -> str:
"""The one way a reset moment is printed anywhere: '21:32 (in 14m 10s)'."""
left = reset_epoch - time.time()
at = time.strftime("%H:%M", time.localtime(reset_epoch))
return f"{at} (in {fmt_elapsed(left)})" if left > 0 else f"{at} (passed)"
def rate_limit_view(s: dict) -> dict | None:
"""The core budget as every surface shows it, derived only from the last real
response's headers. Once that window's reset has passed the budget is full again
and there is nothing to count down. None until the first request of the session."""
rl = s.get("rate_limit")
if not rl or not rl.get("limit"):
return None
view = dict(rl)
checked = s.get("rate_limit_checked_at")
view["age_s"] = (time.monotonic() - checked) if checked else None
if rl.get("reset") and time.time() >= rl["reset"]:
view.update(remaining=rl["limit"], used=0, reset=None, restored=True)
else:
view["restored"] = False
return view
def _wait_for_rate_limit_reset(reset_epoch: float, url: str) -> None:
"""Block this worker until the core bucket resets (in 1 s slices so quitting the
app isn't held up). Raises RateLimitError if asked to stop or the wait is absurd."""
reset_in = reset_epoch - time.time()
if reset_in > RATE_LIMIT_MAX_WAIT_S:
raise RateLimitError(f"API rate limit exhausted and the reset is {int(reset_in // 60)} min away")
STATS.rate_limit_wait_until = reset_epoch + 2
log.warning("API budget spent — waiting for the reset at %s, then continuing (%s)",
fmt_reset(reset_epoch), url.split("?")[0])
try:
while time.time() < reset_epoch + 2:
if STATS.stop_requested:
raise RateLimitError("API rate limit exhausted; stopped while waiting for the reset")
time.sleep(1)
finally:
STATS.rate_limit_wait_until = None
@dataclass
class AuthState:
token: str | None = None
source: str = "none" # "env", "saved login", "gh CLI" or "none"
login: str = ""
AUTH = AuthState()
def _read_auth_file() -> dict:
try:
return json.loads(AUTH_FILE.read_text(encoding="utf-8")) if AUTH_FILE.exists() else {}
except Exception:
log.debug("Could not read %s", AUTH_FILE, exc_info=True)
return {}
def save_token(token: str, login: str = "") -> None:
"""Persist a token from the in-app sign-in, readable only by the current user."""
AUTH_FILE.write_text(json.dumps({"token": token, "login": login}, indent=2), encoding="utf-8")
try:
os.chmod(AUTH_FILE, 0o600) # no-op on Windows, where %LOCALAPPDATA% is already per-user
except OSError:
log.debug("chmod on %s failed", AUTH_FILE, exc_info=True)
AUTH.token, AUTH.source, AUTH.login = token, "saved login", login
def clear_saved_token() -> bool:
existed = AUTH_FILE.exists()
if existed:
AUTH_FILE.unlink()
if AUTH.source == "saved login":
AUTH.token, AUTH.source, AUTH.login = None, "none", ""
return existed
_gh_token_cache: tuple[bool, str | None] = (False, None) # (probed, token)
def gh_cli_token(refresh: bool = False) -> str | None:
"""The GitHub CLI's token, if `gh` is installed and signed in. Probed once per
process (it spawns a subprocess); `refresh=True` re-probes."""
global _gh_token_cache
if _gh_token_cache[0] and not refresh:
return _gh_token_cache[1]
token: str | None = None
if shutil.which("gh") is not None:
try:
result = subprocess.run(
["gh", "auth", "token"], capture_output=True, text=True, encoding="utf-8", errors="replace",
timeout=15,
)
if result.returncode == 0 and result.stdout.strip():
token = result.stdout.strip()
except (OSError, subprocess.SubprocessError):
log.debug("gh auth token failed", exc_info=True)
_gh_token_cache = (True, token)
return token
def gh_cli_available() -> bool:
return gh_cli_token() is not None
AUTH_MODES = ("gh", "rest")
def auth_mode() -> str:
"""Settings → General → GitHub access. "gh" reuses the GitHub CLI's login, "rest"
uses the built-in sign-in. Unset means: gh when it's available, rest otherwise."""
explicit = settings_get(GLOBAL_SCOPE, "auth_mode")
if explicit in AUTH_MODES:
return explicit
return "gh" if gh_cli_available() else "rest"
def resolve_token() -> AuthState:
"""Find a token without asking. $GH_TOKEN / $GITHUB_TOKEN always win; then the
`gh` CLI's login (when the auth mode is "gh"), then the saved in-app login.
Sets and returns AUTH; AUTH.token is None if nothing was found."""
env = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN")
if env:
AUTH.token, AUTH.source, AUTH.login = env.strip(), "env", ""
elif auth_mode() == "gh" and (cli := gh_cli_token()):
AUTH.token, AUTH.source, AUTH.login = cli, "gh CLI", ""
elif (saved := _read_auth_file()).get("token"):
AUTH.token, AUTH.source, AUTH.login = saved["token"], "saved login", saved.get("login", "")
else:
AUTH.token, AUTH.source, AUTH.login = None, "none", ""
log.info("Auth source: %s", AUTH.source)
return AUTH
def auth_status_text() -> str:
"""One line for Settings / Status describing the credentials in use."""
if AUTH.source == "env":
return "Using $GH_TOKEN / $GITHUB_TOKEN from the environment (overrides the setting below)."
if AUTH.source == "gh CLI":
return "Using the GitHub CLI's login (gh auth token)."
if AUTH.source == "saved login":
who = f" as {AUTH.login}" if AUTH.login else ""
return f"Signed in with the built-in login{who}. Token stored in {AUTH_FILE}."
return "Not signed in — the app will ask on the next sync, or use Sign in… below."
def _api_request(url: str, params: dict | None = None, *, retries: int = 4, count: bool = True,
token: str | None = None, wait_for_reset: bool = True,
etag: str | None = None) -> tuple[object, object]:
"""GET one URL. Returns (parsed JSON, response headers).
Retries with backoff on network errors and on secondary rate limits (Retry-After);
waits out a primary rate limit only if it resets within a couple of minutes.
Raises AuthError on 401 and GitHubAPIError for anything else that fails.
"""
if params:
url = f"{url}{'&' if '?' in url else '?'}{urllib.parse.urlencode(params)}"
token = token if token is not None else AUTH.token
headers = {
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
"User-Agent": USER_AGENT,
}
if token:
headers["Authorization"] = f"Bearer {token}"
if etag:
headers["If-None-Match"] = etag # a 304 costs nothing and still carries the rate-limit headers
attempt = 0
while True:
_check_stop()
req = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(req, timeout=60) as resp:
body = resp.read().decode("utf-8")
if count:
STATS.api_calls += 1
_note_rate_limit_headers(resp.headers)
return (json.loads(body) if body.strip() else None), resp.headers
except urllib.error.HTTPError as exc:
status = exc.code
_note_rate_limit_headers(exc.headers)
if status == 304:
return None, exc.headers # Not Modified: free, and the headers are current
body = exc.read().decode("utf-8", "replace")
try:
message = json.loads(body).get("message", body)
except Exception:
message = body
message = (message or f"HTTP {status}").strip()
if status == 401:
STATS.api_errors += 1
STATS.last_error = f"401 {message}"
raise AuthError(f"GitHub rejected the token (401): {message}", status) from None
retry_after = exc.headers.get("Retry-After")
remaining = exc.headers.get("X-RateLimit-Remaining")
rate_limited = status in (403, 429) and (
retry_after is not None or remaining == "0" or "rate limit" in message.lower()
)
if rate_limited and remaining == "0" and not retry_after:
# Primary limit: the hour's budget is spent. Wait for the reset and carry on —
# a first sync of a big repo needs more than 5,000 requests, so this is normal.
if not wait_for_reset:
raise RateLimitError(f"API budget spent — resets {fmt_reset(int(exc.headers.get('X-RateLimit-Reset', '0') or 0))}") from None
STATS.rate_limit_retries += 1
_wait_for_rate_limit_reset(int(exc.headers.get("X-RateLimit-Reset", "0") or 0), url)
continue # doesn't count as an attempt
if rate_limited and attempt < retries:
delay = min(int(float(retry_after)), 120) if retry_after else 2 ** attempt
STATS.rate_limit_retries += 1
log.warning("Rate limited (%d), retrying in %ds (attempt %d/%d): %s",
status, delay, attempt + 1, retries, url.split("?")[0])
_sleep_unless_stopped(delay)
attempt += 1
continue
STATS.api_errors += 1
STATS.last_error = f"{status} {message}"[-200:]
log.error("API call failed (HTTP %d): %s\n%s", status, url, message)
raise GitHubAPIError(f"HTTP {status}: {message}", status) from None
except (urllib.error.URLError, TimeoutError, OSError) as exc:
if attempt < retries:
delay = 2 ** attempt
log.warning("Network error, retrying in %ds: %s", delay, exc)
_sleep_unless_stopped(delay)
attempt += 1
continue
STATS.api_errors += 1
STATS.last_error = f"network: {exc}"[-200:]
log.error("API call failed (network): %s\n%s", url, exc)
raise GitHubAPIError(f"Network error: {exc}") from None
raise GitHubAPIError("unreachable") # keeps type checkers happy
def _next_link(headers) -> str | None:
link = headers.get("Link") if headers is not None else None
if not link:
return None
for part in link.split(","):
url, _, rel = part.partition(";")
if 'rel="next"' in rel:
return url.strip().strip("<>")
return None
def api_get(path: str, params: dict | None = None, **kw) -> object:
return _api_request(f"{GITHUB_API}/{path.lstrip('/')}", params, **kw)[0]
def api_get_all(path: str, params: dict | None = None, *, list_key: str | None = None,
max_items: int | None = None, on_page=None) -> list:
"""Follow `Link: rel=next` pagination. `list_key` unwraps envelope responses
like {"workflow_runs": [...]}; `max_items` stops early. `on_page(fetched, total)`
is called after each page with the envelope's `total_count` (None if absent)."""
url: str | None = f"{GITHUB_API}/{path.lstrip('/')}"
params = {**(params or {}), "per_page": 100}
items: list = []
while url:
data, headers = _api_request(url, params)
params = None # the next link already carries the query string
page = data.get(list_key, []) if list_key else data
items.extend(page)
if on_page is not None:
on_page(len(items), data.get("total_count") if list_key else None)
if max_items is not None and len(items) >= max_items:
return items[:max_items]
if list_key and not page:
break
url = _next_link(headers)
return items
def verify_token(token: str) -> str:
"""Return the login for `token`, raising AuthError if GitHub rejects it."""
user = _api_request(f"{GITHUB_API}/user", token=token, retries=1, count=False)[0]
return str((user or {}).get("login", ""))
# -- OAuth device flow (https://docs.github.com/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps#device-flow)
def _oauth_post(url: str, data: dict) -> dict:
req = urllib.request.Request(
url, data=urllib.parse.urlencode(data).encode(), method="POST",
headers={"Accept": "application/json", "User-Agent": USER_AGENT},
)