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,344 @@
1
+ """
2
+ proxy_chain.py - Egress lane manager for opencode-unlimited.
3
+
4
+ Manages a prioritized list of egress lanes (DIRECT, WARP, TOR, CLEAN_ENDPOINT),
5
+ tracks health state per lane, rotates on failures, and exposes a rich status
6
+ table.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import logging
13
+ from dataclasses import dataclass, field
14
+ from datetime import datetime, timezone
15
+ from enum import Enum
16
+ from typing import List, Optional
17
+
18
+ import httpx
19
+ from rich.table import Table
20
+ from rich.text import Text
21
+
22
+ from ..constants import (
23
+ OPENCODE_API_HOST,
24
+ RATE_LIMIT_STATUS_CODE,
25
+ TOR_SOCKS_PORT,
26
+ WARP_SOCKS_PORT,
27
+ )
28
+
29
+ log = logging.getLogger(__name__)
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # Enums & dataclasses
33
+ # ---------------------------------------------------------------------------
34
+
35
+
36
+ class Lane(str, Enum):
37
+ """Available egress lanes, in rough trust/privacy order."""
38
+
39
+ DIRECT = "direct"
40
+ WARP = "warp"
41
+ TOR = "tor"
42
+ CLEAN_ENDPOINT = "clean_endpoint"
43
+
44
+
45
+ @dataclass
46
+ class LaneStatus:
47
+ """Runtime health record for a single lane."""
48
+
49
+ lane: Lane
50
+ healthy: bool = True
51
+ last_checked: datetime = field(
52
+ default_factory=lambda: datetime.now(tz=timezone.utc)
53
+ )
54
+ fail_count: int = 0
55
+
56
+ def reset(self) -> None:
57
+ """Mark lane healthy again and clear the fail counter."""
58
+ self.healthy = True
59
+ self.fail_count = 0
60
+ self.last_checked = datetime.now(tz=timezone.utc)
61
+ log.debug("Lane %s reset to healthy.", self.lane.value)
62
+
63
+
64
+ # ---------------------------------------------------------------------------
65
+ # Constants
66
+ # ---------------------------------------------------------------------------
67
+
68
+ FAIL_THRESHOLD = 3 # lane goes unhealthy once fail_count exceeds this
69
+ HEALTH_CHECK_TIMEOUT = 10.0 # seconds
70
+
71
+ # Config-file spellings accepted for each lane. "clean" is the name used in
72
+ # the default config and README; it maps to the clean-endpoint lane.
73
+ LANE_ALIASES: dict[str, Lane] = {
74
+ "direct": Lane.DIRECT,
75
+ "warp": Lane.WARP,
76
+ "tor": Lane.TOR,
77
+ "clean": Lane.CLEAN_ENDPOINT,
78
+ "clean_endpoint": Lane.CLEAN_ENDPOINT,
79
+ }
80
+
81
+ # Config flag that switches each optional lane off. DIRECT is always available
82
+ # so the proxy can never end up with an empty rotation.
83
+ _ENABLE_FLAGS: dict[Lane, str] = {
84
+ Lane.WARP: "enable_warp",
85
+ Lane.TOR: "enable_tor",
86
+ Lane.CLEAN_ENDPOINT: "enable_clean_endpoints",
87
+ }
88
+
89
+
90
+ # ---------------------------------------------------------------------------
91
+ # ProxyChain
92
+ # ---------------------------------------------------------------------------
93
+
94
+
95
+ class ProxyChain:
96
+ """
97
+ Maintains an ordered list of egress lanes and rotates through them as
98
+ failures are detected.
99
+
100
+ Priority is taken from ``config.lanes_priority`` (a list of lane name
101
+ strings). Lanes not present in the config are appended in default order
102
+ at the end.
103
+ """
104
+
105
+ def __init__(self, config) -> None:
106
+ self._config = config
107
+ lanes = self._build_priority(getattr(config, "lanes_priority", []))
108
+ self._lanes: List[Lane] = [
109
+ lane
110
+ for lane in lanes
111
+ if lane not in _ENABLE_FLAGS or getattr(config, _ENABLE_FLAGS[lane], True) is not False
112
+ ]
113
+ self._health_check_url = (
114
+ f"https://{getattr(config, 'opencode_api_host', None) or OPENCODE_API_HOST}/"
115
+ )
116
+ self._statuses: dict[Lane, LaneStatus] = {
117
+ lane: LaneStatus(lane=lane) for lane in self._lanes
118
+ }
119
+ self._index: int = 0 # index into self._lanes
120
+ log.info(
121
+ "ProxyChain initialised. Priority: %s",
122
+ [l.value for l in self._lanes],
123
+ )
124
+
125
+ # ------------------------------------------------------------------
126
+ # Internal helpers
127
+ # ------------------------------------------------------------------
128
+
129
+ @staticmethod
130
+ def _build_priority(priority_names: List[str]) -> List[Lane]:
131
+ """
132
+ Build an ordered lane list respecting user-configured priority.
133
+ Unknown names are silently skipped; missing lanes are appended.
134
+ """
135
+ seen: set[Lane] = set()
136
+ result: List[Lane] = []
137
+
138
+ for name in priority_names:
139
+ lane = LANE_ALIASES.get(str(name).lower())
140
+ if lane is None:
141
+ log.warning("Unknown lane name in config: %r - skipping.", name)
142
+ continue
143
+ if lane not in seen:
144
+ result.append(lane)
145
+ seen.add(lane)
146
+
147
+ # Append any lanes not covered by the config in default order
148
+ for lane in Lane:
149
+ if lane not in seen:
150
+ result.append(lane)
151
+
152
+ return result
153
+
154
+ # ------------------------------------------------------------------
155
+ # Properties
156
+ # ------------------------------------------------------------------
157
+
158
+ @property
159
+ def current_lane(self) -> Lane:
160
+ """Return the lane currently at the head of the rotation."""
161
+ return self._lanes[self._index]
162
+
163
+ @property
164
+ def current_status(self) -> LaneStatus:
165
+ return self._statuses[self.current_lane]
166
+
167
+ @property
168
+ def lanes(self) -> List[Lane]:
169
+ """Lanes in rotation order (copy)."""
170
+ return list(self._lanes)
171
+
172
+ def disable_lane(self, lane: Lane) -> None:
173
+ """
174
+ Remove *lane* from rotation, e.g. because Tor or WARP failed to start.
175
+ DIRECT can't be removed, so there is always at least one lane.
176
+ """
177
+ if lane == Lane.DIRECT or lane not in self._lanes:
178
+ return
179
+ current = self.current_lane
180
+ self._lanes.remove(lane)
181
+ self._statuses.pop(lane, None)
182
+ if Lane.DIRECT not in self._lanes:
183
+ self._lanes.append(Lane.DIRECT)
184
+ self._statuses[Lane.DIRECT] = LaneStatus(lane=Lane.DIRECT)
185
+ self._index = self._lanes.index(current) if current in self._lanes else 0
186
+ log.info("Lane %s disabled; rotation is now %s.", lane.value, [l.value for l in self._lanes])
187
+
188
+ def mark_success(self, lane: Lane) -> None:
189
+ """Clear the fail counter after a successful request, so failures must be consecutive."""
190
+ status = self._statuses.get(lane)
191
+ if status is not None and (status.fail_count or not status.healthy):
192
+ status.reset()
193
+
194
+ # ------------------------------------------------------------------
195
+ # Public API
196
+ # ------------------------------------------------------------------
197
+
198
+ def rotate(self) -> Lane:
199
+ """
200
+ Move to the next healthy lane in the priority list.
201
+
202
+ If all lanes are unhealthy, reset all and start over from the
203
+ beginning (best-effort recovery).
204
+ """
205
+ original_index = self._index
206
+
207
+ for _ in range(len(self._lanes)):
208
+ self._index = (self._index + 1) % len(self._lanes)
209
+ candidate = self._lanes[self._index]
210
+ if self._statuses[candidate].healthy:
211
+ log.info(
212
+ "Rotated from %s to %s.",
213
+ self._lanes[original_index].value,
214
+ candidate.value,
215
+ )
216
+ return candidate
217
+
218
+ # All lanes exhausted - reset and fall back to index 0
219
+ log.warning("All lanes unhealthy; resetting all statuses and restarting.")
220
+ for status in self._statuses.values():
221
+ status.reset()
222
+ self._index = 0
223
+ return self._lanes[0]
224
+
225
+ def mark_failed(self, lane: Lane) -> None:
226
+ """
227
+ Increment the fail counter for *lane*. If the counter exceeds
228
+ ``FAIL_THRESHOLD``, mark the lane unhealthy.
229
+ """
230
+ status = self._statuses.get(lane)
231
+ if status is None: # lane was disabled meanwhile
232
+ return
233
+ status.fail_count += 1
234
+ status.last_checked = datetime.now(tz=timezone.utc)
235
+ log.debug(
236
+ "Lane %s fail_count -> %d (threshold %d).",
237
+ lane.value,
238
+ status.fail_count,
239
+ FAIL_THRESHOLD,
240
+ )
241
+ if status.fail_count > FAIL_THRESHOLD:
242
+ status.healthy = False
243
+ log.warning(
244
+ "Lane %s marked UNHEALTHY after %d failures.",
245
+ lane.value,
246
+ status.fail_count,
247
+ )
248
+
249
+ def get_socks_url(self, lane: Optional[Lane] = None) -> Optional[str]:
250
+ """
251
+ Return the SOCKS5 proxy URL for the given lane (defaults to
252
+ ``current_lane``). Returns ``None`` for ``DIRECT``.
253
+ """
254
+ target = lane if lane is not None else self.current_lane
255
+
256
+ if target == Lane.DIRECT:
257
+ return None
258
+ if target == Lane.WARP:
259
+ return f"socks5://127.0.0.1:{WARP_SOCKS_PORT}"
260
+ if target == Lane.TOR:
261
+ return f"socks5://127.0.0.1:{TOR_SOCKS_PORT}"
262
+ if target == Lane.CLEAN_ENDPOINT:
263
+ # The clean-endpoint lane is a direct connection. The previous
264
+ # implementation built socks5://1.1.1.1:40000, but public DNS
265
+ # anycast IPs are not SOCKS servers, so that lane always failed.
266
+ return None
267
+
268
+ return None # pragma: no cover
269
+
270
+ async def health_check_all(self) -> None:
271
+ """
272
+ Concurrently ping ``HEALTH_CHECK_URL`` through every lane and update
273
+ health status accordingly.
274
+ """
275
+ log.info("Starting health check on all %d lanes.", len(self._lanes))
276
+ tasks = [self._check_lane(lane) for lane in self._lanes]
277
+ await asyncio.gather(*tasks, return_exceptions=True)
278
+ log.info("Health check complete.")
279
+
280
+ async def _check_lane(self, lane: Lane) -> None:
281
+ status = self._statuses[lane]
282
+ proxy_url = self.get_socks_url(lane)
283
+
284
+ try:
285
+ async with httpx.AsyncClient(
286
+ proxy=proxy_url,
287
+ timeout=HEALTH_CHECK_TIMEOUT,
288
+ trust_env=False,
289
+ ) as client:
290
+ # Any HTTP answer from the real upstream proves the lane can
291
+ # reach it. 4xx (e.g. 401/404 on "/") still counts as reachable.
292
+ resp = await client.get(self._health_check_url)
293
+ if resp.status_code == RATE_LIMIT_STATUS_CODE:
294
+ log.warning("Health check: lane %s got 429.", lane.value)
295
+ status.healthy = True # reachable, just rate-limited
296
+ elif resp.status_code < 500:
297
+ status.healthy = True
298
+ status.fail_count = 0
299
+ log.debug("Lane %s healthy (HTTP %d).", lane.value, resp.status_code)
300
+ else:
301
+ raise httpx.HTTPStatusError(
302
+ f"HTTP {resp.status_code}", request=resp.request, response=resp
303
+ )
304
+ except Exception as exc:
305
+ status.fail_count += 1
306
+ status.healthy = False
307
+ log.warning("Lane %s health-check failed: %s", lane.value, exc)
308
+ finally:
309
+ status.last_checked = datetime.now(tz=timezone.utc)
310
+
311
+ def status_table(self) -> Table:
312
+ """Return a :class:`rich.table.Table` summarising all lane statuses."""
313
+ table = Table(
314
+ title="Egress Lane Health",
315
+ show_header=True,
316
+ header_style="bold magenta",
317
+ )
318
+ table.add_column("Lane", style="cyan", no_wrap=True)
319
+ table.add_column("Status", justify="center")
320
+ table.add_column("Fails", justify="right")
321
+ table.add_column("Last Checked", style="dim")
322
+ table.add_column("SOCKS URL")
323
+
324
+ active = self.current_lane
325
+
326
+ for lane in self._lanes:
327
+ st = self._statuses[lane]
328
+ marker = " [bold yellow]*[/bold yellow]" if lane == active else ""
329
+ name_cell = Text.from_markup(f"{lane.value}{marker}")
330
+ health_cell = (
331
+ Text.from_markup("[bold green]OK[/bold green]")
332
+ if st.healthy
333
+ else Text.from_markup("[bold red]DOWN[/bold red]")
334
+ )
335
+ socks = self.get_socks_url(lane) or "[dim]none[/dim]"
336
+ table.add_row(
337
+ name_cell,
338
+ health_cell,
339
+ str(st.fail_count),
340
+ st.last_checked.strftime("%H:%M:%S UTC"),
341
+ socks,
342
+ )
343
+
344
+ return table