SPB Git

Repository Public

net.py 7.6 KB 184 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : actors/ka-fb-marketplace/src/net.py10# Module           : actors11# Repository       : https://git.spboucher.ai/lou-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# Author: Simon-Pierre Boucher <contact@spboucher.ai>89# File:   src/net.py (ka-fb-marketplace)90# Desc:   Fetch commun des acteurs KA — curl_cffi (empreinte TLS Chrome) +91#         proxy Apify (résidentiel par défaut) OU gabarit de proxy externe92#         ({session} → id de session, nouvelle IP par tentative), throttling93#         poli, retries à backoff exponentiel + jitter sur 403/407/408/425/94#         429/500/502/503/504.95# ==============================================================================96from __future__ import annotations9798import asyncio99import random100import re101102from apify import Actor103from curl_cffi import requests as cffi104105UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "106      "(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36")107108# statuts transitoires : mur anti-bot, proxy, rate-limit, erreurs serveur109RETRY_STATUSES = frozenset({403, 407, 408, 425, 429, 500, 502, 503, 504})110111112def _backoff(attempt: int) -> float:113    """Backoff exponentiel plafonné + jitter (anti-troupeau)."""114    return min(1.2 * (2 ** attempt), 12.0) + random.uniform(0.0, 0.8)115116117class Fetcher:118    """HTTP poli : proxy Apify ou externe + impersonation Chrome + retries."""119120    def __init__(self, proxy_configuration, delay: float = 1.0,121                 proxy_template: str | None = None) -> None:122        self.proxy_configuration = proxy_configuration123        self.proxy_template = proxy_template or None124        self.delay = delay125        self._lock = asyncio.Lock()126        self._last = 0.0127128    async def _throttle(self) -> None:129        async with self._lock:130            now = asyncio.get_event_loop().time()131            wait = self.delay - (now - self._last)132            if wait > 0:133                await asyncio.sleep(wait)134            self._last = asyncio.get_event_loop().time()135136    async def _proxy_url(self, session_id: str | None, attempt: int) -> str | None:137        sid = session_id or f"s{random.randint(1, 999_999)}"138        sid = re.sub(r"[^\w._~]", "", sid)[:40] or "s"139        # nouvelle session proxy (nouvelle IP) à chaque tentative140        sid = f"{sid}r{attempt}"141        if self.proxy_template:142            return self.proxy_template.replace("{session}", sid)143        if self.proxy_configuration:144            return await self.proxy_configuration.new_url(session_id=sid)145        return None146147    async def request(self, method: str, url: str,148                      headers: dict | None = None, data=None,149                      retries: int = 4, session_id: str | None = None,150                      impersonate: str | None = "chrome"):151        hdrs = {"User-Agent": UA,152                "Accept-Language": "fr-CA,fr;q=0.9,en;q=0.8"}153        if headers:154            hdrs.update(headers)155        last_exc: Exception | None = None156        for attempt in range(retries):157            await self._throttle()158            proxy = await self._proxy_url(session_id, attempt)159            try:160                resp = await asyncio.to_thread(161                    cffi.request, method, url, headers=hdrs, data=data,162                    impersonate=impersonate, timeout=60, allow_redirects=True,163                    proxies={"http": proxy, "https": proxy} if proxy else None)164                if resp.status_code in RETRY_STATUSES \165                        and attempt < retries - 1:166                    Actor.log.warning(167                        f"HTTP {resp.status_code} {url} — retry {attempt + 1}")168                    await asyncio.sleep(_backoff(attempt))169                    continue170                return resp171            except Exception as exc:  # réseau/proxy : on retente172                last_exc = exc173                await asyncio.sleep(_backoff(attempt))174        if last_exc:175            raise last_exc176        raise RuntimeError(f"échec après {retries} tentatives : {url}")177178    async def get(self, url: str, headers: dict | None = None,179                  retries: int = 4, session_id: str | None = None,180                  impersonate: str | None = "chrome"):181        return await self.request("GET", url, headers=headers,182                                  retries=retries, session_id=session_id,183                                  impersonate=impersonate)184
Files main
Menu

Theme