torwire 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.
- torwire/__init__.py +52 -0
- torwire/_platform.py +162 -0
- torwire/binary.py +299 -0
- torwire/bridge.py +324 -0
- torwire/checks.py +195 -0
- torwire/cli.py +199 -0
- torwire/clients/__init__.py +0 -0
- torwire/clients/aiohttp_.py +49 -0
- torwire/clients/httpx_.py +72 -0
- torwire/clients/requests_.py +69 -0
- torwire/config.py +154 -0
- torwire/controller.py +189 -0
- torwire/env.py +101 -0
- torwire/errors.py +198 -0
- torwire/manager.py +370 -0
- torwire/pool.py +125 -0
- torwire/process.py +383 -0
- torwire/py.typed +0 -0
- torwire/rotation.py +148 -0
- torwire-0.1.0.dist-info/METADATA +208 -0
- torwire-0.1.0.dist-info/RECORD +24 -0
- torwire-0.1.0.dist-info/WHEEL +4 -0
- torwire-0.1.0.dist-info/entry_points.txt +2 -0
- torwire-0.1.0.dist-info/licenses/LICENSE +21 -0
torwire/process.py
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
"""Tor process lifecycle management and auto-restart watchdog."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import atexit
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import secrets
|
|
10
|
+
import shutil
|
|
11
|
+
import signal
|
|
12
|
+
import subprocess
|
|
13
|
+
import tempfile
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
from collections import deque
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Callable
|
|
19
|
+
|
|
20
|
+
from torwire._platform import (
|
|
21
|
+
default_data_dir,
|
|
22
|
+
find_free_port,
|
|
23
|
+
subprocess_creation_flags,
|
|
24
|
+
)
|
|
25
|
+
from torwire.config import TorConfig
|
|
26
|
+
from torwire.errors import BootstrapError, ControlError
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger("torwire")
|
|
29
|
+
|
|
30
|
+
_BOOTSTRAP_RE = re.compile(r"Bootstrapped (\d+)%(?: \(([^)]*)\))?:?\s*(.*)")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class TorProcess:
|
|
34
|
+
"""Launch, monitor, and cleanly stop a managed ``tor`` process."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, config: TorConfig, tor_path: Path) -> None:
|
|
37
|
+
self._config = config
|
|
38
|
+
self._tor_path = Path(tor_path)
|
|
39
|
+
self._process: subprocess.Popen[str] | None = None
|
|
40
|
+
self._socks_port: int = config.socks_port
|
|
41
|
+
self._control_port: int = config.control_port
|
|
42
|
+
self._control_password: str = config.control_password or ""
|
|
43
|
+
self._data_dir: Path | None = None
|
|
44
|
+
self._temp_data_dir: bool = False
|
|
45
|
+
self._torrc_path: Path | None = None
|
|
46
|
+
self._lock = threading.Lock()
|
|
47
|
+
self._atexit_registered = False
|
|
48
|
+
self._stopping = False
|
|
49
|
+
self._recent_logs: deque[str] = deque(maxlen=40)
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def socks_port(self) -> int:
|
|
53
|
+
"""Return the SOCKS5 port Tor is listening on."""
|
|
54
|
+
return self._socks_port
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def control_port(self) -> int:
|
|
58
|
+
"""Return the ControlPort Tor is listening on."""
|
|
59
|
+
return self._control_port
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def control_password(self) -> str:
|
|
63
|
+
"""Return the plaintext control-port password for this run."""
|
|
64
|
+
return self._control_password
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def pid(self) -> int | None:
|
|
68
|
+
"""Return the OS process ID of the running Tor process, or ``None``."""
|
|
69
|
+
if self._process is None:
|
|
70
|
+
return None
|
|
71
|
+
return self._process.pid
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def is_alive(self) -> bool:
|
|
75
|
+
"""Return ``True`` if the Tor subprocess is still running."""
|
|
76
|
+
return self._process is not None and self._process.poll() is None
|
|
77
|
+
|
|
78
|
+
def start(self, on_progress: Callable[[int, str], None] | None = None) -> None:
|
|
79
|
+
"""Launch Tor and block until bootstrap reaches 100%.
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
on_progress: Optional callback receiving ``(percent, message)``.
|
|
83
|
+
|
|
84
|
+
Raises:
|
|
85
|
+
BootstrapError: If Tor exits prematurely or exceeds the timeout.
|
|
86
|
+
"""
|
|
87
|
+
with self._lock:
|
|
88
|
+
if self.is_alive:
|
|
89
|
+
return
|
|
90
|
+
self._stopping = False
|
|
91
|
+
self._recent_logs.clear()
|
|
92
|
+
|
|
93
|
+
if self._socks_port == 0:
|
|
94
|
+
self._socks_port = find_free_port()
|
|
95
|
+
if self._control_port == 0:
|
|
96
|
+
self._control_port = find_free_port()
|
|
97
|
+
if not self._control_password:
|
|
98
|
+
self._control_password = self._generate_password()
|
|
99
|
+
|
|
100
|
+
self._prepare_data_dir()
|
|
101
|
+
torrc = self._build_torrc()
|
|
102
|
+
self._torrc_path = self._write_torrc(torrc)
|
|
103
|
+
|
|
104
|
+
cmd = [str(self._tor_path), "-f", str(self._torrc_path)]
|
|
105
|
+
logger.debug("Launching Tor: %s", cmd)
|
|
106
|
+
self._process = subprocess.Popen(
|
|
107
|
+
cmd,
|
|
108
|
+
stdout=subprocess.PIPE,
|
|
109
|
+
stderr=subprocess.STDOUT,
|
|
110
|
+
text=True,
|
|
111
|
+
encoding="utf-8",
|
|
112
|
+
errors="replace",
|
|
113
|
+
bufsize=1,
|
|
114
|
+
creationflags=subprocess_creation_flags(),
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
if not self._atexit_registered:
|
|
118
|
+
atexit.register(self.stop)
|
|
119
|
+
self._atexit_registered = True
|
|
120
|
+
|
|
121
|
+
self._wait_for_bootstrap(on_progress)
|
|
122
|
+
|
|
123
|
+
def stop(self) -> None:
|
|
124
|
+
"""Stop Tor cleanly (terminate, wait, kill if needed) and clean up temp files."""
|
|
125
|
+
with self._lock:
|
|
126
|
+
self._stopping = True
|
|
127
|
+
proc = self._process
|
|
128
|
+
self._process = None
|
|
129
|
+
|
|
130
|
+
if proc is not None and proc.poll() is None:
|
|
131
|
+
logger.debug("Terminating Tor process (pid=%s)", proc.pid)
|
|
132
|
+
try:
|
|
133
|
+
proc.terminate()
|
|
134
|
+
proc.wait(timeout=5.0)
|
|
135
|
+
except subprocess.TimeoutExpired:
|
|
136
|
+
logger.warning("Tor did not exit gracefully; killing pid=%s", proc.pid)
|
|
137
|
+
proc.kill()
|
|
138
|
+
try:
|
|
139
|
+
proc.wait(timeout=5.0)
|
|
140
|
+
except subprocess.TimeoutExpired:
|
|
141
|
+
pass
|
|
142
|
+
except OSError:
|
|
143
|
+
pass
|
|
144
|
+
|
|
145
|
+
if proc is not None and proc.stdout is not None:
|
|
146
|
+
try:
|
|
147
|
+
proc.stdout.close()
|
|
148
|
+
except OSError:
|
|
149
|
+
pass
|
|
150
|
+
|
|
151
|
+
if self._torrc_path is not None and self._torrc_path.exists():
|
|
152
|
+
try:
|
|
153
|
+
self._torrc_path.unlink(missing_ok=True)
|
|
154
|
+
except OSError:
|
|
155
|
+
pass
|
|
156
|
+
self._torrc_path = None
|
|
157
|
+
|
|
158
|
+
if self._temp_data_dir and self._data_dir is not None and not self._config.persist_data:
|
|
159
|
+
self._remove_dir_with_retry(self._data_dir)
|
|
160
|
+
self._data_dir = None
|
|
161
|
+
|
|
162
|
+
def _prepare_data_dir(self) -> None:
|
|
163
|
+
"""Create or resolve the Tor DataDirectory."""
|
|
164
|
+
if self._config.data_dir:
|
|
165
|
+
self._data_dir = Path(self._config.data_dir).expanduser()
|
|
166
|
+
self._data_dir.mkdir(parents=True, exist_ok=True)
|
|
167
|
+
self._temp_data_dir = False
|
|
168
|
+
elif self._config.persist_data:
|
|
169
|
+
self._data_dir = default_data_dir() / "data"
|
|
170
|
+
self._data_dir.mkdir(parents=True, exist_ok=True)
|
|
171
|
+
self._temp_data_dir = False
|
|
172
|
+
else:
|
|
173
|
+
if self._data_dir is None or not self._data_dir.exists():
|
|
174
|
+
self._data_dir = Path(tempfile.mkdtemp(prefix="torwire_"))
|
|
175
|
+
self._temp_data_dir = True
|
|
176
|
+
|
|
177
|
+
def _build_torrc(self) -> dict[str, str]:
|
|
178
|
+
"""Build the complete torrc dictionary for this process."""
|
|
179
|
+
torrc = self._config.effective_torrc()
|
|
180
|
+
torrc["SocksPort"] = f"127.0.0.1:{self._socks_port}"
|
|
181
|
+
torrc["ControlPort"] = f"127.0.0.1:{self._control_port}"
|
|
182
|
+
torrc["HashedControlPassword"] = self._hash_password(self._control_password)
|
|
183
|
+
torrc["DataDirectory"] = str(self._data_dir)
|
|
184
|
+
torrc["__OwningControllerProcess"] = str(os.getpid())
|
|
185
|
+
|
|
186
|
+
# Include geoip files if bundled alongside the tor binary
|
|
187
|
+
for candidate_dir in (self._tor_path.parent, self._tor_path.parent.parent / "data"):
|
|
188
|
+
geoip = candidate_dir / "geoip"
|
|
189
|
+
geoip6 = candidate_dir / "geoip6"
|
|
190
|
+
if geoip.is_file():
|
|
191
|
+
torrc.setdefault("GeoIPFile", str(geoip))
|
|
192
|
+
if geoip6.is_file():
|
|
193
|
+
torrc.setdefault("GeoIPv6File", str(geoip6))
|
|
194
|
+
return torrc
|
|
195
|
+
|
|
196
|
+
def _write_torrc(self, torrc: dict[str, str]) -> Path:
|
|
197
|
+
"""Serialize *torrc* into a temporary torrc file inside the data dir."""
|
|
198
|
+
assert self._data_dir is not None
|
|
199
|
+
torrc_file = self._data_dir / "torrc"
|
|
200
|
+
lines: list[str] = []
|
|
201
|
+
for key, value in torrc.items():
|
|
202
|
+
# Support multiple Bridge lines encoded as Bridge0, Bridge1, ...
|
|
203
|
+
if re.match(r"^Bridge\d+$", key):
|
|
204
|
+
lines.append(f"Bridge {value}")
|
|
205
|
+
else:
|
|
206
|
+
lines.append(f"{key} {value}")
|
|
207
|
+
torrc_file.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
208
|
+
return torrc_file
|
|
209
|
+
|
|
210
|
+
def _generate_password(self) -> str:
|
|
211
|
+
"""Generate a random per-run control password."""
|
|
212
|
+
return secrets.token_hex(16)
|
|
213
|
+
|
|
214
|
+
def _hash_password(self, password: str) -> str:
|
|
215
|
+
"""Hash *password* using ``tor --hash-password``."""
|
|
216
|
+
try:
|
|
217
|
+
proc = subprocess.run(
|
|
218
|
+
[str(self._tor_path), "--hash-password", password],
|
|
219
|
+
capture_output=True,
|
|
220
|
+
text=True,
|
|
221
|
+
timeout=10,
|
|
222
|
+
creationflags=subprocess_creation_flags(),
|
|
223
|
+
)
|
|
224
|
+
if proc.returncode == 0:
|
|
225
|
+
for line in reversed(proc.stdout.splitlines()):
|
|
226
|
+
stripped = line.strip()
|
|
227
|
+
if stripped.startswith("16:"):
|
|
228
|
+
return stripped
|
|
229
|
+
except Exception as exc:
|
|
230
|
+
logger.debug("tor --hash-password failed: %s", exc)
|
|
231
|
+
|
|
232
|
+
raise ControlError("Failed to hash Tor control password using tor --hash-password.")
|
|
233
|
+
|
|
234
|
+
def _wait_for_bootstrap(
|
|
235
|
+
self, on_progress: Callable[[int, str], None] | None
|
|
236
|
+
) -> None:
|
|
237
|
+
"""Read Tor stdout/stderr until 100% bootstrap or timeout."""
|
|
238
|
+
timeout = self._config.effective_bootstrap_timeout()
|
|
239
|
+
bootstrapped_event = threading.Event()
|
|
240
|
+
failure_reason: list[str] = []
|
|
241
|
+
|
|
242
|
+
def _reader() -> None:
|
|
243
|
+
proc = self._process
|
|
244
|
+
if proc is None or proc.stdout is None:
|
|
245
|
+
return
|
|
246
|
+
try:
|
|
247
|
+
for raw_line in proc.stdout:
|
|
248
|
+
line = raw_line.rstrip("\r\n")
|
|
249
|
+
if not line:
|
|
250
|
+
continue
|
|
251
|
+
self._recent_logs.append(line)
|
|
252
|
+
logger.debug("[tor] %s", line)
|
|
253
|
+
|
|
254
|
+
match = _BOOTSTRAP_RE.search(line)
|
|
255
|
+
if match:
|
|
256
|
+
pct = int(match.group(1))
|
|
257
|
+
msg = match.group(3) or match.group(2) or ""
|
|
258
|
+
if on_progress:
|
|
259
|
+
try:
|
|
260
|
+
on_progress(pct, msg)
|
|
261
|
+
except Exception:
|
|
262
|
+
pass
|
|
263
|
+
if pct >= 100:
|
|
264
|
+
bootstrapped_event.set()
|
|
265
|
+
except ValueError:
|
|
266
|
+
# Stream closed during stop()
|
|
267
|
+
pass
|
|
268
|
+
|
|
269
|
+
if not bootstrapped_event.is_set() and not self._stopping:
|
|
270
|
+
failure_reason.append("Tor process exited before finishing bootstrap.")
|
|
271
|
+
bootstrapped_event.set()
|
|
272
|
+
|
|
273
|
+
reader_thread = threading.Thread(target=_reader, daemon=True, name="torwire-bootstrap")
|
|
274
|
+
reader_thread.start()
|
|
275
|
+
|
|
276
|
+
finished = bootstrapped_event.wait(timeout=timeout)
|
|
277
|
+
if not finished:
|
|
278
|
+
self.stop()
|
|
279
|
+
tail = "\n".join(self._recent_logs)
|
|
280
|
+
raise BootstrapError(
|
|
281
|
+
f"Tor bootstrap timed out after {timeout:.0f}s. "
|
|
282
|
+
f"Your network may block Tor; try bridges=[...].\nRecent logs:\n{tail}"
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
if failure_reason:
|
|
286
|
+
self.stop()
|
|
287
|
+
tail = "\n".join(self._recent_logs)
|
|
288
|
+
raise BootstrapError(f"{failure_reason[0]}\nRecent logs:\n{tail}")
|
|
289
|
+
|
|
290
|
+
# Keep draining stdout in background so the pipe never fills up
|
|
291
|
+
def _drain() -> None:
|
|
292
|
+
proc = self._process
|
|
293
|
+
if proc is None or proc.stdout is None:
|
|
294
|
+
return
|
|
295
|
+
try:
|
|
296
|
+
for raw_line in proc.stdout:
|
|
297
|
+
line = raw_line.rstrip("\r\n")
|
|
298
|
+
if line:
|
|
299
|
+
self._recent_logs.append(line)
|
|
300
|
+
except (ValueError, OSError):
|
|
301
|
+
pass
|
|
302
|
+
|
|
303
|
+
if reader_thread.is_alive():
|
|
304
|
+
# reader_thread continues reading until EOF
|
|
305
|
+
pass
|
|
306
|
+
else:
|
|
307
|
+
threading.Thread(target=_drain, daemon=True, name="torwire-drain").start()
|
|
308
|
+
|
|
309
|
+
@staticmethod
|
|
310
|
+
def _remove_dir_with_retry(path: Path, retries: int = 5) -> None:
|
|
311
|
+
"""Remove a directory tree, retrying briefly on Windows file locks."""
|
|
312
|
+
for attempt in range(retries):
|
|
313
|
+
try:
|
|
314
|
+
shutil.rmtree(path)
|
|
315
|
+
return
|
|
316
|
+
except OSError:
|
|
317
|
+
if attempt == retries - 1:
|
|
318
|
+
shutil.rmtree(path, ignore_errors=True)
|
|
319
|
+
return
|
|
320
|
+
time.sleep(0.2 * (attempt + 1))
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
class _Watchdog:
|
|
324
|
+
"""Background daemon thread that restarts Tor if it dies unexpectedly."""
|
|
325
|
+
|
|
326
|
+
def __init__(
|
|
327
|
+
self,
|
|
328
|
+
process: TorProcess,
|
|
329
|
+
interval: float = 10.0,
|
|
330
|
+
max_restarts: int = 5,
|
|
331
|
+
on_restart: Callable[[], None] | None = None,
|
|
332
|
+
) -> None:
|
|
333
|
+
self._process = process
|
|
334
|
+
self._interval = interval
|
|
335
|
+
self._max_restarts = max_restarts
|
|
336
|
+
self._on_restart = on_restart
|
|
337
|
+
self._stop_event = threading.Event()
|
|
338
|
+
self._thread: threading.Thread | None = None
|
|
339
|
+
self._restarts = 0
|
|
340
|
+
|
|
341
|
+
def start(self) -> None:
|
|
342
|
+
"""Start the watchdog thread."""
|
|
343
|
+
if self._thread is not None and self._thread.is_alive():
|
|
344
|
+
return
|
|
345
|
+
self._stop_event.clear()
|
|
346
|
+
self._thread = threading.Thread(
|
|
347
|
+
target=self._run,
|
|
348
|
+
daemon=True,
|
|
349
|
+
name="torwire-watchdog",
|
|
350
|
+
)
|
|
351
|
+
self._thread.start()
|
|
352
|
+
|
|
353
|
+
def stop(self) -> None:
|
|
354
|
+
"""Signal the watchdog thread to stop and wait briefly."""
|
|
355
|
+
self._stop_event.set()
|
|
356
|
+
if self._thread is not None and self._thread.is_alive():
|
|
357
|
+
self._thread.join(timeout=2.0)
|
|
358
|
+
self._thread = None
|
|
359
|
+
|
|
360
|
+
def _run(self) -> None:
|
|
361
|
+
while not self._stop_event.wait(timeout=self._interval):
|
|
362
|
+
if self._process.is_alive:
|
|
363
|
+
continue
|
|
364
|
+
|
|
365
|
+
if self._restarts >= self._max_restarts:
|
|
366
|
+
logger.error(
|
|
367
|
+
"Tor died and max_restarts (%d) reached; watchdog stopping.",
|
|
368
|
+
self._max_restarts,
|
|
369
|
+
)
|
|
370
|
+
return
|
|
371
|
+
|
|
372
|
+
self._restarts += 1
|
|
373
|
+
logger.warning(
|
|
374
|
+
"Tor process died; restarting (attempt %d/%d)...",
|
|
375
|
+
self._restarts,
|
|
376
|
+
self._max_restarts,
|
|
377
|
+
)
|
|
378
|
+
try:
|
|
379
|
+
self._process.start()
|
|
380
|
+
if self._on_restart:
|
|
381
|
+
self._on_restart()
|
|
382
|
+
except Exception as exc:
|
|
383
|
+
logger.error("Watchdog failed to restart Tor: %s", exc)
|
torwire/py.typed
ADDED
|
File without changes
|
torwire/rotation.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""Automatic IP rotation policies and background timer for torwire."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Callable, Protocol, runtime_checkable
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger("torwire")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class RequestStats:
|
|
16
|
+
"""Statistics evaluated by :class:`RotationPolicy` implementations."""
|
|
17
|
+
|
|
18
|
+
total_requests: int = 0
|
|
19
|
+
elapsed_seconds: float = 0.0
|
|
20
|
+
last_status_code: int | None = None
|
|
21
|
+
last_exception: BaseException | None = None
|
|
22
|
+
requests_since_rotation: int = 0
|
|
23
|
+
time_since_rotation: float = 0.0
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@runtime_checkable
|
|
27
|
+
class RotationPolicy(Protocol):
|
|
28
|
+
"""Protocol for policies that decide when to switch Tor identities."""
|
|
29
|
+
|
|
30
|
+
def should_rotate(self, stats: RequestStats) -> bool:
|
|
31
|
+
"""Return ``True`` if a new Tor identity should be requested."""
|
|
32
|
+
...
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class EveryNSeconds:
|
|
36
|
+
"""Rotate identity after *seconds* have elapsed since the last rotation."""
|
|
37
|
+
|
|
38
|
+
def __init__(self, seconds: float) -> None:
|
|
39
|
+
if seconds <= 0:
|
|
40
|
+
raise ValueError("seconds must be positive")
|
|
41
|
+
self.seconds = seconds
|
|
42
|
+
|
|
43
|
+
def should_rotate(self, stats: RequestStats) -> bool:
|
|
44
|
+
"""Return ``True`` when ``time_since_rotation >= self.seconds``."""
|
|
45
|
+
return stats.time_since_rotation >= self.seconds
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class EveryNRequests:
|
|
49
|
+
"""Rotate identity after *n* requests have been made since the last rotation."""
|
|
50
|
+
|
|
51
|
+
def __init__(self, n: int) -> None:
|
|
52
|
+
if n < 1:
|
|
53
|
+
raise ValueError("n must be at least 1")
|
|
54
|
+
self.n = n
|
|
55
|
+
|
|
56
|
+
def should_rotate(self, stats: RequestStats) -> bool:
|
|
57
|
+
"""Return ``True`` when ``requests_since_rotation >= self.n``."""
|
|
58
|
+
return stats.requests_since_rotation >= self.n
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class OnStatus:
|
|
62
|
+
"""Rotate identity when an HTTP response has a matching status code."""
|
|
63
|
+
|
|
64
|
+
def __init__(self, status_codes: set[int]) -> None:
|
|
65
|
+
self.status_codes = set(status_codes)
|
|
66
|
+
|
|
67
|
+
def should_rotate(self, stats: RequestStats) -> bool:
|
|
68
|
+
"""Return ``True`` if ``last_status_code`` is in ``status_codes``."""
|
|
69
|
+
return stats.last_status_code in self.status_codes
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class OnException:
|
|
73
|
+
"""Rotate identity when a request raises a matching exception type."""
|
|
74
|
+
|
|
75
|
+
def __init__(self, exception_types: tuple[type[BaseException], ...]) -> None:
|
|
76
|
+
self.exception_types = exception_types
|
|
77
|
+
|
|
78
|
+
def should_rotate(self, stats: RequestStats) -> bool:
|
|
79
|
+
"""Return ``True`` if ``last_exception`` is an instance of ``exception_types``."""
|
|
80
|
+
if stats.last_exception is None:
|
|
81
|
+
return False
|
|
82
|
+
return isinstance(stats.last_exception, self.exception_types)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class Composite:
|
|
86
|
+
"""Combine multiple rotation policies using logical OR."""
|
|
87
|
+
|
|
88
|
+
def __init__(self, *policies: RotationPolicy) -> None:
|
|
89
|
+
self.policies = policies
|
|
90
|
+
|
|
91
|
+
def should_rotate(self, stats: RequestStats) -> bool:
|
|
92
|
+
"""Return ``True`` if any composed policy recommends rotation."""
|
|
93
|
+
return any(policy.should_rotate(stats) for policy in self.policies)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class _RotationTimer:
|
|
97
|
+
"""Background daemon thread that triggers rotation on a time-based policy."""
|
|
98
|
+
|
|
99
|
+
def __init__(
|
|
100
|
+
self,
|
|
101
|
+
policy: RotationPolicy,
|
|
102
|
+
rotate_fn: Callable[[], object],
|
|
103
|
+
check_interval: float = 1.0,
|
|
104
|
+
) -> None:
|
|
105
|
+
self._policy = policy
|
|
106
|
+
self._rotate_fn = rotate_fn
|
|
107
|
+
self._check_interval = check_interval
|
|
108
|
+
self._stop_event = threading.Event()
|
|
109
|
+
self._thread: threading.Thread | None = None
|
|
110
|
+
self._start_time = time.monotonic()
|
|
111
|
+
self._last_rotation = self._start_time
|
|
112
|
+
|
|
113
|
+
def start(self) -> None:
|
|
114
|
+
"""Start the background rotation timer thread."""
|
|
115
|
+
if self._thread is not None and self._thread.is_alive():
|
|
116
|
+
return
|
|
117
|
+
now = time.monotonic()
|
|
118
|
+
self._start_time = now
|
|
119
|
+
self._last_rotation = now
|
|
120
|
+
self._stop_event.clear()
|
|
121
|
+
self._thread = threading.Thread(
|
|
122
|
+
target=self._run,
|
|
123
|
+
daemon=True,
|
|
124
|
+
name="torwire-rotation-timer",
|
|
125
|
+
)
|
|
126
|
+
self._thread.start()
|
|
127
|
+
|
|
128
|
+
def stop(self) -> None:
|
|
129
|
+
"""Stop the background rotation timer thread."""
|
|
130
|
+
self._stop_event.set()
|
|
131
|
+
if self._thread is not None and self._thread.is_alive():
|
|
132
|
+
self._thread.join(timeout=2.0)
|
|
133
|
+
self._thread = None
|
|
134
|
+
|
|
135
|
+
def _run(self) -> None:
|
|
136
|
+
while not self._stop_event.wait(timeout=self._check_interval):
|
|
137
|
+
now = time.monotonic()
|
|
138
|
+
stats = RequestStats(
|
|
139
|
+
elapsed_seconds=now - self._start_time,
|
|
140
|
+
time_since_rotation=now - self._last_rotation,
|
|
141
|
+
)
|
|
142
|
+
if self._policy.should_rotate(stats):
|
|
143
|
+
try:
|
|
144
|
+
self._rotate_fn()
|
|
145
|
+
except Exception as exc:
|
|
146
|
+
logger.warning("Auto-rotation failed: %s", exc)
|
|
147
|
+
finally:
|
|
148
|
+
self._last_rotation = time.monotonic()
|