SPB Git

Repository Public

_resilient.py 31.1 KB 758 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Fabri·Ka9# File             : fabrika/connectors/_resilient.py10# Module           : fabrika11# Repository       : https://git.spboucher.ai/fabri-ka12# Created          : 2026-08-2213# Last Modified    : 2026-08-2214#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author           : Simon-Pierre Boucher20# Position         : Professor of Finance21# Institution      : Université du Québec en Outaouais (UQO)22# Department       : Département des sciences administratives23# Organization     : SP Boucher24#25# Website          : https://spboucher.ai26# Git              : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General          : info@spboucher.ai33# Professional     : contact@spboucher.ai34# Direct           : simon@spboucher.ai35# Research         : research@spboucher.ai36# Development      : dev@spboucher.ai37# Support          : support@spboucher.ai38# Security/Admin   : admin@spboucher.ai39# Notifications    : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification   : Public66# Distribution     : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License          : None specified (no license file in this repository)80# Maintainer       : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# =============================================================================88# Fabri-Ka — connecteurs : chaîne de fetch anti-bot RÉSILIENTE89# Auteur : Simon-Pierre Boucher <contact@spboucher.ai>90# Fichier : connectors/_resilient.py91# -----------------------------------------------------------------------------92# But : rendre les connecteurs durables dans le temps. Quand un site jusque-là93# ouvert déploie un anti-bot (Cloudflare / Akamai / Incapsula / PerimeterX) ou94# renvoie 403/429/503, la requête directe N'ÉCHOUE PLUS silencieusement : elle95# ESCALADE automatiquement à travers une chaîne de secours :96#97#   1. Direct            — la session du connecteur (curl_cffi impersonate si98#                          dispo, sinon requests) : rapide et gratuit.99#   2. Firecrawl         — navigateur géré + proxy (FIRECRAWL_API_KEY) : premier100#                          recours dès qu'un site BLOQUE (2026-11-26), sous101#                          budget de crédits (par cycle, par hôte, par jour,102#                          par mois : le quota est partagé entre six sites).103#   3. Oxylabs (résid.)  — proxy résidentiel Canada (-cc-CA) : IP propre.104#   4. Scrapfly (ASP)    — bypass anti-bot géré + rendu JS optionnel.105#   5. Bright Data       — Web Unlocker : déblocage premium, dernier recours.106#107# Firecrawl ne sert JAMAIS en première intention : un catalogue qui répond en108# direct (/products.json de Shopify, API Store de WooCommerce) ne consomme109# aucun crédit. Il n'est tenté que si la requête directe est refusée par un110# anti-bot (403/429/503/page-challenge) — voir `host_blocks()`.111#112# Le premier backend qui renvoie un 200 non vide gagne. Si TOUS échouent, on113# renvoie la dernière réponse (avec son code d'erreur) pour que le connecteur114# journalise l'échec comme avant — aucun changement de comportement en cas115# d'échec total, aucun blocage silencieux.116#117# Conception :118#   - Aucun effet de bord à l'import ; toute brique non configurée est sautée.119#   - Les clés sont lues de os.environ, avec repli sur le .env de l'app puis120#     ~/.claude/.env, et acceptent les deux noms Scrapfly (SCRAPFLY_KEY /121#     SCRAPFLY_API_KEY). => aucune modif de .env nécessaire.122#   - `_ResilientResponse` imite requests.Response (.text/.content/.status_code/123#     .url/.headers/.json()/.ok/.raise_for_status()) : les connecteurs existants124#     continuent de fonctionner sans modification.125#   - Coupe-circuit par hôte : après plusieurs escalades totalement infructueuses126#     sur un même hôte, on saute l'escalade payante pendant un temps de repos127#     (évite de brûler du quota Scrapfly/Bright Data sur une source morte).128# =============================================================================129from __future__ import annotations130131import json as _json132import os133import time134from pathlib import Path135from urllib.parse import quote, urlsplit136137import requests138139# -- curl_cffi est OPTIONNEL (meilleur fingerprint TLS s'il est présent) ------140try:  # pragma: no cover141    from curl_cffi import requests as _cffi  # type: ignore142    _HAS_CFFI = True143except Exception:  # noqa: BLE001144    _cffi = None145    _HAS_CFFI = False146147# Codes HTTP typiques d'un blocage anti-bot (≠ 401/404/410/500 « métier » :148# 401 = auth manquante, 403/429 = bot bloqué, 5xx CF = challenge/edge).149BLOCK_STATUS = {403, 429, 503, 520, 521, 522, 523, 524, 526, 1020}150151# Marqueurs de page-challenge (Cloudflare/Akamai/Incapsula/PerimeterX/DataDome).152_CHALLENGE_MARKERS = (153    "just a moment", "cf-browser-verification", "cf-challenge",154    "attention required", "access denied", "request unsuccessful",155    "px-captcha", "perimeterx", "incapsula", "_incapsula_", "datadome",156    "captcha-delivery", "please enable javascript and cookies",157    "checking your browser", "ddos protection by", "sgcaptcha",158    "robot challenge screen",159)160161_UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "162       "(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36")163164# Coupe-circuit en mémoire : hôte -> (timestamp_jusquà, échecs_consécutifs)165_COOLDOWN: dict[str, tuple[float, int]] = {}166_COOLDOWN_HITS = 3           # nb d'échecs totaux avant repos167_COOLDOWN_SECONDS = 900.0    # 15 min de repos pour un hôte « mort »168169# -- chargement paresseux des secrets ----------------------------------------170_ENV_CACHE: dict[str, str] | None = None171172173def _load_env_files() -> dict[str, str]:174    """Parse les .env candidats une seule fois (repli si os.environ vide)."""175    global _ENV_CACHE176    if _ENV_CACHE is not None:177        return _ENV_CACHE178    out: dict[str, str] = {}179    candidates = []180    # .env de l'app (remonte quelques niveaux depuis ce module)181    here = Path(__file__).resolve()182    for up in range(2, 6):183        try:184            candidates.append(here.parents[up] / ".env")185        except IndexError:186            break187    candidates.append(Path.home() / ".claude" / ".env")188    for path in candidates:189        try:190            if not path.is_file():191                continue192            for line in path.read_text(encoding="utf-8", errors="ignore").splitlines():193                line = line.strip()194                if not line or line.startswith("#") or "=" not in line:195                    continue196                k, _, v = line.partition("=")197                k, v = k.strip(), v.strip().strip('"').strip("'")198                # ne pas écraser une valeur déjà trouvée (priorité app > global)199                if k and k not in out:200                    out[k] = v201        except Exception:  # noqa: BLE001202            continue203    _ENV_CACHE = out204    return out205206207def _secret(*names: str) -> str | None:208    """Cherche une clé dans os.environ puis dans les .env (par ordre de noms)."""209    for n in names:210        v = os.environ.get(n)211        if v:212            return v213    env = _load_env_files()214    for n in names:215        v = env.get(n)216        if v:217            return v218    return None219220221# -- réponse compatible requests.Response ------------------------------------222class _ResilientResponse:223    """Imite le minimum utile d'une requests.Response pour les connecteurs."""224225    def __init__(self, url: str, status_code: int, text: str,226                 headers: dict | None = None, via: str = "direct") -> None:227        self.url = url228        self.status_code = int(status_code or 0)229        self._text = text or ""230        self.headers = headers or {}231        self.encoding = "utf-8"232        self.via = via  # backend gagnant (diagnostic)233234    @property235    def text(self) -> str:236        return self._text237238    @property239    def content(self) -> bytes:240        return self._text.encode("utf-8", errors="ignore")241242    @property243    def ok(self) -> bool:244        return 200 <= self.status_code < 400245246    def json(self, **kw):247        return _json.loads(self._text)248249    def raise_for_status(self):250        if 400 <= self.status_code < 600:251            raise requests.HTTPError(252                f"{self.status_code} via {self.via} pour {self.url}",253                response=self)  # type: ignore[arg-type]254        return None255256    def __repr__(self) -> str:  # pragma: no cover257        return f"<_ResilientResponse [{self.status_code}] via {self.via}>"258259260# -- détection de blocage -----------------------------------------------------261def is_blocked(resp) -> bool:262    """True si la réponse ressemble à un blocage anti-bot (≠ erreur métier)."""263    if resp is None:264        return True265    code = getattr(resp, "status_code", 0) or 0266    if code in BLOCK_STATUS:267        return True268    headers = getattr(resp, "headers", None) or {}269    try:270        if "challenge" in str(headers.get("sg-captcha", "")).lower():271            return True                       # SiteGround sgcaptcha (202)272    except Exception:  # noqa: BLE001273        pass274    # 200/202 mais page-challenge servie275    if code in (200, 202):276        try:277            body = (resp.text or "")[:4000].lower()278        except Exception:  # noqa: BLE001279            return False280        server = str(headers.get("Server", "")).lower()281        if any(m in body for m in _CHALLENGE_MARKERS):282            return True283        if "cloudflare" in server and ("captcha" in body or "challenge" in body):284            return True285    return False286287288def _host(url: str) -> str:289    try:290        return urlsplit(url).netloc.lower()291    except Exception:  # noqa: BLE001292        return url293294295def _cooling(host: str) -> bool:296    until, _ = _COOLDOWN.get(host, (0.0, 0))297    return time.time() < until298299300def _note_failure(host: str) -> None:301    until, hits = _COOLDOWN.get(host, (0.0, 0))302    hits += 1303    if hits >= _COOLDOWN_HITS:304        _COOLDOWN[host] = (time.time() + _COOLDOWN_SECONDS, 0)305    else:306        _COOLDOWN[host] = (until, hits)307308309def _note_success(host: str) -> None:310    _COOLDOWN.pop(host, None)311312313314# -- masquage des secrets (journaux, sync_log, exceptions) --------------------315_REDACT_RE = None316317318def redact(text) -> str:319    """Masque toute clé d'API dans un texte destiné à un journal, à sync_log320    ou à un message d'erreur : paramètres `key=` / `token=` / `api_key=` des321    URL de relais, jetons `Bearer`, identifiants de proxy, et la valeur de322    chaque secret connu de l'environnement. À appeler partout où une323    exception de `requests` (qui cite l'URL complète) peut être consignée."""324    global _REDACT_RE325    import re as _re326    s = "" if text is None else str(text)327    if _REDACT_RE is None:328        _REDACT_RE = _re.compile(329            r"(?i)((?:api[_-]?key|key|token|password|pass)=)[^&\s\"'<>]+"330            r"|(Bearer\s+)[A-Za-z0-9._\-]{12,}"331            r"|\b(fc-)[0-9a-f]{16,}|\b(scp-(?:live|test)-)[0-9a-f]{16,}"332            r"|(://[^/\s:@]+:)[^@\s/]+(@)")333334    def _sub(m):335        if m.group(1):336            return m.group(1) + "<masqué>"337        if m.group(2):338            return m.group(2) + "<masqué>"339        if m.group(3) or m.group(4):340            return (m.group(3) or m.group(4)) + "<masqué>"341        return m.group(5) + "<masqué>" + m.group(6)342    s = _REDACT_RE.sub(_sub, s)343    for name in ("FIRECRAWL_API_KEY", "SCRAPFLY_KEY", "SCRAPFLY_API_KEY",344                 "BRIGHTDATA_API_KEY", "OXYLABS_PROXY_PASS", "OXYLABS_PASS",345                 "ANTHROPIC_API_KEY", "APIFY_TOKEN", "SERPER_API_KEY",346                 "TAVILY_API_KEY", "FABRIKA_ADMIN_TOKEN"):347        v = os.environ.get(name) or _load_env_files().get(name)348        if v and len(v) >= 8 and v in s:349            s = s.replace(v, "<masqué>")350    return s351352353def _resolves(host: str) -> bool:354    """False si le nom de domaine n'existe plus (NXDOMAIN) : aucun relais355    payant ne peut rien pour un domaine disparu."""356    import socket357    try:358        socket.getaddrinfo(host.split(":")[0], 443)359        return True360    except socket.gaierror:361        return False362    except Exception:  # noqa: BLE001363        return True364365366def _unwrap_pre(text: str) -> str:367    """Une réponse JSON/texte chargée dans un navigateur revient enrobée dans368    `<html>…<pre>…</pre></html>` : on restitue le corps d'origine."""369    import html as _html370    import re as _re371    m = _re.match(r"\s*<html[^>]*>\s*<head>.*?</head>\s*<body[^>]*>\s*<pre[^>]*>(.*)</pre>"372                  r"\s*(?:<div[^>]*>\s*</div>\s*)*</body>\s*</html>\s*$",373                  text, _re.S | _re.I)374    return _html.unescape(m.group(1)) if m else text375376377# =============================================================================378# Firecrawl — premier recours quand un site bloque (2026-11-26)379# =============================================================================380FIRECRAWL_SCRAPE = "https://api.firecrawl.dev/v2/scrape"381382# Dernière erreur Firecrawl par hôte (diagnostic : jamais de zéro silencieux)383# et coupe-circuit par hôte propre à Firecrawl : après plusieurs échecs384# consécutifs, l'hôte est sauté pendant un temps de repos et l'ancien moyen385# (Scrapfly…) reprend sans délai ni crédit gaspillé.386LAST_FIRECRAWL_ERROR: dict[str, str] = {}387_FC_COOLDOWN: dict[str, tuple[float, int]] = {}388_FC_COOLDOWN_HITS = 3389_FC_COOLDOWN_SECONDS = 1800.0390391# -- budget de crédits ---------------------------------------------------------392# Le quota Firecrawl (100 000 crédits / mois) est PARTAGÉ entre six sites.393# Fabri-Ka suit ~1 700 boutiques, quatre passes par jour : sans plafond, une394# seule boutique « generic » de 800 fiches qui se mettrait à bloquer brûlerait395# 96 000 crédits par mois. Quatre plafonds, tous réglables par l'environnement :396#   FABRIKA_FIRECRAWL_PAR_HOTE   crédits par hôte et par passe      (défaut 15)397#   FABRIKA_FIRECRAWL_PAR_CYCLE  crédits par passe de collecte      (défaut 80)398#   FABRIKA_FIRECRAWL_PAR_JOUR   crédits par jour                   (défaut 300)399#   FABRIKA_FIRECRAWL_PAR_MOIS   crédits par mois civil             (défaut 8000)400# Mesure du 2026-11-26 (essai sans écriture, 112 boutiques dont 12 « generic ») :401# les boutiques qui bloquent le direct sont presque toutes des « generic »402# (fiches lues page par page) ; sans plafond elles auraient demandé ~620403# crédits pour cet échantillon seul. Au plafond : 80 par passe, 300 par jour,404# soit au plus 8 000 par mois (8 % du quota partagé).405# Les compteurs jour / mois survivent aux redémarrages (data/firecrawl_usage.json).406# Plafond atteint = Firecrawl sauté, l'ancien relais reprend comme avant.407import threading as _threading408409_FC_LOCK = _threading.Lock()410_FC_CYCLE = {"credits": 0, "calls": 0, "ok": 0, "skipped": 0, "hosts": {}}411_FC_USAGE_PATH = Path(__file__).resolve().parents[2] / "data" / "firecrawl_usage.json"412RELAY_STATS = {"scrapfly": 0, "oxylabs": 0, "brightdata": 0}413414415def _fc_cap(name: str, default: int) -> int:416    try:417        return int(os.environ.get(name) or (_load_env_files().get(name)) or default)418    except (TypeError, ValueError):419        return default420421422def _fc_usage_load() -> dict:423    try:424        d = _json.loads(_FC_USAGE_PATH.read_text())425        return d if isinstance(d, dict) else {}426    except Exception:  # noqa: BLE001427        return {}428429430def firecrawl_usage() -> dict:431    """Consommation Firecrawl : passe en cours, jour, mois et plafonds."""432    d = _fc_usage_load()433    day, month = time.strftime("%Y-%m-%d"), time.strftime("%Y-%m")434    with _FC_LOCK:435        cyc = {k: (dict(v) if isinstance(v, dict) else v)436               for k, v in _FC_CYCLE.items()}437    return {"cycle": cyc,438            "jour": d.get("days", {}).get(day, 0),439            "mois": d.get("months", {}).get(month, 0),440            "plafonds": {"hote": _fc_cap("FABRIKA_FIRECRAWL_PAR_HOTE", 15),441                         "cycle": _fc_cap("FABRIKA_FIRECRAWL_PAR_CYCLE", 80),442                         "jour": _fc_cap("FABRIKA_FIRECRAWL_PAR_JOUR", 300),443                         "mois": _fc_cap("FABRIKA_FIRECRAWL_PAR_MOIS", 8000)},444            "relais": dict(RELAY_STATS)}445446447def new_cycle() -> None:448    """Début d'une passe de collecte : remet les compteurs de passe à zéro."""449    with _FC_LOCK:450        _FC_CYCLE.update(credits=0, calls=0, ok=0, skipped=0, hosts={})451        for k in RELAY_STATS:452            RELAY_STATS[k] = 0453454455def _fc_budget_ok(host: str) -> bool:456    """True s'il reste du budget pour un appel sur cet hôte (1 crédit prévu)."""457    d = _fc_usage_load()458    day, month = time.strftime("%Y-%m-%d"), time.strftime("%Y-%m")459    with _FC_LOCK:460        if _FC_CYCLE["hosts"].get(host, 0) >= _fc_cap("FABRIKA_FIRECRAWL_PAR_HOTE", 15):461            why = "plafond par hôte atteint"462        elif _FC_CYCLE["credits"] >= _fc_cap("FABRIKA_FIRECRAWL_PAR_CYCLE", 80):463            why = "plafond par passe atteint"464        elif d.get("days", {}).get(day, 0) >= _fc_cap("FABRIKA_FIRECRAWL_PAR_JOUR", 300):465            why = "plafond quotidien atteint"466        elif d.get("months", {}).get(month, 0) >= _fc_cap("FABRIKA_FIRECRAWL_PAR_MOIS", 8000):467            why = "plafond mensuel atteint"468        else:469            return True470        _FC_CYCLE["skipped"] += 1471    LAST_FIRECRAWL_ERROR[host] = f"Firecrawl sauté : {why}"472    return False473474475def _fc_spend(host: str, credits: int) -> None:476    day, month = time.strftime("%Y-%m-%d"), time.strftime("%Y-%m")477    with _FC_LOCK:478        _FC_CYCLE["credits"] += credits479        _FC_CYCLE["calls"] += 1480        _FC_CYCLE["hosts"][host] = _FC_CYCLE["hosts"].get(host, 0) + credits481        d = _fc_usage_load()482        days, months = d.setdefault("days", {}), d.setdefault("months", {})483        days[day] = days.get(day, 0) + credits484        months[month] = months.get(month, 0) + credits485        for k in sorted(days)[:-40]:          # on garde 40 jours486            days.pop(k, None)487        try:488            tmp = _FC_USAGE_PATH.with_suffix(".json.tmp")489            tmp.write_text(_json.dumps(d, ensure_ascii=False))490            os.replace(tmp, _FC_USAGE_PATH)491        except Exception:  # noqa: BLE001 — le compteur ne casse jamais la collecte492            pass493494495def _try_firecrawl(url: str, timeout: int, country: str, render_js: bool,496                   headers: dict | None, wait_ms: int = 0,497                   proxy: str | None = "basic",498                   fmt: str = "rawHtml") -> _ResilientResponse | None:499    """Firecrawl /v2/scrape : octets servis après chargement navigateur.500501    `proxy` = "basic" (1 crédit, défaut : coût borné) | "stealth" | "auto"502    (jusqu'à 5 crédits) ; `fmt` = "rawHtml" (défaut) ou "html". Brique sautée503    si FIRECRAWL_API_KEY est absente ou si le budget est épuisé. Renvoie None504    si l'API refuse (clé, quota, erreur) : la raison est gardée dans505    LAST_FIRECRAWL_ERROR, jamais avalée en silence.506    """507    key = _secret("FIRECRAWL_API_KEY")508    host = _host(url)509    if not key:510        LAST_FIRECRAWL_ERROR[host] = "FIRECRAWL_API_KEY manquant"511        return None512    if not _fc_budget_ok(host):513        return None514    payload: dict = {"url": url, "formats": [fmt],515                     "onlyMainContent": False,516                     "location": {"country": (country or "ca").upper()},517                     "timeout": int(max(timeout, 60) * 1000)}518    wait = wait_ms or (2500 if render_js else 0)519    if wait:520        payload["waitFor"] = int(wait)521    if proxy:522        payload["proxy"] = proxy523    if headers:524        payload["headers"] = {str(k): str(v) for k, v in headers.items()}525    try:526        r = requests.post(527            FIRECRAWL_SCRAPE,528            headers={"Authorization": f"Bearer {key}",529                     "Content-Type": "application/json"},530            json=payload, timeout=max(timeout, 60) + 30)531        body = r.json() or {}532        if not body.get("success"):533            # 402 / 429 : quota ou débit — aucun crédit débité534            LAST_FIRECRAWL_ERROR[host] = redact(535                f"HTTP {r.status_code} : {str(body.get('error') or body)[:200]}")536            if r.status_code not in (401, 402, 429):537                _fc_spend(host, 1)538            return None539        data = body.get("data") or {}540        meta = data.get("metadata") or {}541        try:542            credits = max(1, int(meta.get("creditsUsed") or 1))543        except (TypeError, ValueError):544            credits = 1545        _fc_spend(host, credits)546        LAST_FIRECRAWL_ERROR.pop(host, None)547        return _ResilientResponse(548            meta.get("sourceURL") or url, meta.get("statusCode") or 0,549            _unwrap_pre(data.get(fmt) or ""), {}, via="firecrawl")550    except Exception as exc:  # noqa: BLE001551        LAST_FIRECRAWL_ERROR[host] = redact(f"{type(exc).__name__} : {exc}")[:200]552        return None553554555def firecrawl_first(url: str, *, timeout: int = 30, country: str = "ca",556                    render_js: bool = False, headers: dict | None = None,557                    wait_ms: int = 0, proxy: str | None = "basic",558                    fmt: str = "rawHtml", must_contain: str | None = None,559                    accept=None) -> _ResilientResponse | None:560    """Firecrawl AVANT l'ancien relais (Scrapfly, Bright Data).561562    Renvoie la réponse seulement si elle est exploitable : HTTP 200, corps non563    vide, pas une page-challenge, et — contrôles contre les pages vides —564    `must_contain` présent dans le corps et `accept(texte)` vrai quand ils565    sont fournis (ex. « le corps est du JSON valide »). Sinon None : l'appelant566    se replie sur son ancien moyen. Coupe-circuit par hôte : un site que567    Firecrawl ne franchit pas n'est plus tenté pendant 30 min.568    """569    host = _host(url)570    until, hits = _FC_COOLDOWN.get(host, (0.0, 0))571    if time.time() < until:572        return None573    resp = _try_firecrawl(url, timeout, country, render_js, headers,574                          wait_ms=wait_ms, proxy=proxy, fmt=fmt)575    if resp is not None and resp.status_code == 200 and resp.text \576            and not is_blocked(resp):577        good = True578        if must_contain and must_contain not in resp.text:579            good = False580            LAST_FIRECRAWL_ERROR[host] = (581                f"page sans le marqueur attendu « {must_contain[:40]} »")582        if good and accept is not None:583            try:584                good = bool(accept(resp.text))585            except Exception:  # noqa: BLE001586                good = False587            if not good:588                LAST_FIRECRAWL_ERROR[host] = "contenu refusé par le contrôle du connecteur"589        if good:590            _FC_COOLDOWN.pop(host, None)591            with _FC_LOCK:592                _FC_CYCLE["ok"] += 1593            return resp594    elif resp is not None:595        LAST_FIRECRAWL_ERROR.setdefault(596            host, f"réponse inexploitable (HTTP {resp.status_code}, "597                  f"{len(resp.text)} octets)")598    if LAST_FIRECRAWL_ERROR.get(host, "").startswith("Firecrawl sauté"):599        return None                   # budget : ce n'est pas un échec de l'hôte600    hits += 1601    _FC_COOLDOWN[host] = ((time.time() + _FC_COOLDOWN_SECONDS, 0)602                          if hits >= _FC_COOLDOWN_HITS else (0.0, hits))603    return None604605606# -- le site bloque-t-il VRAIMENT ? --------------------------------------------607# Les connecteurs appellent le relais après n'importe quel échec du direct,608# y compris une erreur « métier » (404 d'une API désinstallée, 500 d'un609# WordPress cassé) pour laquelle un navigateur géré ne changera rien. Avant de610# dépenser un crédit, on sonde l'URL en direct, une fois par hôte et par passe.611_BLOCK_VERDICT: dict[str, tuple[float, bool]] = {}612_BLOCK_TTL = 3 * 3600.0613614615def host_blocks(url: str, timeout: int = 20) -> bool:616    """True si l'hôte refuse la requête directe par un anti-bot (403, 429,617    503, 52x, page-challenge) ; False s'il répond (même par une erreur618    métier 400/404/500) ou si son domaine n'existe plus."""619    host = _host(url)620    hit = _BLOCK_VERDICT.get(host)621    if hit and time.time() - hit[0] < _BLOCK_TTL:622        return hit[1]623    verdict = False624    if _resolves(host):625        try:626            r = requests.get(url, timeout=timeout, allow_redirects=True,627                             headers={"User-Agent": _UA,628                                      "Accept-Language": "fr-CA,fr;q=0.9,en;q=0.8"})629            verdict = is_blocked(r)630        except (requests.ConnectionError, requests.Timeout):631            verdict = False      # réseau / TLS : pas un anti-bot632        except Exception:  # noqa: BLE001633            verdict = False634    _BLOCK_VERDICT[host] = (time.time(), verdict)635    return verdict636637# -- backends d'escalade ------------------------------------------------------638def _try_oxylabs(url: str, timeout: int, country: str,639                 headers: dict | None) -> _ResilientResponse | None:640    endpoint = _secret("OXYLABS_PROXY")            # pr.oxylabs.io:7777641    user = _secret("OXYLABS_PROXY_USER")           # customer-...  (sans -cc-XX)642    pwd = _secret("OXYLABS_PROXY_PASS")643    if not (endpoint and user and pwd):644        return None645    cc = (country or "ca").upper()646    puser = f"{user}-cc-{cc}"647    proxy = f"http://{quote(puser, safe='')}:{quote(pwd, safe='')}@{endpoint}"648    proxies = {"http": proxy, "https": proxy}649    hdrs = {"User-Agent": _UA}650    if headers:651        hdrs.update(headers)652    try:653        RELAY_STATS["oxylabs"] += 1654        r = requests.get(url, proxies=proxies, headers=hdrs, timeout=timeout,655                         verify=False)  # noqa: S501 (proxy MITM du CA Oxylabs)656        return _ResilientResponse(url, r.status_code, r.text,657                                  dict(r.headers), via="oxylabs")658    except Exception:  # noqa: BLE001659        return None660661662def _try_scrapfly(url: str, timeout: int, country: str, render_js: bool,663                  headers: dict | None) -> _ResilientResponse | None:664    key = _secret("SCRAPFLY_KEY", "SCRAPFLY_API_KEY")665    if not key:666        return None667    params = {"key": key, "url": url, "country": country or "ca",668              "asp": "true", "proxy_pool": "public_residential_pool"}669    if render_js:670        params["render_js"] = "true"671    if headers:672        for k, v in headers.items():673            params[f"headers[{k}]"] = v674    try:675        RELAY_STATS["scrapfly"] += 1676        r = requests.get("https://api.scrapfly.io/scrape", params=params,677                         timeout=max(timeout, 180))678        result = (r.json() or {}).get("result") or {}679        return _ResilientResponse(680            url, result.get("status_code") or 0, result.get("content") or "",681            (result.get("response_headers") or {}), via="scrapfly")682    except Exception:  # noqa: BLE001683        return None684685686def _try_brightdata(url: str, timeout: int,687                    headers: dict | None) -> _ResilientResponse | None:688    key = _secret("BRIGHTDATA_API_KEY")689    zone = _secret("BRIGHTDATA_ZONE") or "web_unlocker1"690    if not key:691        return None692    try:693        RELAY_STATS["brightdata"] += 1694        r = requests.post(695            "https://api.brightdata.com/request",696            headers={"Authorization": f"Bearer {key}",697                     "Content-Type": "application/json"},698            json={"zone": zone, "url": url, "format": "raw"},699            timeout=max(timeout, 120))700        return _ResilientResponse(url, r.status_code, r.text,701                                  dict(r.headers), via="brightdata")702    except Exception:  # noqa: BLE001703        return None704705706# -- API publique -------------------------------------------------------------707def escalate(url: str, *, timeout: int = 30, country: str = "ca",708             render_js: bool = False, headers: dict | None = None,709             original=None):710    """Tente la chaîne de secours et renvoie la meilleure réponse.711712    Renvoie un `_ResilientResponse` 200 dès qu'un backend réussit ; sinon la713    dernière réponse tentée (ou `original`) pour préserver le comportement714    d'échec du connecteur. Respecte le coupe-circuit par hôte.715    """716    host = _host(url)717    if _cooling(host):718        return original  # source au repos : on ne brûle pas de quota payant719    if not _resolves(host):720        return original  # domaine disparu : aucun relais n'y peut rien721722    def _fc():723        # Firecrawl d'abord, avec son coupe-circuit et son budget propres724        until, _ = _FC_COOLDOWN.get(host, (0.0, 0))725        if time.time() < until:726            return None727        return _try_firecrawl(url, timeout, country, render_js, headers)728729    last = original730    for backend in (731        _fc,732        lambda: _try_oxylabs(url, timeout, country, headers),733        lambda: _try_scrapfly(url, timeout, country, render_js, headers),734        lambda: _try_brightdata(url, timeout, headers),735    ):736        resp = backend()737        if resp is None:738            continue739        last = resp740        if resp.status_code == 200 and resp.text and not is_blocked(resp):741            _note_success(host)742            return resp743        time.sleep(0.4)744745    _note_failure(host)746    return last if last is not None else original747748749def escalate_if_blocked(resp, url: str, *, timeout: int = 30,750                        country: str = "ca", render_js: bool = False,751                        headers: dict | None = None):752    """Renvoie `resp` s'il est bon ; sinon lance l'escalade anti-bot."""753    if not is_blocked(resp):754        return resp755    better = escalate(url, timeout=timeout, country=country,756                      render_js=render_js, headers=headers, original=resp)757    return better if better is not None else resp758
Files main
Menu

Theme