switchback 0.6.3__tar.gz → 0.7.1__tar.gz
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.
- {switchback-0.6.3 → switchback-0.7.1}/.env.example +2 -0
- {switchback-0.6.3 → switchback-0.7.1}/CHANGELOG.md +20 -0
- {switchback-0.6.3 → switchback-0.7.1}/PKG-INFO +3 -1
- {switchback-0.6.3 → switchback-0.7.1}/README.md +2 -0
- {switchback-0.6.3 → switchback-0.7.1}/pyproject.toml +1 -1
- {switchback-0.6.3 → switchback-0.7.1}/switchback/policy/botwall.py +63 -6
- switchback-0.7.1/switchback/tiers/tier_4.py +188 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback.egg-info/PKG-INFO +3 -1
- switchback-0.6.3/switchback/tiers/tier_4.py +0 -101
- {switchback-0.6.3 → switchback-0.7.1}/CONTRIBUTING.md +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/LICENSE +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/MANIFEST.in +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/NOTICE +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/SECURITY.md +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/clients/node_bridge.md +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/clients/python_client.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/config/botwall_skip_urls.txt +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/config/extraction.example.json +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/setup.cfg +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/__init__.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/__main__.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/api.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/concurrency.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/content_cache.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/doctor.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/egress.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/extract.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/flags.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/highlights.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/mcp_server.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/normalize.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/orchestrator.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/policy/__init__.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/policy/gates.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/py.typed +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/reporting.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/search.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/server.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/session_cache.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/session_trace.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/state.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/tiers/__init__.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/tiers/_browser.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/tiers/tier_1.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/tiers/tier_2.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/tiers/tier_3.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/tiers/tier_5.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/tiers/tier_6.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/tiers/tier_7.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback/tracing.py +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback.egg-info/SOURCES.txt +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback.egg-info/dependency_links.txt +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback.egg-info/entry_points.txt +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback.egg-info/requires.txt +0 -0
- {switchback-0.6.3 → switchback-0.7.1}/switchback.egg-info/top_level.txt +0 -0
|
@@ -70,6 +70,8 @@ SCRAPER_DEADLINE_S=45
|
|
|
70
70
|
# 1 matches the sequential design; raise only if the box has RAM headroom and
|
|
71
71
|
# you scrape in parallel.
|
|
72
72
|
SCRAPER_BROWSER_CONCURRENCY=1
|
|
73
|
+
# Keep one Chromium up this many idle seconds between URLs (0 = launch one per URL).
|
|
74
|
+
# SCRAPER_BROWSER_KEEPALIVE_S=60
|
|
73
75
|
|
|
74
76
|
# ── State ───────────────────────────────────────────────────────────────────
|
|
75
77
|
# Where the botwall DB + JSONL event log live (default: ./state).
|
|
@@ -4,6 +4,26 @@ All notable changes to this project are documented here. Format loosely follows
|
|
|
4
4
|
[Keep a Changelog](https://keepachangelog.com/); this project uses semantic-ish
|
|
5
5
|
versioning while pre-1.0.
|
|
6
6
|
|
|
7
|
+
## [0.7.1] - 2026-12-05
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
- **Opt-in kept browser: `SCRAPER_BROWSER_KEEPALIVE_S`.** The Chromium tier
|
|
11
|
+
launched and closed a browser for every URL, which is most of a simple page's
|
|
12
|
+
cost. Set this to N > 0 and one thread keeps a browser up between URLs (each
|
|
13
|
+
URL still gets its own context) and closes it after N idle seconds or a failed
|
|
14
|
+
render. A kept browser renders one page at a time. Unset or 0, nothing changes.
|
|
15
|
+
|
|
16
|
+
## [0.7.0] - 2026-10-17
|
|
17
|
+
|
|
18
|
+
### Added
|
|
19
|
+
- **Opt-in log retention: `SCRAPER_BOTWALL_LOG_RETENTION_DAYS`.** The botwall
|
|
20
|
+
audit logs (`botwall_events.jsonl`, `botwall_excluded.jsonl`,
|
|
21
|
+
`botwall_excluded.log`) only ever grew. Set this to N > 0 to keep the last N
|
|
22
|
+
days: the logging path trims them at most once an hour per process, streaming
|
|
23
|
+
through a temp file and `os.replace` that keeps the file's permissions. Lines without a
|
|
24
|
+
readable timestamp are kept, and a failed trim only logs a warning. The
|
|
25
|
+
default 0 keeps everything, as before; `botwall_db.json` is never trimmed.
|
|
26
|
+
|
|
7
27
|
## [0.6.3] - 2026-10-14
|
|
8
28
|
|
|
9
29
|
### Fixed
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: switchback
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.7.1
|
|
4
4
|
Summary: One cost-ordered scrape cascade (HTTP → stealth browser → paid), shared by every tool.
|
|
5
5
|
Author-email: Akash Kodavuru <akash@theaklabs.com>
|
|
6
6
|
License: MIT
|
|
@@ -412,8 +412,10 @@ export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
|
|
|
412
412
|
- `SCRAPER_FIRECRAWL_FALLBACK_AFTER_S` — after this many seconds on a URL, stop trying the local tiers and fall back to Firecrawl, so a hard host doesn't burn the whole deadline before the paid last resort gets a turn (25s; 0 = off)
|
|
413
413
|
- `SCRAPER_TIER_<N>_TIMEOUT_S` — per-tier timeout in seconds, `N` = 1–7 (tier_1 apis · tier_2 http · tier_3 cloudscraper · tier_4 browser · tier_5 camoufox · tier_6 residential · tier_7 firecrawl). Defaults: 15/15/**25**/15/**45**/**30**/15 (the three bold ones keep their prior budgets; everything else is 15s). The pre-0.5.0 `SCRAPER_CLOUDSCRAPER_TIMEOUT_S` / `SCRAPER_CAMOUFOX_TIMEOUT_MS` / `SCRAPER_RESIDENTIAL_TIMEOUT_MS` are still honored when the new var is unset. Note: `tier_7` (Firecrawl) was previously unbounded — its 15s default now bounds the paid tier, so raise `SCRAPER_TIER_7_TIMEOUT_S` if slow hosts get cut off
|
|
414
414
|
- `SCRAPER_BROWSER_CONCURRENCY` — max simultaneous headless browsers (default 1)
|
|
415
|
+
- `SCRAPER_BROWSER_KEEPALIVE_S` — keep one Chromium up this many idle seconds between URLs instead of launching one per URL (default 0, off); renders one page at a time
|
|
415
416
|
- `SCRAPER_BOTWALL_URL_SKIP_COOLDOWN_H` — auto-skip re-test window (24h; 0 = never)
|
|
416
417
|
- `SCRAPER_BOTWALL_EGRESS_AFTER` — local-tier failures before a host escalates to the residential tier (default 2)
|
|
418
|
+
- `SCRAPER_BOTWALL_LOG_RETENTION_DAYS` — keep only the last N days of `botwall_events.jsonl` / `botwall_excluded.jsonl` / `botwall_excluded.log`, trimmed at most hourly (**0 = keep everything**, the default)
|
|
417
419
|
- `SCRAPER_SESSION_TTL_S` — cf_clearance reuse window (1800s)
|
|
418
420
|
- `SCRAPER_DISABLE_SESSION_CACHE` — turn off cf_clearance reuse
|
|
419
421
|
- `SCRAPER_CONTENT_TTL_S` — URL→result cache TTL (**0 = off**; set e.g. 86400 to skip re-scraping a page within a day)
|
|
@@ -347,8 +347,10 @@ export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
|
|
|
347
347
|
- `SCRAPER_FIRECRAWL_FALLBACK_AFTER_S` — after this many seconds on a URL, stop trying the local tiers and fall back to Firecrawl, so a hard host doesn't burn the whole deadline before the paid last resort gets a turn (25s; 0 = off)
|
|
348
348
|
- `SCRAPER_TIER_<N>_TIMEOUT_S` — per-tier timeout in seconds, `N` = 1–7 (tier_1 apis · tier_2 http · tier_3 cloudscraper · tier_4 browser · tier_5 camoufox · tier_6 residential · tier_7 firecrawl). Defaults: 15/15/**25**/15/**45**/**30**/15 (the three bold ones keep their prior budgets; everything else is 15s). The pre-0.5.0 `SCRAPER_CLOUDSCRAPER_TIMEOUT_S` / `SCRAPER_CAMOUFOX_TIMEOUT_MS` / `SCRAPER_RESIDENTIAL_TIMEOUT_MS` are still honored when the new var is unset. Note: `tier_7` (Firecrawl) was previously unbounded — its 15s default now bounds the paid tier, so raise `SCRAPER_TIER_7_TIMEOUT_S` if slow hosts get cut off
|
|
349
349
|
- `SCRAPER_BROWSER_CONCURRENCY` — max simultaneous headless browsers (default 1)
|
|
350
|
+
- `SCRAPER_BROWSER_KEEPALIVE_S` — keep one Chromium up this many idle seconds between URLs instead of launching one per URL (default 0, off); renders one page at a time
|
|
350
351
|
- `SCRAPER_BOTWALL_URL_SKIP_COOLDOWN_H` — auto-skip re-test window (24h; 0 = never)
|
|
351
352
|
- `SCRAPER_BOTWALL_EGRESS_AFTER` — local-tier failures before a host escalates to the residential tier (default 2)
|
|
353
|
+
- `SCRAPER_BOTWALL_LOG_RETENTION_DAYS` — keep only the last N days of `botwall_events.jsonl` / `botwall_excluded.jsonl` / `botwall_excluded.log`, trimmed at most hourly (**0 = keep everything**, the default)
|
|
352
354
|
- `SCRAPER_SESSION_TTL_S` — cf_clearance reuse window (1800s)
|
|
353
355
|
- `SCRAPER_DISABLE_SESSION_CACHE` — turn off cf_clearance reuse
|
|
354
356
|
- `SCRAPER_CONTENT_TTL_S` — URL→result cache TTL (**0 = off**; set e.g. 86400 to skip re-scraping a page within a day)
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "switchback"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.7.1"
|
|
8
8
|
description = "One cost-ordered scrape cascade (HTTP → stealth browser → paid), shared by every tool."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -24,6 +24,7 @@ import json
|
|
|
24
24
|
import logging
|
|
25
25
|
import os
|
|
26
26
|
import threading
|
|
27
|
+
import time
|
|
27
28
|
from datetime import datetime, timezone
|
|
28
29
|
|
|
29
30
|
from .gates import host_of
|
|
@@ -69,6 +70,11 @@ SEED_HOSTS = {
|
|
|
69
70
|
# When true, each time Firecrawl is invoked for a host it counts as a failure
|
|
70
71
|
# toward the domain skip threshold (original v1 behaviour). No effect if
|
|
71
72
|
# SCRAPER_BOTWALL_DOMAIN_SKIP_AFTER is 0.
|
|
73
|
+
#
|
|
74
|
+
# SCRAPER_BOTWALL_LOG_RETENTION_DAYS int ≥0, default 0 (keep everything)
|
|
75
|
+
# When >0, botwall_events.jsonl, botwall_excluded.jsonl and botwall_excluded.log
|
|
76
|
+
# are trimmed to the last N days, at most once an hour per process. Lines
|
|
77
|
+
# without a readable timestamp are kept. botwall_db.json is never trimmed.
|
|
72
78
|
|
|
73
79
|
def _int_env(name: str, default: int) -> int:
|
|
74
80
|
try:
|
|
@@ -92,6 +98,10 @@ URL_SKIP_COOLDOWN_H = _int_env("SCRAPER_BOTWALL_URL_SKIP_COOLDOWN_H", 24)
|
|
|
92
98
|
# residential tier. 0 disables escalation.
|
|
93
99
|
PROMOTE_EGRESS_AFTER = _int_env("SCRAPER_BOTWALL_EGRESS_AFTER", 2)
|
|
94
100
|
|
|
101
|
+
LOG_RETENTION_DAYS = _int_env("SCRAPER_BOTWALL_LOG_RETENTION_DAYS", 0)
|
|
102
|
+
_LOG_LOCK = threading.Lock() # appends vs. the trim's rewrite, within this process
|
|
103
|
+
_last_trim = 0.0
|
|
104
|
+
|
|
95
105
|
# Outcomes a *single URL* is excluded for (deterministic per-URL failures). A 429
|
|
96
106
|
# is deliberately excluded — it's transient, so it escalates egress but never
|
|
97
107
|
# permanently skips the URL.
|
|
@@ -247,12 +257,57 @@ def _log_event(url, tier, outcome, md_len=None, error=None, latency_ms=None,
|
|
|
247
257
|
"outcome": outcome, "md_len": md_len, "latency_ms": latency_ms,
|
|
248
258
|
"error": error, "status_code": status_code, "challenge": challenge}
|
|
249
259
|
try:
|
|
250
|
-
with
|
|
251
|
-
|
|
260
|
+
with _LOG_LOCK:
|
|
261
|
+
with open(EVENTS_PATH, "a") as f:
|
|
262
|
+
f.write(json.dumps(ev) + "\n")
|
|
263
|
+
_maybe_trim_logs()
|
|
252
264
|
except Exception as e:
|
|
253
265
|
logger.warning(f"botwall: event log failed: {e}")
|
|
254
266
|
|
|
255
267
|
|
|
268
|
+
def _line_ts(line: str):
|
|
269
|
+
"""A log line's timestamp: JSON `ts`, else the first token (.log lines)."""
|
|
270
|
+
try:
|
|
271
|
+
return json.loads(line)["ts"]
|
|
272
|
+
except Exception:
|
|
273
|
+
parts = line.split(None, 1)
|
|
274
|
+
return parts[0] if parts else None
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _maybe_trim_logs() -> None:
|
|
278
|
+
"""Drop log lines older than LOG_RETENTION_DAYS. Caller holds _LOG_LOCK.
|
|
279
|
+
|
|
280
|
+
shortcut: another process appending during the os.replace loses that line;
|
|
281
|
+
fine for an audit log, use a file lock if several processes share a state dir."""
|
|
282
|
+
global _last_trim
|
|
283
|
+
if LOG_RETENTION_DAYS <= 0 or time.time() - _last_trim < 3600:
|
|
284
|
+
return
|
|
285
|
+
_last_trim = time.time()
|
|
286
|
+
max_age = LOG_RETENTION_DAYS * 86400
|
|
287
|
+
for path in (EVENTS_PATH, EXCLUDED_JSONL, EXCLUDED_LOG):
|
|
288
|
+
tmp = f"{path}.tmp.{os.getpid()}"
|
|
289
|
+
try:
|
|
290
|
+
if not os.path.exists(path):
|
|
291
|
+
continue
|
|
292
|
+
dropped = 0
|
|
293
|
+
# Streamed line by line: a log that only ever grew can be far larger than memory.
|
|
294
|
+
with open(path) as src, open(tmp, "w") as dst:
|
|
295
|
+
for ln in src:
|
|
296
|
+
if (age := _age_seconds(_line_ts(ln))) is None or age < max_age:
|
|
297
|
+
dst.write(ln)
|
|
298
|
+
else:
|
|
299
|
+
dropped += 1
|
|
300
|
+
if not dropped:
|
|
301
|
+
os.unlink(tmp)
|
|
302
|
+
continue
|
|
303
|
+
os.chmod(tmp, os.stat(path).st_mode & 0o7777)
|
|
304
|
+
os.replace(tmp, path)
|
|
305
|
+
except Exception as e:
|
|
306
|
+
logger.warning(f"botwall: log trim failed for {path}: {e}")
|
|
307
|
+
if os.path.exists(tmp):
|
|
308
|
+
os.unlink(tmp)
|
|
309
|
+
|
|
310
|
+
|
|
256
311
|
def log_final(url: str, outcome: str, latency_ms=None, error=None,
|
|
257
312
|
status_code=None) -> None:
|
|
258
313
|
"""Write one aggregate event for a URL's final cascade result (all_failed /
|
|
@@ -283,10 +338,12 @@ def _log_exclusion(url: str, reason: str) -> None:
|
|
|
283
338
|
"""Write to both the structured JSONL and the human-readable log."""
|
|
284
339
|
ev = {"ts": _now(), "url": url, "host": host_of(url), "reason": reason}
|
|
285
340
|
try:
|
|
286
|
-
with
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
341
|
+
with _LOG_LOCK:
|
|
342
|
+
with open(EXCLUDED_JSONL, "a") as f:
|
|
343
|
+
f.write(json.dumps(ev) + "\n")
|
|
344
|
+
with open(EXCLUDED_LOG, "a") as f:
|
|
345
|
+
f.write(f"{ev['ts']} EXCLUDED {url} [{reason}]\n")
|
|
346
|
+
_maybe_trim_logs()
|
|
290
347
|
except Exception as e:
|
|
291
348
|
logger.warning(f"botwall: exclusion log failed: {e}")
|
|
292
349
|
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Tier 3 — stealth headless browser (patchright).
|
|
2
|
+
|
|
3
|
+
Renders JS-heavy SPAs. patchright is a hardened Playwright fork that evades the
|
|
4
|
+
common automation fingerprints. Tries domcontentloaded first, then networkidle
|
|
5
|
+
if the DOM is suspiciously small (lazy/JS content).
|
|
6
|
+
|
|
7
|
+
SCRAPER_BROWSER_KEEPALIVE_S keeps one browser up between URLs (see below).
|
|
8
|
+
|
|
9
|
+
Future: browser-harness mode to drive the user's logged-in Chrome over CDP for
|
|
10
|
+
auth-walled pages (set BU_CDP_URL).
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
import queue
|
|
16
|
+
import threading
|
|
17
|
+
from concurrent.futures import Future
|
|
18
|
+
|
|
19
|
+
from . import _browser
|
|
20
|
+
from .. import session_cache, session_trace
|
|
21
|
+
from ..concurrency import browser_slot
|
|
22
|
+
from ..egress import playwright_proxy, add_wire_bytes
|
|
23
|
+
from ..normalize import html_to_markdown
|
|
24
|
+
from ..policy.gates import Unavailable, check
|
|
25
|
+
|
|
26
|
+
NAME = "tier_4"
|
|
27
|
+
PAID = False
|
|
28
|
+
|
|
29
|
+
# Per-tier navigation timeout (seconds); override with SCRAPER_TIER_4_TIMEOUT_S.
|
|
30
|
+
_TIMEOUT_S = float(os.getenv("SCRAPER_TIER_4_TIMEOUT_S", "15"))
|
|
31
|
+
|
|
32
|
+
# Install hint surfaced when patchright or its Chromium isn't ready — notably
|
|
33
|
+
# during an async cold-start install (the browser binary lands after boot).
|
|
34
|
+
_INSTALL_HINT = 'pip install "switchback[browser]" && patchright install chromium'
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def available() -> tuple[bool, str]:
|
|
38
|
+
"""Whether patchright is importable *and* its Chromium is downloaded.
|
|
39
|
+
Returns (ok, detail). On a cold start where the browser is installed by a
|
|
40
|
+
background thread, this flips to True once that finishes. Used by `fetch`
|
|
41
|
+
(clear `unavailable` reason instead of a buried launch error) and by
|
|
42
|
+
`switchback doctor`."""
|
|
43
|
+
try:
|
|
44
|
+
from patchright.sync_api import sync_playwright
|
|
45
|
+
except ImportError:
|
|
46
|
+
return False, f"patchright not installed — {_INSTALL_HINT}"
|
|
47
|
+
try:
|
|
48
|
+
with sync_playwright() as p:
|
|
49
|
+
exe = p.chromium.executable_path
|
|
50
|
+
except Exception as e: # pragma: no cover — driver start is environment-specific
|
|
51
|
+
return False, f"patchright driver error: {e}"
|
|
52
|
+
if not exe or not os.path.exists(exe):
|
|
53
|
+
return False, f"patchright Chromium not installed — {_INSTALL_HINT}"
|
|
54
|
+
return True, "patchright + Chromium ready"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _keepalive_s() -> float:
|
|
58
|
+
"""Seconds an idle Chromium stays up for the next URL (SCRAPER_BROWSER_KEEPALIVE_S).
|
|
59
|
+
0, the default, launches and closes a browser per URL."""
|
|
60
|
+
try:
|
|
61
|
+
return max(0.0, float(os.getenv("SCRAPER_BROWSER_KEEPALIVE_S") or 0))
|
|
62
|
+
except ValueError:
|
|
63
|
+
return 0.0
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _launch(p, proxy=None):
|
|
67
|
+
try:
|
|
68
|
+
return p.chromium.launch(headless=True, proxy=proxy)
|
|
69
|
+
except Exception as e:
|
|
70
|
+
# Chromium not downloaded yet (cold-start window) reads as a launch
|
|
71
|
+
# error; surface it as unavailable + the fix, not a generic failure.
|
|
72
|
+
msg = str(e)
|
|
73
|
+
if "Executable doesn't exist" in msg or "patchright install" in msg:
|
|
74
|
+
raise Unavailable(
|
|
75
|
+
f"patchright Chromium not installed — {_INSTALL_HINT}")
|
|
76
|
+
raise
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _render(browser, url: str, timeout_ms: int, proxy=None) -> tuple[str, int]:
|
|
80
|
+
"""One URL in its own context: (markdown, wire bytes). `proxy` is for a kept
|
|
81
|
+
browser, which is launched without one and takes it per context."""
|
|
82
|
+
ctx = None
|
|
83
|
+
try:
|
|
84
|
+
# No user_agent override: patchright ships a real, internally
|
|
85
|
+
# consistent Chromium fingerprint; overriding the UA desyncs it from
|
|
86
|
+
# the engine version / client hints and defeats the stealth fork.
|
|
87
|
+
opts = _browser.context_options()
|
|
88
|
+
if proxy:
|
|
89
|
+
opts["proxy"] = proxy
|
|
90
|
+
ctx = browser.new_context(**opts)
|
|
91
|
+
_browser.block_private_networks(ctx)
|
|
92
|
+
session_trace.start(ctx, url)
|
|
93
|
+
auth = session_cache.browser_cookies(url)
|
|
94
|
+
if auth:
|
|
95
|
+
ctx.add_cookies(auth)
|
|
96
|
+
page = ctx.new_page()
|
|
97
|
+
responses: list = []
|
|
98
|
+
page.on("response", lambda resp: responses.append(resp))
|
|
99
|
+
_browser.raise_if_missing(page.goto(url, timeout=timeout_ms, wait_until="domcontentloaded"))
|
|
100
|
+
html = page.content()
|
|
101
|
+
if len(html) < 5000:
|
|
102
|
+
try:
|
|
103
|
+
page.wait_for_load_state("networkidle", timeout=8000)
|
|
104
|
+
except Exception:
|
|
105
|
+
pass
|
|
106
|
+
html = page.content()
|
|
107
|
+
# A JS bot-manager (Akamai/Imperva/…) may serve a sensor interstitial
|
|
108
|
+
# first; settle + reload once to get the real page on an acceptable IP.
|
|
109
|
+
if _browser.looks_blocked(html, page.url or url):
|
|
110
|
+
html = _browser.reload_through_challenge(page, url, timeout_ms)
|
|
111
|
+
return html_to_markdown(html, base_url=page.url or url), _browser.response_bytes(responses)
|
|
112
|
+
finally:
|
|
113
|
+
if ctx is not None:
|
|
114
|
+
session_trace.stop(ctx, url)
|
|
115
|
+
ctx.close()
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# --- Kept browser (SCRAPER_BROWSER_KEEPALIVE_S > 0) -----------------------------
|
|
119
|
+
# Launching Chromium is most of a simple page's cost, so one thread keeps a
|
|
120
|
+
# browser up between URLs and closes it once idle. One thread, because sync
|
|
121
|
+
# Playwright objects only work on the thread that made them; so a kept browser
|
|
122
|
+
# renders one page at a time whatever SCRAPER_BROWSER_CONCURRENCY says.
|
|
123
|
+
_jobs: queue.Queue = queue.Queue()
|
|
124
|
+
_worker_lock = threading.Lock()
|
|
125
|
+
_worker: threading.Thread | None = None
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _stop(pw, browser) -> None:
|
|
129
|
+
for closer in (getattr(browser, "close", None), getattr(pw, "stop", None)):
|
|
130
|
+
try:
|
|
131
|
+
if closer:
|
|
132
|
+
closer()
|
|
133
|
+
except Exception:
|
|
134
|
+
pass
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _worker_loop() -> None:
|
|
138
|
+
from patchright.sync_api import sync_playwright
|
|
139
|
+
pw = browser = None
|
|
140
|
+
while True:
|
|
141
|
+
try:
|
|
142
|
+
job = _jobs.get(timeout=_keepalive_s() or 1) if pw else _jobs.get()
|
|
143
|
+
except queue.Empty:
|
|
144
|
+
_stop(pw, browser) # idle: give the memory back
|
|
145
|
+
pw = browser = None
|
|
146
|
+
continue
|
|
147
|
+
done, url, timeout_ms, proxy = job
|
|
148
|
+
try:
|
|
149
|
+
if browser is None or not browser.is_connected():
|
|
150
|
+
_stop(pw, browser)
|
|
151
|
+
pw = browser = None
|
|
152
|
+
pw = sync_playwright().start()
|
|
153
|
+
browser = _launch(pw)
|
|
154
|
+
done.set_result(_render(browser, url, timeout_ms, proxy))
|
|
155
|
+
except BaseException as e:
|
|
156
|
+
done.set_exception(e)
|
|
157
|
+
_stop(pw, browser) # a failed render may leave a sick browser: start clean
|
|
158
|
+
pw = browser = None
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _render_kept(url: str, timeout_ms: int, proxy) -> tuple[str, int]:
|
|
162
|
+
global _worker
|
|
163
|
+
with _worker_lock:
|
|
164
|
+
if _worker is None or not _worker.is_alive():
|
|
165
|
+
_worker = threading.Thread(target=_worker_loop, name="switchback-tier-4", daemon=True)
|
|
166
|
+
_worker.start()
|
|
167
|
+
done: Future = Future()
|
|
168
|
+
_jobs.put((done, url, timeout_ms, proxy))
|
|
169
|
+
return done.result()
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def fetch(url: str, timeout_ms: int = int(_TIMEOUT_S * 1000)) -> str:
|
|
173
|
+
try:
|
|
174
|
+
from patchright.sync_api import sync_playwright
|
|
175
|
+
except ImportError:
|
|
176
|
+
raise Unavailable(f"patchright not installed — {_INSTALL_HINT}")
|
|
177
|
+
with browser_slot(NAME):
|
|
178
|
+
if _keepalive_s():
|
|
179
|
+
md, wire = _render_kept(url, timeout_ms, playwright_proxy())
|
|
180
|
+
else:
|
|
181
|
+
with sync_playwright() as p:
|
|
182
|
+
browser = _launch(p, playwright_proxy())
|
|
183
|
+
try:
|
|
184
|
+
md, wire = _render(browser, url, timeout_ms)
|
|
185
|
+
finally:
|
|
186
|
+
browser.close()
|
|
187
|
+
add_wire_bytes(wire)
|
|
188
|
+
return check(url, md)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: switchback
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.7.1
|
|
4
4
|
Summary: One cost-ordered scrape cascade (HTTP → stealth browser → paid), shared by every tool.
|
|
5
5
|
Author-email: Akash Kodavuru <akash@theaklabs.com>
|
|
6
6
|
License: MIT
|
|
@@ -412,8 +412,10 @@ export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
|
|
|
412
412
|
- `SCRAPER_FIRECRAWL_FALLBACK_AFTER_S` — after this many seconds on a URL, stop trying the local tiers and fall back to Firecrawl, so a hard host doesn't burn the whole deadline before the paid last resort gets a turn (25s; 0 = off)
|
|
413
413
|
- `SCRAPER_TIER_<N>_TIMEOUT_S` — per-tier timeout in seconds, `N` = 1–7 (tier_1 apis · tier_2 http · tier_3 cloudscraper · tier_4 browser · tier_5 camoufox · tier_6 residential · tier_7 firecrawl). Defaults: 15/15/**25**/15/**45**/**30**/15 (the three bold ones keep their prior budgets; everything else is 15s). The pre-0.5.0 `SCRAPER_CLOUDSCRAPER_TIMEOUT_S` / `SCRAPER_CAMOUFOX_TIMEOUT_MS` / `SCRAPER_RESIDENTIAL_TIMEOUT_MS` are still honored when the new var is unset. Note: `tier_7` (Firecrawl) was previously unbounded — its 15s default now bounds the paid tier, so raise `SCRAPER_TIER_7_TIMEOUT_S` if slow hosts get cut off
|
|
414
414
|
- `SCRAPER_BROWSER_CONCURRENCY` — max simultaneous headless browsers (default 1)
|
|
415
|
+
- `SCRAPER_BROWSER_KEEPALIVE_S` — keep one Chromium up this many idle seconds between URLs instead of launching one per URL (default 0, off); renders one page at a time
|
|
415
416
|
- `SCRAPER_BOTWALL_URL_SKIP_COOLDOWN_H` — auto-skip re-test window (24h; 0 = never)
|
|
416
417
|
- `SCRAPER_BOTWALL_EGRESS_AFTER` — local-tier failures before a host escalates to the residential tier (default 2)
|
|
418
|
+
- `SCRAPER_BOTWALL_LOG_RETENTION_DAYS` — keep only the last N days of `botwall_events.jsonl` / `botwall_excluded.jsonl` / `botwall_excluded.log`, trimmed at most hourly (**0 = keep everything**, the default)
|
|
417
419
|
- `SCRAPER_SESSION_TTL_S` — cf_clearance reuse window (1800s)
|
|
418
420
|
- `SCRAPER_DISABLE_SESSION_CACHE` — turn off cf_clearance reuse
|
|
419
421
|
- `SCRAPER_CONTENT_TTL_S` — URL→result cache TTL (**0 = off**; set e.g. 86400 to skip re-scraping a page within a day)
|
|
@@ -1,101 +0,0 @@
|
|
|
1
|
-
"""Tier 3 — stealth headless browser (patchright).
|
|
2
|
-
|
|
3
|
-
Renders JS-heavy SPAs. patchright is a hardened Playwright fork that evades the
|
|
4
|
-
common automation fingerprints. Tries domcontentloaded first, then networkidle
|
|
5
|
-
if the DOM is suspiciously small (lazy/JS content).
|
|
6
|
-
|
|
7
|
-
Future: (a) batch many URLs through one browser (musings does this — big perf
|
|
8
|
-
win); (b) browser-harness mode to drive the user's logged-in Chrome over CDP for
|
|
9
|
-
auth-walled pages (set BU_CDP_URL).
|
|
10
|
-
"""
|
|
11
|
-
from __future__ import annotations
|
|
12
|
-
|
|
13
|
-
import os
|
|
14
|
-
|
|
15
|
-
from . import _browser
|
|
16
|
-
from .. import session_cache, session_trace
|
|
17
|
-
from ..concurrency import browser_slot
|
|
18
|
-
from ..egress import playwright_proxy, add_wire_bytes
|
|
19
|
-
from ..normalize import html_to_markdown
|
|
20
|
-
from ..policy.gates import Unavailable, check
|
|
21
|
-
|
|
22
|
-
NAME = "tier_4"
|
|
23
|
-
PAID = False
|
|
24
|
-
|
|
25
|
-
# Per-tier navigation timeout (seconds); override with SCRAPER_TIER_4_TIMEOUT_S.
|
|
26
|
-
_TIMEOUT_S = float(os.getenv("SCRAPER_TIER_4_TIMEOUT_S", "15"))
|
|
27
|
-
|
|
28
|
-
# Install hint surfaced when patchright or its Chromium isn't ready — notably
|
|
29
|
-
# during an async cold-start install (the browser binary lands after boot).
|
|
30
|
-
_INSTALL_HINT = 'pip install "switchback[browser]" && patchright install chromium'
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
def available() -> tuple[bool, str]:
|
|
34
|
-
"""Whether patchright is importable *and* its Chromium is downloaded.
|
|
35
|
-
Returns (ok, detail). On a cold start where the browser is installed by a
|
|
36
|
-
background thread, this flips to True once that finishes. Used by `fetch`
|
|
37
|
-
(clear `unavailable` reason instead of a buried launch error) and by
|
|
38
|
-
`switchback doctor`."""
|
|
39
|
-
try:
|
|
40
|
-
from patchright.sync_api import sync_playwright
|
|
41
|
-
except ImportError:
|
|
42
|
-
return False, f"patchright not installed — {_INSTALL_HINT}"
|
|
43
|
-
try:
|
|
44
|
-
with sync_playwright() as p:
|
|
45
|
-
exe = p.chromium.executable_path
|
|
46
|
-
except Exception as e: # pragma: no cover — driver start is environment-specific
|
|
47
|
-
return False, f"patchright driver error: {e}"
|
|
48
|
-
if not exe or not os.path.exists(exe):
|
|
49
|
-
return False, f"patchright Chromium not installed — {_INSTALL_HINT}"
|
|
50
|
-
return True, "patchright + Chromium ready"
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
def fetch(url: str, timeout_ms: int = int(_TIMEOUT_S * 1000)) -> str:
|
|
54
|
-
try:
|
|
55
|
-
from patchright.sync_api import sync_playwright
|
|
56
|
-
except ImportError:
|
|
57
|
-
raise Unavailable(f"patchright not installed — {_INSTALL_HINT}")
|
|
58
|
-
with browser_slot(NAME), sync_playwright() as p:
|
|
59
|
-
try:
|
|
60
|
-
browser = p.chromium.launch(headless=True, proxy=playwright_proxy())
|
|
61
|
-
except Exception as e:
|
|
62
|
-
# Chromium not downloaded yet (cold-start window) reads as a launch
|
|
63
|
-
# error; surface it as unavailable + the fix, not a generic failure.
|
|
64
|
-
msg = str(e)
|
|
65
|
-
if "Executable doesn't exist" in msg or "patchright install" in msg:
|
|
66
|
-
raise Unavailable(
|
|
67
|
-
f"patchright Chromium not installed — {_INSTALL_HINT}")
|
|
68
|
-
raise
|
|
69
|
-
ctx = None
|
|
70
|
-
try:
|
|
71
|
-
# No user_agent override: patchright ships a real, internally
|
|
72
|
-
# consistent Chromium fingerprint; overriding the UA desyncs it from
|
|
73
|
-
# the engine version / client hints and defeats the stealth fork.
|
|
74
|
-
ctx = browser.new_context(**_browser.context_options())
|
|
75
|
-
_browser.block_private_networks(ctx)
|
|
76
|
-
session_trace.start(ctx, url)
|
|
77
|
-
auth = session_cache.browser_cookies(url)
|
|
78
|
-
if auth:
|
|
79
|
-
ctx.add_cookies(auth)
|
|
80
|
-
page = ctx.new_page()
|
|
81
|
-
responses: list = []
|
|
82
|
-
page.on("response", lambda resp: responses.append(resp))
|
|
83
|
-
_browser.raise_if_missing(page.goto(url, timeout=timeout_ms, wait_until="domcontentloaded"))
|
|
84
|
-
html = page.content()
|
|
85
|
-
if len(html) < 5000:
|
|
86
|
-
try:
|
|
87
|
-
page.wait_for_load_state("networkidle", timeout=8000)
|
|
88
|
-
except Exception:
|
|
89
|
-
pass
|
|
90
|
-
html = page.content()
|
|
91
|
-
# A JS bot-manager (Akamai/Imperva/…) may serve a sensor interstitial
|
|
92
|
-
# first; settle + reload once to get the real page on an acceptable IP.
|
|
93
|
-
if _browser.looks_blocked(html, page.url or url):
|
|
94
|
-
html = _browser.reload_through_challenge(page, url, timeout_ms)
|
|
95
|
-
add_wire_bytes(_browser.response_bytes(responses))
|
|
96
|
-
md = html_to_markdown(html, base_url=page.url or url)
|
|
97
|
-
finally:
|
|
98
|
-
if ctx is not None:
|
|
99
|
-
session_trace.stop(ctx, url)
|
|
100
|
-
browser.close()
|
|
101
|
-
return check(url, md)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|