readthrough 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. readthrough/__init__.py +8 -0
  2. readthrough/__main__.py +3 -0
  3. readthrough/agents.py +344 -0
  4. readthrough/analyze.py +537 -0
  5. readthrough/assets/SKILL.md +86 -0
  6. readthrough/assets/defaults.toml +143 -0
  7. readthrough/assets/profile-reference.md +133 -0
  8. readthrough/assets/vendor/README.md +22 -0
  9. readthrough/assets/vendor/cose-base.js +3214 -0
  10. readthrough/assets/vendor/cytoscape-fcose.js +1549 -0
  11. readthrough/assets/vendor/cytoscape.min.js +31 -0
  12. readthrough/assets/vendor/layout-base.js +5230 -0
  13. readthrough/assets/vendor/licenses/cose-base-LICENSE +21 -0
  14. readthrough/assets/vendor/licenses/cytoscape-LICENSE +19 -0
  15. readthrough/assets/vendor/licenses/cytoscape-fcose-LICENSE +19 -0
  16. readthrough/assets/vendor/licenses/dompurify-LICENSE +202 -0
  17. readthrough/assets/vendor/licenses/layout-base-LICENSE +21 -0
  18. readthrough/assets/vendor/licenses/lucide-LICENSE +15 -0
  19. readthrough/assets/vendor/licenses/marked-LICENSE +44 -0
  20. readthrough/assets/vendor/lucide-icons.js +36 -0
  21. readthrough/assets/vendor/marked.umd.js +82 -0
  22. readthrough/assets/vendor/purify.min.js +7 -0
  23. readthrough/assets/web/dashboard.css +202 -0
  24. readthrough/assets/web/dashboard.html +48 -0
  25. readthrough/assets/web/dashboard.js +937 -0
  26. readthrough/assets/web/setup.css +57 -0
  27. readthrough/assets/web/setup.html +28 -0
  28. readthrough/assets/web/setup.js +342 -0
  29. readthrough/assets/web/theme.css +36 -0
  30. readthrough/assistants.py +699 -0
  31. readthrough/brief.py +145 -0
  32. readthrough/build.py +616 -0
  33. readthrough/ci.py +107 -0
  34. readthrough/cli.py +958 -0
  35. readthrough/config.py +533 -0
  36. readthrough/contract.py +394 -0
  37. readthrough/engine.py +230 -0
  38. readthrough/faults.py +92 -0
  39. readthrough/files.py +110 -0
  40. readthrough/forges/__init__.py +614 -0
  41. readthrough/forges/azure_devops.py +658 -0
  42. readthrough/forges/forgejo.py +300 -0
  43. readthrough/forges/github.py +487 -0
  44. readthrough/forges/gitlab.py +335 -0
  45. readthrough/ledger.py +61 -0
  46. readthrough/limits.py +26 -0
  47. readthrough/logs.py +169 -0
  48. readthrough/membership.py +76 -0
  49. readthrough/model.py +177 -0
  50. readthrough/onboard.py +551 -0
  51. readthrough/onboard_model.py +319 -0
  52. readthrough/process.py +169 -0
  53. readthrough/profile.py +699 -0
  54. readthrough/py.typed +0 -0
  55. readthrough/registry.py +157 -0
  56. readthrough/review.py +394 -0
  57. readthrough/rules.py +111 -0
  58. readthrough/runtimes/__init__.py +297 -0
  59. readthrough/runtimes/anthropic.py +278 -0
  60. readthrough/runtimes/copilot.py +313 -0
  61. readthrough/runtimes/openai.py +307 -0
  62. readthrough/serve.py +817 -0
  63. readthrough/study.py +327 -0
  64. readthrough/system.py +205 -0
  65. readthrough/terminals.py +168 -0
  66. readthrough/tuning.py +266 -0
  67. readthrough/usage.py +169 -0
  68. readthrough/web_setup.py +635 -0
  69. readthrough-0.4.0.dist-info/METADATA +123 -0
  70. readthrough-0.4.0.dist-info/RECORD +73 -0
  71. readthrough-0.4.0.dist-info/WHEEL +4 -0
  72. readthrough-0.4.0.dist-info/entry_points.txt +2 -0
  73. readthrough-0.4.0.dist-info/licenses/LICENSE +21 -0
readthrough/serve.py ADDED
@@ -0,0 +1,817 @@
1
+ """The live dashboard: a localhost server that keeps every onboarded repo fresh and pushes changes to the page.
2
+
3
+ Each repo lives under ``/r/<forge>/<owner>/<name>/`` (its slug: ``/r/github/microsoft/vscode/``) and gets the
4
+ same single-file dashboard as a static build, plus a small API (paths relative to the repo prefix):
5
+
6
+ GET / the dashboard
7
+ GET /api/data the current payload
8
+ GET /api/events Server-Sent Events: data, ledger, sessions, status, study
9
+ GET /api/study/<n> the PR's study log; GET /api/brief/<n> its brief
10
+ POST /api/refresh rebuild now
11
+ POST /api/review/<n> start or resume the deep-review session for a PR
12
+ POST /api/ledger/<n> {"status": "understood" | "reviewed" | ... | null}
13
+ POST /api/study/<n>[/ask] add to the study log, or ask the study assistant
14
+
15
+ ``GET /api/health`` (no prefix) is the liveness probe; ``/`` redirects to the default repo, or to ``/setup``
16
+ when nothing is onboarded yet. ``/setup`` is browser onboarding and repo settings; its API lives under
17
+ ``/api/setup/`` (see web_setup.py).
18
+
19
+ Only 127.0.0.1 is bound. Requests must carry a matching Host header (blocks DNS rebinding), and
20
+ POSTs must carry the per-run token embedded in the page plus a same-origin Origin, so other sites
21
+ in your browser can't drive it.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import contextlib
27
+ import datetime as dt
28
+ import json
29
+ import logging
30
+ import queue
31
+ import random
32
+ import re
33
+ import secrets
34
+ import socket
35
+ import sys
36
+ import threading
37
+ import time
38
+ import urllib.parse
39
+ import urllib.request
40
+ from http import HTTPStatus
41
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
42
+ from typing import Any
43
+
44
+ from readthrough import __version__, contract, ledger, logs, review, study
45
+ from readthrough.build import (
46
+ DATA_SCHEMA,
47
+ BuildFailed,
48
+ apply_session_changes,
49
+ build,
50
+ mark_seen,
51
+ refresh_sessions,
52
+ render_html,
53
+ render_setup,
54
+ session_changes,
55
+ )
56
+ from readthrough.config import DEFAULT_HOME, Config, load_settings
57
+ from readthrough.engine import Busy, StudyEngine, public_entries
58
+ from readthrough.faults import ForgeError
59
+ from readthrough.files import mtime, stamp
60
+ from readthrough.limits import MAX_DISCARD_BYTES, MAX_REQUEST_BYTES
61
+ from readthrough.model import PR_NUMBER
62
+ from readthrough.web_setup import Conflict, SetupError, SetupService
63
+
64
+ log = logging.getLogger(__name__)
65
+
66
+
67
+ class BodyTooLarge(ValueError):
68
+ pass
69
+
70
+
71
+ def _now() -> str:
72
+ return dt.datetime.now(dt.UTC).isoformat(timespec="seconds")
73
+
74
+
75
+ def page_csp(nonce: str) -> str:
76
+ """Only our own nonce'd scripts run. PR descriptions are third-party HTML, so this matters."""
77
+ return (
78
+ f"default-src 'none'; script-src 'nonce-{nonce}'; style-src 'unsafe-inline'; img-src data: https:; "
79
+ "connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
80
+ )
81
+
82
+
83
+ def base_url(port: int) -> str:
84
+ return f"http://127.0.0.1:{port}/"
85
+
86
+
87
+ def repo_url(port: int, slug: str) -> str:
88
+ return f"{base_url(port)}r/{slug}/"
89
+
90
+
91
+ def server_url(cfg: Config) -> str:
92
+ """The live page for this repo."""
93
+ return repo_url(cfg.port, cfg.slug)
94
+
95
+
96
+ def server_alive(port: int, *, timeout: float = 0.5) -> dict[str, Any] | None:
97
+ """The running server's health info, or None."""
98
+ try:
99
+ with urllib.request.urlopen(f"{base_url(port)}api/health", timeout=timeout) as resp: # noqa: S310 - a fixed http://127.0.0.1 URL
100
+ info = json.loads(resp.read())
101
+ return info if info.get("app") == "readthrough" else None
102
+ except (OSError, ValueError):
103
+ return None
104
+
105
+
106
+ class Dashboard:
107
+ """Owns the payload and the background threads; the HTTP handler only reads and delegates."""
108
+
109
+ def __init__(self, cfg: Config, *, with_diffs: bool = True, seed: int | None = None) -> None:
110
+ self.cfg = cfg
111
+ self.with_diffs = with_diffs
112
+ # Refresh jitter spreads repos' refreshes apart. Its own generator so a seed makes it reproducible.
113
+ self.jitter = random.Random(seed) # noqa: S311 - timing jitter, not security
114
+ self.token = "" # set by the server, shared by every repo it serves
115
+ self.instance = ""
116
+ self.payload: dict[str, Any] = {}
117
+ self._lock = threading.Lock()
118
+ self._build_lock = threading.Lock()
119
+ self._wake = threading.Event()
120
+ self._stop = threading.Event()
121
+ self._clients: set[queue.Queue[tuple[str, Any]]] = set()
122
+ # error is None or {"id", "message", "step", "at"}; the dashboard shows it, and so does /api/health.
123
+ self.status: dict[str, Any] = {
124
+ "building": False, "error": None, "last_build": None, "next_build": None,
125
+ "last_success": None, "consecutive_failures": 0, "warnings": 0,
126
+ } # fmt: skip
127
+ self._seen = {"data": 0.0, "ledger": 0.0}
128
+ self._study_seen: dict[str, tuple[float, int]] = {} # per log file: (mtime, size) last seen
129
+ self._wake_reason = "scheduled"
130
+ self._start_delay = 0.0
131
+ self.engine = StudyEngine(cfg, self._engine_event, self.pr_info, lambda: self.snapshot().get("components", []))
132
+
133
+ def reconfigure(self, cfg: Config) -> None:
134
+ """A fresh Config for the same repo after config.toml changed: the threads read ``self.cfg`` on each
135
+ pass, and the study engine (and through it the assistant) must see the same one."""
136
+ self.cfg = cfg
137
+ self.engine.reconfigure(cfg)
138
+
139
+ def _engine_event(self, event: str, data: Any) -> None:
140
+ # Keep the payload's per-PR summary current so a page reload shows the latest progress.
141
+ if event == "study" and data.get("type") == "entry":
142
+ info = self.pr_info(data["pr"])
143
+ if info is not None:
144
+ info["study"] = data["summary"]
145
+ self._study_seen[f"pr-{data['pr']}.jsonl"] = stamp(study.log_path(self.cfg, data["pr"]))
146
+ self.broadcast(event, data)
147
+
148
+ # ---- state
149
+
150
+ def load(self) -> bool:
151
+ if not self.cfg.data_path.exists():
152
+ return False
153
+ try:
154
+ payload = json.loads(self.cfg.data_path.read_text(encoding="utf-8"))
155
+ except ValueError as exc:
156
+ log.warning("Ignoring unreadable %s (%s); it will be rebuilt", self.cfg.data_path, exc)
157
+ return False
158
+ if payload.get("schema", DATA_SCHEMA) != DATA_SCHEMA:
159
+ log.warning("Ignoring %s: written for data schema %s, this version reads %s; it will be rebuilt",
160
+ self.cfg.data_path, payload.get("schema"), DATA_SCHEMA) # fmt: skip
161
+ return False
162
+ payload["ledger"] = ledger.load(self.cfg.ledger_path)
163
+ refresh_sessions(payload, self.cfg)
164
+ with self._lock:
165
+ self.payload = payload
166
+ self._seen = {"data": mtime(self.cfg.data_path), "ledger": mtime(self.cfg.ledger_path)}
167
+ self.status["last_build"] = payload.get("generated")
168
+ return True
169
+
170
+ def snapshot(self) -> dict[str, Any]:
171
+ with self._lock:
172
+ return self.payload
173
+
174
+ # ---- events
175
+
176
+ def subscribe(self) -> queue.Queue[tuple[str, Any]]:
177
+ q: queue.Queue[tuple[str, Any]] = queue.Queue(maxsize=100)
178
+ with self._lock:
179
+ self._clients.add(q)
180
+ return q
181
+
182
+ def unsubscribe(self, q: queue.Queue[tuple[str, Any]]) -> None:
183
+ with self._lock:
184
+ self._clients.discard(q)
185
+
186
+ def broadcast(self, event: str, data: Any) -> None:
187
+ """Queue an event for every connected page. A page that can't keep up (a long streamed reply, a
188
+ throttled tab) loses what was queued and is told so with one ``resync``, so it fetches everything again
189
+ rather than quietly showing a stale page while its connection looks healthy."""
190
+ if event not in contract.EVENTS:
191
+ raise ValueError(f"{event!r} is not an event the page knows (contract.EVENTS)")
192
+ with self._lock:
193
+ clients = list(self._clients)
194
+ for q in clients:
195
+ try:
196
+ q.put_nowait((event, data))
197
+ except queue.Full:
198
+ with contextlib.suppress(queue.Empty):
199
+ while True:
200
+ q.get_nowait()
201
+ with contextlib.suppress(queue.Full):
202
+ q.put_nowait(("resync", {"reason": "this page fell behind the server's events"}))
203
+
204
+ def _set_status(self, **changes: Any) -> None:
205
+ self.status.update(changes)
206
+ self.broadcast("status", self.status)
207
+
208
+ # ---- background work
209
+
210
+ def rebuild(self) -> bool:
211
+ """Build once. The build logs its own failure; here we only record it for the dashboard and /api/health."""
212
+ if not self._build_lock.acquire(blocking=False):
213
+ return False
214
+ try:
215
+ self._set_status(building=True)
216
+ try:
217
+ build(self.cfg, with_diffs=self.with_diffs)
218
+ self.load()
219
+ except BuildFailed as exc:
220
+ self._failed(exc.error_id, exc.reason, exc.step)
221
+ return False
222
+ except Exception as exc: # loading the result failed: not GitHub's fault, so keep the traceback
223
+ error_id = logs.new_id()
224
+ with logs.context(self.cfg.repo):
225
+ log.exception("Loading the new build failed [error %s]", error_id, extra={"error_id": error_id})
226
+ self._failed(error_id, f"{type(exc).__name__}: {exc}", "loading the build")
227
+ return False
228
+ self._set_status(
229
+ building=False, error=None, consecutive_failures=0, last_success=_now(),
230
+ last_build=self.payload.get("generated"), warnings=len(self.payload.get("warnings") or []),
231
+ ) # fmt: skip
232
+ self.broadcast("data", {"generated": self.payload.get("generated")})
233
+ return True
234
+ finally:
235
+ self._build_lock.release()
236
+
237
+ def _failed(self, error_id: str, message: str, step: str) -> None:
238
+ self._set_status(
239
+ building=False, consecutive_failures=self.status["consecutive_failures"] + 1,
240
+ error={"id": error_id, "message": message[:400], "step": step, "at": _now()},
241
+ ) # fmt: skip
242
+
243
+ def request_refresh(self, reason: str) -> None:
244
+ self._wake_reason = reason
245
+ self._wake.set()
246
+
247
+ def next_wait(self) -> float:
248
+ """Seconds until the next refresh: the interval (with jitter), or sooner after a failure."""
249
+ t = self.cfg.tuning.server
250
+ interval = (
251
+ max(1, self.cfg.refresh_minutes) * 60 * (1 + self.jitter.uniform(-t.refresh_jitter, t.refresh_jitter))
252
+ )
253
+ failures = self.status["consecutive_failures"]
254
+ if failures and failures <= len(t.retry_after_failure_minutes):
255
+ return min(interval, t.retry_after_failure_minutes[failures - 1] * 60)
256
+ return interval
257
+
258
+ def refresh_loop(self) -> None:
259
+ with logs.context(self.cfg.repo):
260
+ if self._start_delay and not self._stop.wait(self._start_delay):
261
+ log.debug("first refresh after a %.0fs stagger", self._start_delay)
262
+ while not self._stop.is_set():
263
+ wait = self.next_wait()
264
+ self.status["next_build"] = time.time() + wait
265
+ if self.status["consecutive_failures"]:
266
+ log.info("next attempt in %.0fs (after %d failed refresh%s)", wait, self.status["consecutive_failures"],
267
+ "es" if self.status["consecutive_failures"] > 1 else "") # fmt: skip
268
+ woken = self._wake.wait(timeout=wait)
269
+ self._wake.clear()
270
+ reason, self._wake_reason = (self._wake_reason if woken else "scheduled"), "scheduled"
271
+ if not self._stop.is_set():
272
+ log.info("refreshing (%s)", reason)
273
+ self.rebuild()
274
+
275
+ def watch_loop(self) -> None:
276
+ """Pick up changes made outside the server: `readthrough build`, `readthrough ledger`, agent sessions."""
277
+ while not self._stop.wait(self.cfg.tuning.server.watch_seconds):
278
+ try:
279
+ self._watch_once()
280
+ except Exception:
281
+ log.exception("Watcher failed")
282
+
283
+ def _watch_once(self) -> None:
284
+ data_m, ledger_m = mtime(self.cfg.data_path), mtime(self.cfg.ledger_path)
285
+ if data_m != self._seen["data"] and not self._build_lock.locked():
286
+ log.info("data.json changed outside the server; reloading")
287
+ self.load()
288
+ self.broadcast("data", {"generated": self.payload.get("generated")})
289
+ return
290
+ if ledger_m != self._seen["ledger"]:
291
+ self._seen["ledger"] = ledger_m
292
+ entries = ledger.load(self.cfg.ledger_path)
293
+ with self._lock:
294
+ self.payload["ledger"] = entries
295
+ self.broadcast("ledger", entries)
296
+ # Look without the lock (the scan takes real time on a machine with many sessions), apply under it.
297
+ payload = self.snapshot()
298
+ changed = session_changes(payload, self.cfg) if payload else {}
299
+ if changed:
300
+ with self._lock:
301
+ apply_session_changes(self.payload, changed)
302
+ self.broadcast("sessions", changed)
303
+ self._watch_study()
304
+
305
+ def _watch_study(self) -> None:
306
+ """Pick up study-log appends made outside the dashboard, e.g. `readthrough study N --note` from a terminal."""
307
+ folder = self.cfg.study_dir
308
+ if not folder.is_dir():
309
+ return
310
+ for path in folder.glob("pr-*.jsonl"):
311
+ seen = stamp(path)
312
+ if self._study_seen.get(path.name) == seen:
313
+ continue
314
+ first_look = path.name not in self._study_seen
315
+ self._study_seen[path.name] = seen
316
+ if not first_look:
317
+ self._study_changed(int(path.stem.split("-")[1]), reload=True)
318
+
319
+ def _study_changed(self, number: int, *, reload: bool = False) -> dict[str, Any]:
320
+ summary = study.summarize(study.load(self.cfg, number))
321
+ info = self.pr_info(number)
322
+ if info is not None:
323
+ info["study"] = summary
324
+ if reload:
325
+ self.broadcast("study", {"pr": number, "type": "reload", "summary": summary})
326
+ self._study_seen[f"pr-{number}.jsonl"] = stamp(study.log_path(self.cfg, number))
327
+ return summary
328
+
329
+ def start(self, *, build_now: bool = False, delay: float = 0.0) -> None:
330
+ """Start the refresh and watch threads. ``delay`` staggers repos so they don't all hit GitHub at once."""
331
+ self._start_delay = delay
332
+ for target in (self.refresh_loop, self.watch_loop):
333
+ threading.Thread(target=target, daemon=True, name=f"{target.__name__}:{self.cfg.repo}").start()
334
+ if build_now:
335
+ self.request_refresh("first build")
336
+
337
+ def stop(self) -> None:
338
+ self._stop.set()
339
+ self._wake.set()
340
+ self.engine.stop()
341
+
342
+ # ---- actions
343
+
344
+ def pr_info(self, number: int) -> dict[str, Any] | None:
345
+ return next((p for p in self.snapshot().get("prs", []) if p["number"] == number), None)
346
+
347
+ def study_state(self, number: int) -> dict[str, Any]:
348
+ entries = study.load(self.cfg, number)
349
+ return {
350
+ "entries": public_entries(entries),
351
+ "summary": study.summarize(entries),
352
+ "engine": {**self.engine.engine_info(), "busy": self.engine.busy(number)},
353
+ }
354
+
355
+ def add_study(self, number: int, body: dict[str, Any]) -> dict[str, Any]:
356
+ """Entries the learner writes directly, without asking the assistant anything."""
357
+ kind = body.get("kind")
358
+ if kind not in contract.STUDY_ADD_KINDS:
359
+ raise ValueError("you can add a prediction, teachback, reflection, note, or finding")
360
+ if self.pr_info(number) is None:
361
+ raise ValueError(f"#{number} isn't an open PR in the current data")
362
+ fields = {
363
+ k: body[k]
364
+ for k in ("text", "section", "severity", "summary", "path", "line")
365
+ if body.get(k) not in (None, "")
366
+ }
367
+ if kind == "reflection" and body.get("qid"):
368
+ if not isinstance(body["qid"], str):
369
+ raise ValueError("qid must be a question id")
370
+ fields["qid"] = body["qid"]
371
+ if kind == "prediction" and body.get("skipped") is True:
372
+ fields = {"text": "Skipped the prediction.", "skipped": True}
373
+ if kind == "note" and body.get("pinned") is not None:
374
+ if not isinstance(body["pinned"], int):
375
+ raise ValueError("pinned must be an entry id")
376
+ fields["pinned"] = body["pinned"]
377
+ entry = study.append(self.cfg, number, kind, by="you", **fields)
378
+ study.refresh_brief(self.cfg, number)
379
+ summary = self._study_changed(number)
380
+ self.broadcast("study", {"pr": number, "type": "entry", "entry": entry, "summary": summary})
381
+ return entry
382
+
383
+ def ask(self, number: int, body: dict[str, Any]) -> None:
384
+ self.engine.submit(number, str(body.get("action", "chat")), str(body.get("text") or ""), body.get("qid"))
385
+
386
+ def brief(self, number: int) -> str:
387
+ path = self.cfg.briefs_dir / f"pr-{number}.md"
388
+ if not path.exists():
389
+ raise ValueError(f"No brief for #{number}")
390
+ return path.read_text(encoding="utf-8")
391
+
392
+ def head_of(self, number: int) -> str | None:
393
+ return next((p["head"] for p in self.snapshot().get("prs", []) if p["number"] == number), None)
394
+
395
+ def set_status(self, number: int, status: str | None) -> dict[str, Any]:
396
+ if status is None:
397
+ ledger.clear_status(self.cfg.ledger_path, number)
398
+ else:
399
+ ledger.record(self.cfg.ledger_path, number, status=status, head=self.head_of(number) or "")
400
+ self._watch_once()
401
+ return self.snapshot()["ledger"]
402
+
403
+ def launch_review(self, number: int, session_id: str | None = None) -> dict[str, Any]:
404
+ entry = ledger.load(self.cfg.ledger_path).get(str(number))
405
+ launch = review.plan_review(self.cfg, number, ledger_entry=entry, session_id=session_id)
406
+ terminal = review.launch_in_terminal(launch, self.cfg)
407
+ log.info(
408
+ "%s %s session %s for #%d in %s",
409
+ "Resumed" if launch.resuming else "Started", launch.agent, launch.session_id, number, terminal,
410
+ ) # fmt: skip
411
+ return {"session": launch.session_id, "resuming": launch.resuming, "agent": launch.agent}
412
+
413
+
414
+ class Handler(BaseHTTPRequestHandler):
415
+ server_version = f"readthrough/{__version__}"
416
+
417
+ @property
418
+ def app(self) -> DashboardServer:
419
+ """``self.server`` with its real type: a Handler only ever runs inside a DashboardServer."""
420
+ server = self.server
421
+ if not isinstance(server, DashboardServer): # pragma: no cover - a programming error, not a request error
422
+ raise TypeError("Handler is bound to the wrong server type")
423
+ return server
424
+
425
+ def log_message(self, format: str, *args: Any) -> None: # noqa: A002 - BaseHTTPRequestHandler's signature
426
+ log.debug("%s %s", self.address_string(), format % args)
427
+
428
+ def _host_ok(self) -> bool:
429
+ port = self.app.server_address[1]
430
+ return self.headers.get("Host", "") in (f"127.0.0.1:{port}", f"localhost:{port}")
431
+
432
+ def _route(self) -> tuple[Dashboard | None, str]:
433
+ return self.app.route(self.path.split("?", 1)[0])
434
+
435
+ def _send(self, status: int, body: bytes, content_type: str, headers: dict[str, str] | None = None) -> None:
436
+ self.send_response(status)
437
+ self.send_header("Content-Type", content_type)
438
+ self.send_header("Content-Length", str(len(body)))
439
+ self.send_header("Cache-Control", "no-store")
440
+ self.send_header("X-Content-Type-Options", "nosniff")
441
+ for key, value in (headers or {}).items():
442
+ self.send_header(key, value)
443
+ self.end_headers()
444
+ self.wfile.write(body)
445
+
446
+ def _json(self, data: Any, status: int = HTTPStatus.OK) -> None:
447
+ self._send(status, json.dumps(data).encode(), "application/json")
448
+
449
+ def _error(self, status: int, message: str) -> None:
450
+ self._json({"error": message}, status)
451
+
452
+ def do_GET(self) -> None:
453
+ if not self._host_ok():
454
+ return self._error(HTTPStatus.FORBIDDEN, "bad host")
455
+ dashboard, path = self._route()
456
+ if dashboard is None:
457
+ if path == "/api/health":
458
+ return self._json({"app": "readthrough", "version": __version__,
459
+ "repos": [r["slug"] for r in self.app.repo_names()],
460
+ "status": self.app.repo_status()}) # fmt: skip
461
+ if path in ("/", "/index.html"):
462
+ return self._front_page()
463
+ if path == "/setup":
464
+ return self._setup_page()
465
+ if m := re.fullmatch(r"/setup/preview/([0-9a-f]{32})", path):
466
+ payload = self.app.setup.preview_payload(m.group(1))
467
+ if payload is None:
468
+ return self._error(HTTPStatus.NOT_FOUND, "preview expired; make a new one")
469
+ nonce = secrets.token_urlsafe(16)
470
+ html = render_html(payload, nonce=nonce).encode()
471
+ return self._send(
472
+ HTTPStatus.OK, html, "text/html; charset=utf-8", {"Content-Security-Policy": page_csp(nonce)}
473
+ )
474
+ if path.startswith("/api/setup/"):
475
+ query = dict(urllib.parse.parse_qsl(self.path.partition("?")[2]))
476
+ return self._setup_call(lambda: self.app.setup.get(path, query))
477
+ return self._error(HTTPStatus.NOT_FOUND, "not found")
478
+ if path in ("/", "/index.html"):
479
+ return self._page(dashboard)
480
+ if path == "/api/data":
481
+ return self._json(dashboard.snapshot())
482
+ if path == "/api/events":
483
+ return self._events(dashboard)
484
+ try:
485
+ if m := re.fullmatch(rf"/api/study/({PR_NUMBER})", path):
486
+ return self._json(dashboard.study_state(int(m.group(1))))
487
+ if m := re.fullmatch(rf"/api/brief/({PR_NUMBER})", path):
488
+ return self._json({"markdown": dashboard.brief(int(m.group(1)))})
489
+ except ValueError as exc:
490
+ return self._error(HTTPStatus.NOT_FOUND, str(exc))
491
+ return self._error(HTTPStatus.NOT_FOUND, "not found")
492
+
493
+ def _front_page(self) -> None:
494
+ names = self.app.repo_names()
495
+ if names:
496
+ target = self.app.default_repo() or names[0]["slug"]
497
+ self.send_response(HTTPStatus.FOUND)
498
+ self.send_header("Location", f"/r/{urllib.parse.quote(target)}/")
499
+ self.send_header("Content-Length", "0")
500
+ self.end_headers()
501
+ return
502
+ self.send_response(HTTPStatus.FOUND)
503
+ self.send_header("Location", "/setup")
504
+ self.send_header("Content-Length", "0")
505
+ self.end_headers()
506
+
507
+ def _setup_page(self) -> None:
508
+ nonce = secrets.token_urlsafe(16)
509
+ live = {"token": self.app.token, "instance": self.app.instance, "repos": self.app.repo_names()}
510
+ html = render_setup(live, nonce).encode()
511
+ self._send(HTTPStatus.OK, html, "text/html; charset=utf-8", {"Content-Security-Policy": page_csp(nonce)})
512
+
513
+ def _setup_call(self, call: Any) -> None:
514
+ try:
515
+ return self._json(call())
516
+ except Conflict as exc:
517
+ return self._error(HTTPStatus.CONFLICT, str(exc))
518
+ except SetupError as exc:
519
+ return self._error(HTTPStatus.BAD_REQUEST, str(exc))
520
+ except LookupError as exc:
521
+ return self._error(HTTPStatus.NOT_FOUND, str(exc))
522
+ except ForgeError as exc: # the forge refused or failed: that's the answer, not a crash
523
+ return self._error(HTTPStatus.BAD_GATEWAY, f"{exc.reason} ({exc.what})" if exc.what else exc.reason)
524
+
525
+ def handle_one_request(self) -> None:
526
+ """Whatever escapes a handler is logged once, with an error id, and answered; never a traceback on
527
+ stderr and a dropped connection, which is what ``socketserver`` does by default."""
528
+ try:
529
+ super().handle_one_request()
530
+ except (ConnectionError, TimeoutError):
531
+ raise # the client went away; nothing to answer
532
+ except Exception as exc:
533
+ error_id = logs.new_id()
534
+ log.exception("Request %s failed [error %s]", self.path, error_id, extra={"error_id": error_id})
535
+ with contextlib.suppress(Exception): # the response may be half-written already
536
+ self._error(HTTPStatus.INTERNAL_SERVER_ERROR, f"{type(exc).__name__}: {exc} [error {error_id}]")
537
+
538
+ def _page(self, dashboard: Dashboard) -> None:
539
+ snapshot = dashboard.snapshot()
540
+ if not snapshot:
541
+ body = f"<!doctype html><title>readthrough</title><meta http-equiv=refresh content=5><p>Building {dashboard.cfg.repo} for the first time…".encode()
542
+ return self._send(HTTPStatus.OK, body, "text/html; charset=utf-8")
543
+ live = {
544
+ "token": self.app.token,
545
+ "instance": self.app.instance,
546
+ "base": f"/r/{urllib.parse.quote(dashboard.cfg.slug)}",
547
+ "repos": self.app.repo_names(),
548
+ "refresh_minutes": dashboard.cfg.refresh_minutes,
549
+ "status": dashboard.status,
550
+ }
551
+ nonce = secrets.token_urlsafe(16)
552
+ html = render_html(snapshot, live=live, nonce=nonce).encode()
553
+ mark_seen(dashboard.cfg, snapshot)
554
+ self._send(HTTPStatus.OK, html, "text/html; charset=utf-8", {"Content-Security-Policy": page_csp(nonce)})
555
+ return None
556
+
557
+ def do_POST(self) -> None:
558
+ # Read the body before any early rejection: on Windows, closing a socket with unread request
559
+ # data sends a reset, and the client sees a connection error instead of our 403.
560
+ try:
561
+ raw = self._read_body()
562
+ except ValueError as exc:
563
+ self.close_connection = True
564
+ too_large = isinstance(exc, BodyTooLarge)
565
+ return self._error(HTTPStatus.REQUEST_ENTITY_TOO_LARGE if too_large else HTTPStatus.BAD_REQUEST, str(exc))
566
+ if not self._host_ok():
567
+ return self._error(HTTPStatus.FORBIDDEN, "bad host")
568
+ origin = self.headers.get("Origin")
569
+ if origin is not None and origin != f"http://{self.headers['Host']}":
570
+ return self._error(HTTPStatus.FORBIDDEN, "bad origin")
571
+ if not secrets.compare_digest(self.headers.get("X-Readthrough-Token", ""), self.app.token):
572
+ return self._error(HTTPStatus.FORBIDDEN, "bad token (reload the page)")
573
+ dashboard, path = self._route()
574
+ if dashboard is None:
575
+ if path.startswith("/api/setup/"):
576
+ try:
577
+ setup_body = self._parse_json(raw)
578
+ except ValueError as exc:
579
+ return self._error(HTTPStatus.BAD_REQUEST, str(exc))
580
+ return self._setup_call(lambda: self.app.setup.post(path, setup_body))
581
+ return self._error(HTTPStatus.NOT_FOUND, "not found")
582
+ try:
583
+ body = self._parse_json(raw)
584
+ if path == "/api/refresh":
585
+ dashboard.request_refresh(f"requested from {self.headers.get('User-Agent', '?')[:60]}")
586
+ return self._json({"ok": True})
587
+ if m := re.fullmatch(rf"/api/review/({PR_NUMBER})", path):
588
+ sid = body.get("session")
589
+ if sid is not None and not (isinstance(sid, str) and re.fullmatch(r"[0-9a-f-]{36}", sid)):
590
+ return self._error(HTTPStatus.BAD_REQUEST, "bad session id")
591
+ return self._json(dashboard.launch_review(int(m.group(1)), sid))
592
+ if m := re.fullmatch(rf"/api/ledger/({PR_NUMBER})", path):
593
+ status = body.get("status")
594
+ if status is not None and status not in ledger.STATUSES:
595
+ return self._error(HTTPStatus.BAD_REQUEST, "unknown status")
596
+ return self._json(dashboard.set_status(int(m.group(1)), status))
597
+ if m := re.fullmatch(rf"/api/study/({PR_NUMBER})", path):
598
+ return self._json(dashboard.add_study(int(m.group(1)), body))
599
+ if m := re.fullmatch(rf"/api/study/({PR_NUMBER})/ask", path):
600
+ dashboard.ask(int(m.group(1)), body)
601
+ return self._json({"ok": True}, HTTPStatus.ACCEPTED)
602
+ except Busy as exc:
603
+ return self._error(HTTPStatus.CONFLICT, str(exc))
604
+ except (RuntimeError, ValueError) as exc:
605
+ return self._error(HTTPStatus.BAD_REQUEST, str(exc))
606
+ return self._error(HTTPStatus.NOT_FOUND, "not found")
607
+
608
+ def _read_body(self) -> bytes:
609
+ try:
610
+ length = int(self.headers.get("Content-Length") or 0)
611
+ except ValueError:
612
+ raise ValueError("invalid Content-Length") from None
613
+ if length > MAX_REQUEST_BYTES:
614
+ if length <= MAX_DISCARD_BYTES:
615
+ while length > 0:
616
+ chunk = self.rfile.read(min(length, 65536))
617
+ if not chunk:
618
+ break
619
+ length -= len(chunk)
620
+ raise BodyTooLarge(f"body too large (the limit is {MAX_REQUEST_BYTES} bytes)")
621
+ return self.rfile.read(length) if length > 0 else b""
622
+
623
+ @staticmethod
624
+ def _parse_json(raw: bytes) -> dict[str, Any]:
625
+ data = json.loads(raw) if raw else {}
626
+ if not isinstance(data, dict):
627
+ raise ValueError("expected a JSON object") # noqa: TRY004 - bad input, reported as a 400
628
+ return data
629
+
630
+ def _events(self, dashboard: Dashboard) -> None:
631
+ self.send_response(HTTPStatus.OK)
632
+ self.send_header("Content-Type", "text/event-stream")
633
+ self.send_header("Cache-Control", "no-store")
634
+ self.end_headers()
635
+ q = dashboard.subscribe()
636
+ try:
637
+ self._event("hello", {"instance": self.app.instance})
638
+ self._event("status", dashboard.status)
639
+ while True:
640
+ try:
641
+ event, data = q.get(timeout=dashboard.cfg.tuning.server.keepalive_seconds)
642
+ except queue.Empty:
643
+ self.wfile.write(b": keepalive\n\n")
644
+ self.wfile.flush()
645
+ continue
646
+ self._event(event, data)
647
+ except OSError:
648
+ pass
649
+ finally:
650
+ dashboard.unsubscribe(q)
651
+
652
+ def _event(self, event: str, data: Any) -> None:
653
+ self.wfile.write(f"event: {event}\ndata: {json.dumps(data)}\n\n".encode())
654
+ self.wfile.flush()
655
+
656
+
657
+ class DashboardServer(ThreadingHTTPServer):
658
+ """Serves every onboarded repo. Follows config.toml, so newly onboarded repos appear without a restart."""
659
+
660
+ daemon_threads = True
661
+ # On Windows SO_REUSEADDR lets a second server bind the same port and silently share traffic.
662
+ allow_reuse_address = sys.platform != "win32"
663
+
664
+ def __init__(
665
+ self, dashboards: list[Dashboard], port: int, *, settings_loader: Any = None, with_diffs: bool = True
666
+ ) -> None:
667
+ self.token = secrets.token_urlsafe(24)
668
+ self.instance = secrets.token_hex(6)
669
+ self.dashboards: dict[str, Dashboard] = {}
670
+ self._lock = threading.Lock()
671
+ self._sync_lock = threading.Lock() # one sync at a time: the setup page and the config watcher both call it
672
+ home = dashboards[0].cfg.home if dashboards else DEFAULT_HOME
673
+ self._settings_loader = settings_loader
674
+ self._with_diffs = with_diffs
675
+ self._watch_seconds = dashboards[0].cfg.tuning.server.watch_seconds if dashboards else 3.0
676
+ self._default: str | None = None
677
+ for dashboard in dashboards:
678
+ self._add(dashboard)
679
+ loader = settings_loader or (lambda: load_settings(home))
680
+ self.setup = SetupService(loader, on_change=lambda: self.sync(loader()))
681
+ super().__init__(("127.0.0.1", port), Handler)
682
+
683
+ def server_bind(self) -> None:
684
+ if sys.platform == "win32":
685
+ self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
686
+ super().server_bind()
687
+
688
+ def _add(self, dashboard: Dashboard) -> None:
689
+ dashboard.token = self.token
690
+ dashboard.instance = self.instance
691
+ with self._lock:
692
+ self.dashboards[dashboard.cfg.slug.lower()] = dashboard
693
+
694
+ def dashboard_for(self, slug: str) -> Dashboard | None:
695
+ with self._lock:
696
+ return self.dashboards.get(slug.lower())
697
+
698
+ def route(self, path: str) -> tuple[Dashboard | None, str]:
699
+ """Split ``/r/<forge>/<owner>/<name>/<rest>`` into the repo's Dashboard and ``/<rest>``.
700
+
701
+ Slugs have as many segments as the forge needs, so the longest known slug that prefixes the path wins.
702
+ """
703
+ if not path.startswith("/r/"):
704
+ return None, path
705
+ path = urllib.parse.unquote(path) # the browser sends "Delivery Team" as Delivery%20Team
706
+ lower = path.lower()
707
+ with self._lock:
708
+ slugs = sorted(self.dashboards, key=len, reverse=True)
709
+ for slug in slugs:
710
+ prefix = f"/r/{slug}"
711
+ if lower == prefix or lower.startswith(prefix + "/"):
712
+ return self.dashboards[slug], path[len(prefix) :] or "/"
713
+ return None, path
714
+
715
+ def repo_names(self) -> list[dict[str, str]]:
716
+ """Each served repo's slug (for URLs) and the name the user knows it by."""
717
+ with self._lock:
718
+ dashboards = list(self.dashboards.values())
719
+ counts: dict[str, int] = {}
720
+ for d in dashboards:
721
+ counts[d.cfg.repo.lower()] = counts.get(d.cfg.repo.lower(), 0) + 1
722
+ return [
723
+ {"slug": d.cfg.slug, "name": d.cfg.repo if counts[d.cfg.repo.lower()] == 1 else d.cfg.slug}
724
+ for d in dashboards
725
+ ]
726
+
727
+ def default_repo(self) -> str | None:
728
+ """The default repo's slug, when it's served."""
729
+ if not self._default:
730
+ return None
731
+ with self._lock:
732
+ dashboards = list(self.dashboards.values())
733
+ want = self._default.lower()
734
+ match = next((d for d in dashboards if want in (d.cfg.slug.lower(), d.cfg.repo.lower())), None)
735
+ return match.cfg.slug if match else None
736
+
737
+ def repo_status(self) -> dict[str, dict[str, Any]]:
738
+ keys = ("building", "error", "last_success", "consecutive_failures", "warnings", "next_build")
739
+ with self._lock:
740
+ return {r.cfg.slug: {k: r.status.get(k) for k in keys} for r in self.dashboards.values()}
741
+
742
+ def sync(self, settings: Any) -> None:
743
+ """Add dashboards for newly onboarded repos and stop those that were removed.
744
+
745
+ Serialized: saving from the setup page calls this and also rewrites config.toml, which the config
746
+ watcher then notices, so two syncs for the same change arrive within seconds of each other. Without
747
+ the lock both could find a repo missing and each start a dashboard for it, one of them an orphan that
748
+ keeps building and broadcasting with no way to stop it.
749
+ """
750
+ with self._sync_lock:
751
+ self._default = settings.default_repo
752
+ wanted = {c.slug.lower(): c for c in settings.all() if c.onboarded}
753
+ with self._lock:
754
+ current = dict(self.dashboards)
755
+ for key, dashboard in current.items():
756
+ if key not in wanted:
757
+ log.info("No longer serving %s", dashboard.cfg.repo)
758
+ dashboard.stop()
759
+ with self._lock:
760
+ self.dashboards.pop(key, None)
761
+ for key, cfg in wanted.items():
762
+ if key not in current:
763
+ log.info("Now serving %s", cfg.repo)
764
+ dashboard = Dashboard(cfg, with_diffs=self._with_diffs)
765
+ self._add(dashboard)
766
+ dashboard.start(build_now=not dashboard.load())
767
+ else:
768
+ current[key].reconfigure(cfg)
769
+
770
+ def watch_config(self, stop: threading.Event) -> None:
771
+ if self._settings_loader is None:
772
+ return
773
+ seen = 0.0
774
+ while not stop.wait(self._watch_seconds):
775
+ try:
776
+ settings = self._settings_loader()
777
+ stamp = mtime(settings.path)
778
+ if stamp != seen:
779
+ seen = stamp
780
+ self.sync(settings)
781
+ except Exception:
782
+ log.exception("Reloading config.toml failed")
783
+
784
+ def stop_all(self) -> None:
785
+ with self._lock:
786
+ dashboards = list(self.dashboards.values())
787
+ for dashboard in dashboards:
788
+ dashboard.stop()
789
+
790
+
791
+ def serve(settings: Any, *, with_diffs: bool = True, on_ready: Any = None, settings_loader: Any = None) -> None:
792
+ configs = [c for c in settings.all() if c.onboarded]
793
+ dashboards = [Dashboard(c, with_diffs=with_diffs) for c in configs]
794
+ try:
795
+ httpd = DashboardServer(dashboards, settings.port, settings_loader=settings_loader, with_diffs=with_diffs)
796
+ except OSError as exc:
797
+ raise RuntimeError(
798
+ f"Can't listen on port {settings.port} ({exc}). Is another program using it? Set `port` in config.toml."
799
+ ) from exc
800
+ httpd.sync(settings)
801
+ stop = threading.Event()
802
+ threading.Thread(target=httpd.watch_config, args=(stop,), daemon=True, name="config-watch").start()
803
+ stagger = settings.tuning.server.start_stagger_seconds
804
+ for i, dashboard in enumerate(dashboards):
805
+ dashboard.start(build_now=not dashboard.load(), delay=i * stagger)
806
+ log.info("Live dashboard at %s for %s (refreshing every %d min; Ctrl+C to stop)",
807
+ base_url(settings.port), ", ".join(c.repo for c in configs) or "no repos yet", settings.refresh_minutes) # fmt: skip
808
+ if on_ready:
809
+ on_ready()
810
+ try:
811
+ httpd.serve_forever()
812
+ except KeyboardInterrupt:
813
+ pass
814
+ finally:
815
+ stop.set()
816
+ httpd.stop_all()
817
+ httpd.server_close()