opencode-unlimited 0.1.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.
@@ -0,0 +1,503 @@
1
+ """FastAPI web dashboard for opencode-unlimited."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from pathlib import Path
7
+ from typing import Any, Optional
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+ # ---------------------------------------------------------------------------
12
+ # Embedded single-page dashboard HTML
13
+ # ---------------------------------------------------------------------------
14
+
15
+ DASHBOARD_HTML = """<!DOCTYPE html>
16
+ <html lang="en">
17
+ <head>
18
+ <meta charset="UTF-8" />
19
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
20
+ <title>OpenCode Unlimited Dashboard</title>
21
+ <style>
22
+ :root {
23
+ --bg: #0d1117;
24
+ --surface: #161b22;
25
+ --surface2: #21262d;
26
+ --border: #30363d;
27
+ --text: #c9d1d9;
28
+ --text-dim: #8b949e;
29
+ --accent: #58a6ff;
30
+ --green: #3fb950;
31
+ --red: #f85149;
32
+ --yellow: #d29922;
33
+ --purple: #bc8cff;
34
+ --radius: 8px;
35
+ }
36
+ * { box-sizing: border-box; margin: 0; padding: 0; }
37
+ body {
38
+ background: var(--bg);
39
+ color: var(--text);
40
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, monospace;
41
+ min-height: 100vh;
42
+ }
43
+ header {
44
+ display: flex;
45
+ align-items: center;
46
+ justify-content: space-between;
47
+ padding: 16px 24px;
48
+ background: var(--surface);
49
+ border-bottom: 1px solid var(--border);
50
+ }
51
+ header h1 { font-size: 1.25rem; color: var(--accent); }
52
+ header .pill {
53
+ font-size: 0.75rem;
54
+ padding: 3px 10px;
55
+ border-radius: 999px;
56
+ background: var(--surface2);
57
+ color: var(--text-dim);
58
+ }
59
+ .container { max-width: 1200px; margin: 0 auto; padding: 24px; }
60
+ .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
61
+ @media (max-width: 768px) { .grid { grid-template-columns: 1fr; } }
62
+ .card {
63
+ background: var(--surface);
64
+ border: 1px solid var(--border);
65
+ border-radius: var(--radius);
66
+ padding: 20px;
67
+ }
68
+ .card h2 {
69
+ font-size: 0.85rem;
70
+ text-transform: uppercase;
71
+ letter-spacing: 0.08em;
72
+ color: var(--text-dim);
73
+ margin-bottom: 16px;
74
+ }
75
+ .stat-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
76
+ .stat-label { color: var(--text-dim); font-size: 0.875rem; }
77
+ .stat-value { font-weight: 600; font-size: 0.875rem; }
78
+ .badge {
79
+ display: inline-block;
80
+ padding: 2px 8px;
81
+ border-radius: 4px;
82
+ font-size: 0.75rem;
83
+ font-weight: 600;
84
+ }
85
+ .badge-green { background: rgba(63,185,80,0.15); color: var(--green); }
86
+ .badge-red { background: rgba(248,81,73,0.15); color: var(--red); }
87
+ .badge-yellow { background: rgba(210,153,34,0.15); color: var(--yellow); }
88
+ .badge-blue { background: rgba(88,166,255,0.15); color: var(--accent); }
89
+ table { width: 100%; border-collapse: collapse; font-size: 0.85rem; }
90
+ th { text-align: left; padding: 8px 12px; color: var(--text-dim); font-weight: 500;
91
+ border-bottom: 1px solid var(--border); }
92
+ td { padding: 8px 12px; border-bottom: 1px solid var(--border); }
93
+ tr:last-child td { border-bottom: none; }
94
+ .btn {
95
+ display: inline-flex; align-items: center; gap: 6px;
96
+ padding: 8px 16px; border-radius: 6px; border: 1px solid var(--border);
97
+ background: var(--surface2); color: var(--text); cursor: pointer;
98
+ font-size: 0.85rem; transition: background 0.15s;
99
+ }
100
+ .btn:hover { background: var(--border); }
101
+ .btn-primary { background: var(--accent); border-color: var(--accent); color: #000; }
102
+ .btn-primary:hover { opacity: 0.85; }
103
+ .btn-danger { background: rgba(248,81,73,0.15); border-color: var(--red); color: var(--red); }
104
+ .actions { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 16px; }
105
+ .log-box {
106
+ background: #000;
107
+ border: 1px solid var(--border);
108
+ border-radius: var(--radius);
109
+ padding: 12px;
110
+ font-family: monospace;
111
+ font-size: 0.75rem;
112
+ color: #a3e635;
113
+ max-height: 300px;
114
+ overflow-y: auto;
115
+ white-space: pre-wrap;
116
+ word-break: break-all;
117
+ }
118
+ #refresh-indicator {
119
+ font-size: 0.75rem;
120
+ color: var(--text-dim);
121
+ }
122
+ .full-width { grid-column: 1 / -1; }
123
+ .event-row { display: flex; gap: 10px; align-items: flex-start; padding: 6px 0; border-bottom: 1px solid var(--border); }
124
+ .event-time { color: var(--text-dim); font-size: 0.75rem; white-space: nowrap; }
125
+ .event-msg { font-size: 0.85rem; }
126
+ </style>
127
+ </head>
128
+ <body>
129
+ <header>
130
+ <h1>OpenCode Unlimited</h1>
131
+ <div style="display:flex;gap:12px;align-items:center">
132
+ <span id="refresh-indicator">Refreshing...</span>
133
+ <span class="pill" id="uptime-pill">--</span>
134
+ </div>
135
+ </header>
136
+ <div class="container">
137
+ <div class="grid">
138
+
139
+ <!-- Status card -->
140
+ <div class="card">
141
+ <h2>Proxy Status</h2>
142
+ <div class="stat-row">
143
+ <span class="stat-label">Proxy Running</span>
144
+ <span class="stat-value" id="proxy-running">--</span>
145
+ </div>
146
+ <div class="stat-row">
147
+ <span class="stat-label">Current Lane</span>
148
+ <span class="stat-value" id="current-lane">--</span>
149
+ </div>
150
+ <div class="stat-row">
151
+ <span class="stat-label">Total Requests</span>
152
+ <span class="stat-value" id="total-requests">--</span>
153
+ </div>
154
+ <div class="stat-row">
155
+ <span class="stat-label">Rate-Limit Events (1h)</span>
156
+ <span class="stat-value" id="rl-events">--</span>
157
+ </div>
158
+ <div class="actions">
159
+ <button class="btn btn-primary" onclick="rotateLane()">Rotate Lane</button>
160
+ <button class="btn" onclick="rotateAccount()">Rotate Account</button>
161
+ </div>
162
+ </div>
163
+
164
+ <!-- Active account card -->
165
+ <div class="card">
166
+ <h2>Active Account</h2>
167
+ <div class="stat-row">
168
+ <span class="stat-label">Account ID</span>
169
+ <span class="stat-value" id="acc-id">--</span>
170
+ </div>
171
+ <div class="stat-row">
172
+ <span class="stat-label">Token</span>
173
+ <span class="stat-value" id="acc-token">--</span>
174
+ </div>
175
+ <div class="stat-row">
176
+ <span class="stat-label">Rate Limited</span>
177
+ <span class="stat-value" id="acc-rl">--</span>
178
+ </div>
179
+ <div class="stat-row">
180
+ <span class="stat-label">Pool Size</span>
181
+ <span class="stat-value" id="acc-pool-size">--</span>
182
+ </div>
183
+ </div>
184
+
185
+ <!-- Lanes card -->
186
+ <div class="card full-width">
187
+ <h2>Egress Lanes</h2>
188
+ <table>
189
+ <thead>
190
+ <tr><th>Lane</th><th>Healthy</th><th>Fail Count</th><th>Last Checked</th></tr>
191
+ </thead>
192
+ <tbody id="lanes-tbody">
193
+ <tr><td colspan="4" style="color:var(--text-dim)">Loading...</td></tr>
194
+ </tbody>
195
+ </table>
196
+ </div>
197
+
198
+ <!-- Rate limit events -->
199
+ <div class="card">
200
+ <h2>Rate-Limit Events</h2>
201
+ <div id="rl-events-list" style="max-height:220px;overflow-y:auto">
202
+ <span style="color:var(--text-dim);font-size:0.85rem">No events yet</span>
203
+ </div>
204
+ </div>
205
+
206
+ <!-- Accounts -->
207
+ <div class="card">
208
+ <h2>All Accounts</h2>
209
+ <table>
210
+ <thead>
211
+ <tr><th>ID</th><th>Token</th><th>Active</th><th>Rate-Ltd</th></tr>
212
+ </thead>
213
+ <tbody id="accounts-tbody">
214
+ <tr><td colspan="4" style="color:var(--text-dim)">Loading...</td></tr>
215
+ </tbody>
216
+ </table>
217
+ </div>
218
+
219
+ <!-- Logs -->
220
+ <div class="card full-width">
221
+ <h2>Recent Logs</h2>
222
+ <div class="log-box" id="log-box">Loading...</div>
223
+ </div>
224
+
225
+ </div>
226
+ </div>
227
+
228
+ <script>
229
+ const $ = id => document.getElementById(id);
230
+
231
+ function badge(text, type) {
232
+ return `<span class="badge badge-${type}">${text}</span>`;
233
+ }
234
+
235
+ async function fetchStatus() {
236
+ try {
237
+ const r = await fetch('/api/status');
238
+ const d = await r.json();
239
+
240
+ // Proxy status
241
+ $('proxy-running').innerHTML = d.proxy_running
242
+ ? badge('Running', 'green') : badge('Stopped', 'red');
243
+ $('current-lane').innerHTML = badge(d.current_lane || 'DIRECT', 'blue');
244
+ $('total-requests').textContent = d.total_requests ?? '--';
245
+ $('rl-events').textContent = d.rate_limit_event_count ?? 0;
246
+
247
+ // Active account
248
+ const acc = d.active_account;
249
+ if (acc) {
250
+ $('acc-id').textContent = acc.id ? acc.id.slice(0,8) + '...' : '--';
251
+ $('acc-token').textContent = acc.token_masked ?? '--';
252
+ $('acc-rl').innerHTML = acc.rate_limited
253
+ ? badge('YES', 'red') : badge('No', 'green');
254
+ }
255
+ $('acc-pool-size').textContent = d.pool_size ?? '--';
256
+
257
+ // Lanes
258
+ const lanesBody = $('lanes-tbody');
259
+ if (d.lanes && d.lanes.length) {
260
+ lanesBody.innerHTML = d.lanes.map(l => `
261
+ <tr>
262
+ <td>${l.lane}</td>
263
+ <td>${l.healthy ? badge('OK','green') : badge('DOWN','red')}</td>
264
+ <td>${l.fail_count}</td>
265
+ <td>${l.last_checked ?? '--'}</td>
266
+ </tr>`).join('');
267
+ }
268
+
269
+ // Rate limit events
270
+ const rlList = $('rl-events-list');
271
+ if (d.rate_limit_events && d.rate_limit_events.length) {
272
+ rlList.innerHTML = d.rate_limit_events.slice(-20).reverse().map(e => `
273
+ <div class="event-row">
274
+ <span class="event-time">${e.time ?? ''}</span>
275
+ <span class="event-msg">${e.message ?? JSON.stringify(e)}</span>
276
+ </div>`).join('');
277
+ }
278
+
279
+ // Accounts table
280
+ const accBody = $('accounts-tbody');
281
+ if (d.accounts && d.accounts.length) {
282
+ accBody.innerHTML = d.accounts.map(a => `
283
+ <tr>
284
+ <td style="font-family:monospace">${(a.id||'').slice(0,8)}...</td>
285
+ <td style="font-family:monospace">${a.token_masked ?? '--'}</td>
286
+ <td>${a.active ? badge('YES','green') : ''}</td>
287
+ <td>${a.rate_limited ? badge('YES','red') : badge('No','green')}</td>
288
+ </tr>`).join('');
289
+ }
290
+
291
+ $('refresh-indicator').textContent = 'Last updated: ' + new Date().toLocaleTimeString();
292
+ } catch(e) {
293
+ $('refresh-indicator').textContent = 'Error: ' + e.message;
294
+ }
295
+ }
296
+
297
+ async function fetchLogs() {
298
+ try {
299
+ const r = await fetch('/api/logs');
300
+ const d = await r.json();
301
+ $('log-box').textContent = (d.lines || []).join('\\n') || '(no logs)';
302
+ $('log-box').scrollTop = $('log-box').scrollHeight;
303
+ } catch(e) {}
304
+ }
305
+
306
+ async function rotateLane() {
307
+ await fetch('/api/rotate', {method:'POST'});
308
+ fetchStatus();
309
+ }
310
+
311
+ async function rotateAccount() {
312
+ await fetch('/api/accounts/rotate', {method:'POST'});
313
+ fetchStatus();
314
+ }
315
+
316
+ fetchStatus();
317
+ fetchLogs();
318
+ setInterval(fetchStatus, 5000);
319
+ setInterval(fetchLogs, 10000);
320
+ </script>
321
+ </body>
322
+ </html>
323
+ """
324
+
325
+
326
+ def create_app(proxy_chain, zen_guard, account_pool, config): # noqa: ANN001
327
+ """Create and return the FastAPI dashboard application.
328
+
329
+ Parameters
330
+ ----------
331
+ proxy_chain:
332
+ ProxyChain instance (may be None when running standalone).
333
+ zen_guard:
334
+ ZenGuard instance (may be None).
335
+ account_pool:
336
+ AccountPool instance.
337
+ config:
338
+ OCUConfig instance.
339
+
340
+ Returns
341
+ -------
342
+ FastAPI application.
343
+ """
344
+ try:
345
+ from fastapi import FastAPI, Request
346
+ from fastapi.responses import HTMLResponse, JSONResponse
347
+ except ImportError as exc: # pragma: no cover
348
+ raise RuntimeError(
349
+ "FastAPI is required for the dashboard. Install it with: pip install fastapi uvicorn"
350
+ ) from exc
351
+
352
+ import datetime as _dt
353
+
354
+ app = FastAPI(title="OpenCode Unlimited Dashboard", version="0.1.0")
355
+
356
+ # Keep a small ring-buffer of rate-limit events
357
+ _rl_events: list[dict] = []
358
+ _total_requests: int = 0
359
+
360
+ # Attach references so external code can mutate them
361
+ app.state.proxy_chain = proxy_chain
362
+ app.state.zen_guard = zen_guard
363
+ app.state.account_pool = account_pool
364
+ app.state.config = config
365
+ app.state.rl_events = _rl_events
366
+
367
+ # ------------------------------------------------------------------
368
+ # Routes
369
+ # ------------------------------------------------------------------
370
+
371
+ @app.get("/", response_class=HTMLResponse)
372
+ async def root() -> HTMLResponse:
373
+ return HTMLResponse(DASHBOARD_HTML)
374
+
375
+ @app.get("/api/status")
376
+ async def api_status() -> JSONResponse:
377
+ pc = app.state.proxy_chain
378
+ ap = app.state.account_pool
379
+ active = ap.get_active() if ap else None
380
+
381
+ lanes_data: list[dict] = []
382
+ current_lane = "DIRECT"
383
+ if pc:
384
+ current_lane = pc.current_lane.name if hasattr(pc.current_lane, "name") else str(pc.current_lane)
385
+ for ls in getattr(pc, "_lanes", {}).values():
386
+ lanes_data.append({
387
+ "lane": ls.lane.name if hasattr(ls.lane, "name") else str(ls.lane),
388
+ "healthy": ls.healthy,
389
+ "fail_count": ls.fail_count,
390
+ "last_checked": ls.last_checked.isoformat() if ls.last_checked else None,
391
+ })
392
+
393
+ accounts_data: list[dict] = []
394
+ pool_size = 0
395
+ if ap:
396
+ pool_size = len(ap)
397
+ for acc in getattr(ap, "_accounts", []):
398
+ accounts_data.append({
399
+ "id": acc.id,
400
+ "token_masked": acc.masked_token(),
401
+ "active": acc.active,
402
+ "rate_limited": acc.rate_limited,
403
+ })
404
+
405
+ rl_events = list(app.state.rl_events)[-100:]
406
+
407
+ return JSONResponse({
408
+ "proxy_running": pc is not None,
409
+ "current_lane": current_lane,
410
+ "total_requests": _total_requests,
411
+ "rate_limit_event_count": len(rl_events),
412
+ "rate_limit_events": rl_events,
413
+ "active_account": {
414
+ "id": active.id if active else None,
415
+ "token_masked": active.masked_token() if active else None,
416
+ "rate_limited": active.rate_limited if active else None,
417
+ },
418
+ "pool_size": pool_size,
419
+ "lanes": lanes_data,
420
+ "accounts": accounts_data,
421
+ })
422
+
423
+ @app.post("/api/rotate")
424
+ async def api_rotate() -> JSONResponse:
425
+ pc = app.state.proxy_chain
426
+ if pc:
427
+ new_lane = pc.rotate()
428
+ return JSONResponse({"ok": True, "new_lane": str(new_lane)})
429
+ return JSONResponse({"ok": False, "error": "No proxy chain available"}, status_code=503)
430
+
431
+ @app.post("/api/config")
432
+ async def api_config_update(request: Request) -> JSONResponse:
433
+ body = await request.json()
434
+ cfg = app.state.config
435
+ updated: list[str] = []
436
+ for key, value in body.items():
437
+ if hasattr(cfg, key):
438
+ setattr(cfg, key, value)
439
+ updated.append(key)
440
+ from opencode_unlimited.config import save_config
441
+ save_config(cfg)
442
+ return JSONResponse({"ok": True, "updated": updated})
443
+
444
+ @app.get("/api/logs")
445
+ async def api_logs() -> JSONResponse:
446
+ from opencode_unlimited.constants import LOG_FILE
447
+ lines: list[str] = []
448
+ if LOG_FILE.exists():
449
+ try:
450
+ text = LOG_FILE.read_text(encoding="utf-8", errors="replace")
451
+ lines = text.splitlines()[-100:]
452
+ except OSError:
453
+ pass
454
+ return JSONResponse({"lines": lines})
455
+
456
+ @app.get("/api/accounts")
457
+ async def api_accounts() -> JSONResponse:
458
+ ap = app.state.account_pool
459
+ if not ap:
460
+ return JSONResponse({"accounts": []})
461
+ accounts_data = []
462
+ for acc in getattr(ap, "_accounts", []):
463
+ accounts_data.append({
464
+ "id": acc.id,
465
+ "token_masked": acc.masked_token(),
466
+ "active": acc.active,
467
+ "rate_limited": acc.rate_limited,
468
+ "last_used": acc.last_used.isoformat() if acc.last_used else None,
469
+ })
470
+ return JSONResponse({"accounts": accounts_data})
471
+
472
+ @app.post("/api/accounts/rotate")
473
+ async def api_accounts_rotate() -> JSONResponse:
474
+ ap = app.state.account_pool
475
+ if not ap:
476
+ return JSONResponse({"ok": False, "error": "No account pool"}, status_code=503)
477
+ new_acc = ap.rotate()
478
+ if new_acc:
479
+ return JSONResponse({"ok": True, "new_account_id": new_acc.id})
480
+ return JSONResponse({"ok": False, "error": "No healthy accounts available"}, status_code=503)
481
+
482
+ return app
483
+
484
+
485
+ def run_dashboard(app, port: int = 7979) -> None: # noqa: ANN001
486
+ """Run the dashboard using uvicorn.
487
+
488
+ Parameters
489
+ ----------
490
+ app:
491
+ FastAPI application returned by ``create_app``.
492
+ port:
493
+ TCP port to listen on (default: 7979).
494
+ """
495
+ try:
496
+ import uvicorn
497
+ except ImportError as exc: # pragma: no cover
498
+ raise RuntimeError(
499
+ "uvicorn is required to run the dashboard. Install it with: pip install uvicorn"
500
+ ) from exc
501
+
502
+ logger.info("Starting dashboard on http://0.0.0.0:%d", port)
503
+ uvicorn.run(app, host="0.0.0.0", port=port, log_level="warning")
File without changes
@@ -0,0 +1,182 @@
1
+ """
2
+ clean_endpoint.py - Clean endpoint benchmarker for opencode-unlimited.
3
+
4
+ Discovers the lowest-latency reachable endpoint from a list of candidates,
5
+ suitable for use as a direct egress lane when WARP and Tor are unavailable.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import logging
12
+ import time
13
+ from dataclasses import dataclass, field
14
+ from typing import Optional
15
+
16
+ import httpx
17
+ from rich.console import Console
18
+ from rich.table import Table
19
+
20
+ log = logging.getLogger(__name__)
21
+ console = Console()
22
+
23
+ # ---------------------------------------------------------------------------
24
+ # Default ping URL template -- we HEAD the endpoint directly
25
+ # ---------------------------------------------------------------------------
26
+ _PING_PATH = "/"
27
+ _PING_TIMEOUT = 5.0 # seconds per probe
28
+
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # Dataclass
32
+ # ---------------------------------------------------------------------------
33
+
34
+ @dataclass
35
+ class EndpointBenchmark:
36
+ """Result of a single endpoint latency probe."""
37
+
38
+ host: str
39
+ latency_ms: float = float("inf")
40
+ reachable: bool = False
41
+
42
+
43
+ # ---------------------------------------------------------------------------
44
+ # CleanEndpointManager
45
+ # ---------------------------------------------------------------------------
46
+
47
+ class CleanEndpointManager:
48
+ """
49
+ Pings a list of HTTPS endpoints concurrently and tracks the best one
50
+ (lowest latency, reachable).
51
+
52
+ Usage::
53
+
54
+ manager = CleanEndpointManager(endpoints=["1.1.1.1", "8.8.8.8"])
55
+ await manager.ping_all()
56
+ best = manager.best_endpoint()
57
+ print(manager.status_table())
58
+ """
59
+
60
+ def __init__(self, endpoints: Optional[list[str]] = None) -> None:
61
+ if endpoints is None:
62
+ # Lazy import to avoid circular imports at module load time
63
+ from opencode_unlimited.constants import CLEAN_ENDPOINTS # type: ignore[import-not-found]
64
+ endpoints = list(CLEAN_ENDPOINTS)
65
+
66
+ if not endpoints:
67
+ raise ValueError("endpoints list must not be empty")
68
+
69
+ self._endpoints: list[str] = endpoints
70
+ self._results: dict[str, EndpointBenchmark] = {
71
+ ep: EndpointBenchmark(host=ep) for ep in endpoints
72
+ }
73
+ log.debug("CleanEndpointManager tracking %d endpoints", len(endpoints))
74
+
75
+ # ------------------------------------------------------------------
76
+ # Benchmarking
77
+ # ------------------------------------------------------------------
78
+
79
+ async def ping_all(self) -> list[EndpointBenchmark]:
80
+ """
81
+ Probe every endpoint concurrently via HTTPS HEAD request.
82
+ Updates internal results and returns the list of benchmarks.
83
+ """
84
+ log.info("[bold cyan]CleanEndpoint[/] Pinging %d endpoints...", len(self._endpoints), extra={"markup": True})
85
+ tasks = [self._probe(ep) for ep in self._endpoints]
86
+ results: list[EndpointBenchmark] = await asyncio.gather(*tasks)
87
+ reachable_count = sum(1 for r in results if r.reachable)
88
+ log.info(
89
+ "[bold green]CleanEndpoint[/] %d/%d reachable",
90
+ reachable_count, len(results),
91
+ extra={"markup": True},
92
+ )
93
+ return results
94
+
95
+ async def _probe(self, host: str) -> EndpointBenchmark:
96
+ """Probe a single host and update internal state."""
97
+ benchmark = self._results[host]
98
+ url = f"https://{host}{_PING_PATH}"
99
+ try:
100
+ async with httpx.AsyncClient(timeout=_PING_TIMEOUT, verify=False) as client:
101
+ t0 = time.perf_counter()
102
+ resp = await client.head(url, follow_redirects=True)
103
+ latency_ms = (time.perf_counter() - t0) * 1000.0
104
+ benchmark.latency_ms = latency_ms
105
+ benchmark.reachable = resp.status_code < 500
106
+ log.debug(
107
+ " %s -> %dms (HTTP %d)",
108
+ host, int(latency_ms), resp.status_code,
109
+ )
110
+ except Exception as exc: # noqa: BLE001
111
+ benchmark.reachable = False
112
+ benchmark.latency_ms = float("inf")
113
+ log.debug(" %s -> UNREACHABLE (%s)", host, exc)
114
+ return benchmark
115
+
116
+ # ------------------------------------------------------------------
117
+ # Selection
118
+ # ------------------------------------------------------------------
119
+
120
+ def best_endpoint(self) -> Optional[str]:
121
+ """Return the hostname of the fastest reachable endpoint."""
122
+ candidates = [b for b in self._results.values() if b.reachable]
123
+ if not candidates:
124
+ log.warning("[bold red]CleanEndpoint[/] No reachable endpoints found", extra={"markup": True})
125
+ return None
126
+ best = min(candidates, key=lambda b: b.latency_ms)
127
+ log.info(
128
+ "[bold green]CleanEndpoint[/] Best endpoint: %s (%.1fms)",
129
+ best.host, best.latency_ms,
130
+ extra={"markup": True},
131
+ )
132
+ return best.host
133
+
134
+ def get_socks_url(self, endpoint: str) -> str:
135
+ """
136
+ Return a proxy URL for the given endpoint.
137
+
138
+ For clean endpoints this is a direct HTTPS URL (no SOCKS tunnel);
139
+ callers may use the endpoint as a Host override or direct target.
140
+ """
141
+ return f"https://{endpoint}"
142
+
143
+ # ------------------------------------------------------------------
144
+ # Display
145
+ # ------------------------------------------------------------------
146
+
147
+ def status_table(self) -> Table:
148
+ """Return a rich Table showing all endpoints and their latency."""
149
+ table = Table(title="Clean Endpoint Status", show_header=True, header_style="bold magenta")
150
+ table.add_column("Host", style="cyan", no_wrap=True)
151
+ table.add_column("Reachable", justify="center")
152
+ table.add_column("Latency (ms)", justify="right")
153
+
154
+ # Sort: reachable first, then by latency
155
+ sorted_results = sorted(
156
+ self._results.values(),
157
+ key=lambda b: (not b.reachable, b.latency_ms),
158
+ )
159
+
160
+ for b in sorted_results:
161
+ reachable_str = "[green]YES[/]" if b.reachable else "[red]NO[/]"
162
+ if b.latency_ms == float("inf"):
163
+ latency_str = "[dim]--[/]"
164
+ else:
165
+ latency_str = f"{b.latency_ms:.1f}"
166
+ table.add_row(b.host, reachable_str, latency_str)
167
+
168
+ return table
169
+
170
+ # ------------------------------------------------------------------
171
+ # Properties
172
+ # ------------------------------------------------------------------
173
+
174
+ @property
175
+ def endpoints(self) -> list[str]:
176
+ """The full list of monitored endpoints."""
177
+ return list(self._endpoints)
178
+
179
+ @property
180
+ def results(self) -> list[EndpointBenchmark]:
181
+ """Current benchmark results for all endpoints."""
182
+ return list(self._results.values())