Download main.py from andervier/Tazas_API: direct link, hf CLI and curl.
- Browser
- Download file 36 kB
-
https://huggingface.co/spaces/andervier/Tazas_API/resolve/main/main.py
- Command line
-
hf download hf://spaces/andervier/Tazas_API/main.py
-
curl -L -o main.py https://huggingface.co/spaces/andervier/Tazas_API/resolve/main/main.py
36 kB
| from contextlib import asynccontextmanager | |
| from fastapi import FastAPI, Depends, HTTPException, Header, Query | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import ORJSONResponse | |
| from bs4 import BeautifulSoup | |
| import httpx | |
| import asyncio | |
| import time | |
| import re | |
| import hashlib | |
| import hmac | |
| import jwt | |
| import logging | |
| import os | |
| from jwt import PyJWKClient | |
| from starlette.concurrency import run_in_threadpool | |
| import history | |
| import stats | |
| logging.basicConfig(level=logging.WARNING) | |
| logger = logging.getLogger(__name__) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Cache + locks anti-thundering-herd | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| _cache: dict = {} | |
| BCV_TTL = 60 * 60 * 4 # 4 horas (BCV actualiza una vez al dΓa) | |
| P2P_TTL = 60 * 2 # 2 minutos | |
| # Throttle del webhook: aunque llegue con token vΓ‘lido, no se re-scrapea el BCV | |
| # mΓ‘s de una vez cada N segundos. Neutraliza un flood con token vΓ‘lido (evita | |
| # martillar a bcv.org.ve y quemar CPU). El cron legΓtimo (cada 2 min) nunca lo toca. | |
| _last_forced_refresh = 0.0 | |
| FORCED_REFRESH_MIN_INTERVAL = 30 # segundos | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # v2 β Constantes (aislamiento total respecto a v1) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| P2P_V2_TTL = 60 * 10 | |
| BINANCE_P2P_URL = "https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search" | |
| COUNTRY_CODE_PATTERN = re.compile(r"^[A-Z]{2}$") | |
| # ISO 3166-1 alpha-2 β ISO 4217 (fiat para Binance P2P) | |
| SUPPORTED_COUNTRIES: dict[str, str] = { | |
| "AR": "ARS", # Argentina | |
| "BO": "BOB", # Bolivia | |
| "BR": "BRL", # Brasil | |
| "CL": "CLP", # Chile | |
| "CO": "COP", # Colombia | |
| "CR": "CRC", # Costa Rica | |
| "DO": "DOP", # RepΓΊblica Dominicana | |
| "GT": "GTQ", # Guatemala | |
| "HN": "HNL", # Honduras | |
| "MX": "MXN", # MΓ©xico | |
| "NI": "NIO", # Nicaragua | |
| "PY": "PYG", # Paraguay | |
| "PE": "PEN", # PerΓΊ | |
| "UY": "UYU", # Uruguay | |
| "VE": "VES", # Venezuela (caso especial: local = null) | |
| "ES": "EUR", # EspaΓ±a | |
| } | |
| # Un Lock por clave: si el cachΓ© vence y llegan 1000 requests simultΓ‘neas, | |
| # solo la primera hace el fetch β las demΓ‘s esperan y consumen el cachΓ©. | |
| _locks: dict[str, asyncio.Lock] = {} | |
| def _lock(key: str) -> asyncio.Lock: | |
| if key not in _locks: | |
| _locks[key] = asyncio.Lock() | |
| return _locks[key] | |
| def _cached(key: str, ttl: int): | |
| entry = _cache.get(key) | |
| if entry and (time.time() - entry["ts"]) < ttl: | |
| return entry["data"] | |
| return None | |
| def _store(key: str, data: dict): | |
| _cache[key] = {"ts": time.time(), "data": data} | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Clientes HTTP persistentes (reutilizan conexiones TCP/TLS) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| _http: httpx.AsyncClient | None = None # Binance / general | |
| _http_nv: httpx.AsyncClient | None = None # BCV (verify=False β cert roto del BCV) | |
| async def lifespan(app: FastAPI): | |
| global _http, _http_nv | |
| limits = httpx.Limits(max_connections=10, max_keepalive_connections=5) | |
| _http = httpx.AsyncClient(timeout=10, limits=limits) | |
| _http_nv = httpx.AsyncClient(timeout=15, follow_redirects=True, verify=False, limits=limits) | |
| history.init() | |
| sampler = asyncio.create_task(_history_sampler()) if history.is_enabled() else None | |
| stats_task = stats.start(history.get_db) | |
| appcheck_cleanup_task = asyncio.create_task(_appcheck_cache_cleanup()) | |
| yield | |
| if sampler: | |
| sampler.cancel() | |
| if stats_task: | |
| stats_task.cancel() | |
| appcheck_cleanup_task.cancel() | |
| await _http.aclose() | |
| await _http_nv.aclose() | |
| app = FastAPI( | |
| title="Tazas API", | |
| version="1.0.0", | |
| lifespan=lifespan, | |
| default_response_class=ORJSONResponse, # orjson: serializaciΓ³n JSON en C (5-10x mΓ‘s rΓ‘pido) | |
| ) | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_methods=["GET"], | |
| allow_headers=["*"], | |
| ) | |
| _known_paths: set[str] | None = None | |
| def _tracked_path(path: str) -> str: | |
| """Colapsa cualquier path que no sea una ruta real de la app a 'other'. Sin | |
| esto, byPath/latencyByPath en stats crecen sin lΓmite: un escΓ‘ner probando | |
| /wp-admin, /.env, etc. crea una entrada nueva en el dict por cada intento, | |
| hasta reventar el lΓmite de 1 MiB por documento de Firestore.""" | |
| global _known_paths | |
| if _known_paths is None: | |
| _known_paths = {route.path for route in app.routes if hasattr(route, "path")} | |
| return path if path in _known_paths else "other" | |
| async def _stats_middleware(request, call_next): | |
| # Mide throughput/latencia/errores por endpoint. Si call_next lanza, cuenta 500. | |
| started = time.perf_counter() | |
| status = 500 | |
| try: | |
| response = await call_next(request) | |
| status = response.status_code | |
| return response | |
| finally: | |
| stats.record(_tracked_path(request.url.path), status, time.perf_counter() - started) | |
| # DEBUG TEMPORAL: guarda el detalle de los fallos de App Check para diagnosticarlos. | |
| # verify_app_check ahora devuelve 404 (no 401) en cualquier fallo, asΓ que | |
| # el disparador de esta captura tiene que ser 404, no 401. | |
| p = request.url.path | |
| if status == 404 and (p.startswith("/v1") or p.startswith("/v2")): | |
| await _capture_401(request) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Firebase App Check | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| PROJECT_NUMBER = "748155614527" | |
| APP_ID = "1:748155614527:android:c29d203cf594986dda8f8a" | |
| JWKS_URL = "https://firebaseappcheck.googleapis.com/v1/jwks" | |
| _jwks_client = PyJWKClient(JWKS_URL, cache_jwk_set=True, lifespan=3600) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Cache de validez de App Check | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # El token de App Check dura 7 dΓas (config del cliente, fuera de este repo). | |
| # Verificar la firma RSA (CPU-bound) en cada request de esos 7 dΓas es | |
| # desperdicio: el mismo patrΓ³n _cached/_lock/_store que usa el resto del | |
| # archivo no aplica igual acΓ‘ porque no queremos guardar el token crudo como | |
| # clave, asΓ que este cache vive aparte con la clave hasheada. | |
| # Clave: sha256(token) β nunca el token crudo. Valor: timestamp valido_hasta. | |
| _appcheck_cache: dict[str, float] = {} | |
| APPCHECK_CACHE_MAX_TTL = 3 * 24 * 3600 # techo: nunca cachear mΓ‘s de 3 dΓas | |
| APPCHECK_CACHE_CLEANUP_INTERVAL = 60 * 60 # limpieza cada 1 hora | |
| def invalidate_appcheck_token(token: str) -> None: | |
| """Borra manualmente un token del cache de App Check (p.ej. si se detecta que | |
| fue comprometido y no se quiere esperar a que expire su entrada). No falla si | |
| el token no estaba cacheado.""" | |
| _appcheck_cache.pop(hashlib.sha256(token.encode()).hexdigest(), None) | |
| async def _appcheck_cache_cleanup(): | |
| """Tarea periΓ³dica (cada 1 hora, ciclo independiente del flush de 120s de | |
| stats.py) que purga del cache las entradas ya vencidas. Sin esto el dict | |
| crece indefinidamente con tokens que ya no van a volver a usarse.""" | |
| while True: | |
| await asyncio.sleep(APPCHECK_CACHE_CLEANUP_INTERVAL) | |
| ahora = time.time() | |
| vencidos = [k for k, valido_hasta in _appcheck_cache.items() if valido_hasta <= ahora] | |
| for k in vencidos: | |
| _appcheck_cache.pop(k, None) | |
| async def verify_app_check(x_firebase_appcheck: str = Header(None)): | |
| # DISABLE_APP_CHECK tiene tres estados: | |
| # "1" β desactivado del todo (parche histΓ³rico): no valida nada. | |
| # "shadow" β valida y clasifica el motivo igual que en modo estricto, pero | |
| # NUNCA bloquea. Sirve para medir cuΓ‘nta gente fallarΓa antes de | |
| # activar el bloqueo real, sin arriesgar usuarios reales (caso | |
| # conocido: redes WiFi que bloquean el alcance a Play Integrity). | |
| # (nada) β modo estricto: bloquea con 404. | |
| mode = os.getenv("DISABLE_APP_CHECK") | |
| if mode == "1": | |
| return | |
| shadow = mode == "shadow" | |
| # 404 en vez de 401 en modo estricto: a quien golpee sin token vΓ‘lido, el | |
| # endpoint le parece inexistente. Un 401 delata que hay algo ahΓ protegido y | |
| # digno de atacar; un 404 no invita a insistir. | |
| def _reject(reason: str): | |
| stats.record_auth_failure(reason) | |
| if shadow: | |
| return | |
| raise HTTPException(status_code=404, detail="Not Found") | |
| if not x_firebase_appcheck: | |
| return _reject("sin_token") | |
| token_hash = hashlib.sha256(x_firebase_appcheck.encode()).hexdigest() | |
| # Cache-hit: este token ya se verificΓ³ antes y sigue vigente. No hace falta | |
| # volver a validar la firma RSA (CPU-bound) ni pasar por el threadpool β se | |
| # resuelve directo en el event loop. Este es el camino que toma la mayorΓa | |
| # de los requests una vez que el cache se calienta. | |
| valido_hasta = _appcheck_cache.get(token_hash) | |
| if valido_hasta is not None and valido_hasta > time.time(): | |
| stats.record_accepted_request() | |
| stats.record_appcheck_hit() | |
| return | |
| # Cache-miss: token nuevo o vencido en el cache. La verificaciΓ³n de firma es | |
| # CPU-bound y cara, asΓ que se manda al threadpool para no bloquear el event | |
| # loop mientras se calcula. | |
| def _verificar_firma(): | |
| signing_key = _jwks_client.get_signing_key_from_jwt(x_firebase_appcheck) | |
| return jwt.decode( | |
| x_firebase_appcheck, | |
| signing_key.key, | |
| algorithms=["RS256"], | |
| audience=f"projects/{PROJECT_NUMBER}", | |
| issuer=f"https://firebaseappcheck.googleapis.com/{PROJECT_NUMBER}", | |
| ) | |
| try: | |
| claims = await run_in_threadpool(_verificar_firma) | |
| if claims.get("sub") != APP_ID: | |
| return _reject("sub_no_coincide") | |
| except jwt.exceptions.PyJWTError as e: | |
| # Nombre real de la excepciΓ³n de PyJWT (ExpiredSignatureError, DecodeError, | |
| # InvalidAudienceError, PyJWKClientError...) en vez de adivinar el motivo. | |
| return _reject(type(e).__name__) | |
| # Llegar hasta acΓ‘ significa que no pasΓ³ por ningΓΊn _reject(): token presente, | |
| # firma/audience/issuer vΓ‘lidos y sub coincide con la app. Request aceptada. | |
| # Se cachea el Γ©xito (nunca los fallos) hasta el mΓnimo entre el exp real del | |
| # token y el techo de 3 dΓas β nunca le damos al cache mΓ‘s vida que la que el | |
| # token realmente tiene segΓΊn su propio claim. | |
| _appcheck_cache[token_hash] = min(claims["exp"], time.time() + APPCHECK_CACHE_MAX_TTL) | |
| stats.record_accepted_request() | |
| stats.record_appcheck_miss() | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # DEBUG TEMPORAL β App Check: por quΓ© fallan los 401 | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Ante un 401 en /v1|/v2, guarda el detalle en la colecciΓ³n rodante `appcheck_401` | |
| # (30 slots que se reescriben), con el MOTIVO clasificado para ver el patrΓ³n: | |
| # sin_token β la app no consiguiΓ³ token (red bloquea Google / Play Integrity) | |
| # token_no_jwt β dummy/error de App Check (no obtuvo token real) | |
| # token_expirado β token vencido | |
| # sub_no_coincide β token de otra app | |
| # firma_o_aud_iss β JWT en forma OK pero rechazado (firma/audience/issuer) | |
| # Throttle 2s para no floodear Firestore. QUITAR cuando se resuelva. | |
| _last_401_capture = 0.0 | |
| async def _capture_401(request) -> None: | |
| global _last_401_capture | |
| db = history.get_db() | |
| if db is None: | |
| return | |
| now = time.time() | |
| if now - _last_401_capture < 2: | |
| return | |
| _last_401_capture = now | |
| token = request.headers.get("x-firebase-appcheck") | |
| info = { | |
| "ts": int(now), | |
| "path": request.url.path, | |
| "userAgent": request.headers.get("user-agent"), | |
| "hasToken": token is not None, | |
| "disableAppCheck": os.getenv("DISABLE_APP_CHECK"), | |
| } | |
| reason = "sin_token" | |
| if token: | |
| info["tokenLen"] = len(token) | |
| try: | |
| claims = jwt.decode(token, options={"verify_signature": False}) | |
| info["claims"] = {k: claims.get(k) for k in ("sub", "aud", "iss", "exp", "iat")} | |
| sub_ok = claims.get("sub") == APP_ID | |
| exp = claims.get("exp") | |
| expired = bool(exp and exp < int(now)) | |
| info["subMatches"] = sub_ok | |
| info["expired"] = expired | |
| reason = ( | |
| "token_expirado" if expired | |
| else "sub_no_coincide" if not sub_ok | |
| else "firma_o_aud_iss" | |
| ) | |
| except Exception as e: | |
| info["decodeError"] = f"{type(e).__name__}: {e}" | |
| info["tokenPreview"] = token[:48] | |
| reason = "token_no_jwt" | |
| info["reason"] = reason | |
| slot = int(now) % 30 | |
| try: | |
| await db.collection("appcheck_401").document(f"slot_{slot:02d}").set(info) | |
| except Exception as e: | |
| logger.error("captura 401 fallΓ³: %s", e) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Helpers | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _parse_bcv_rate(text: str) -> float | None: | |
| """Convierte '36,85' o '36.853,12' a float.""" | |
| cleaned = text.strip().replace("Bs.", "").replace("S", "").strip() | |
| # Formato venezolano: punto como separador de miles, coma como decimal | |
| cleaned = cleaned.replace(".", "").replace(",", ".") | |
| try: | |
| return float(cleaned) | |
| except ValueError: | |
| return None | |
| def _classify_fetch_error(e: Exception) -> str: | |
| """Clasifica el fallo de un fetcher externo (BCV, P2P) en un motivo legible | |
| para las stats β asΓ el dashboard distingue timeout de caΓda de conexiΓ³n de | |
| un cambio de formato en la respuesta.""" | |
| if isinstance(e, httpx.TimeoutException): | |
| return "timeout" | |
| if isinstance(e, httpx.HTTPStatusError): | |
| return f"http_error_{e.response.status_code}" | |
| if isinstance(e, httpx.RequestError): | |
| return "connection_error" | |
| return type(e).__name__ | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Fetchers | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def fetch_bcv(force: bool = False) -> dict: | |
| # force=True omite el cachΓ©: lo usa el webhook cuando changedetection.io | |
| # avisa que la pΓ‘gina del BCV cambiΓ³, para traer la tasa nueva de inmediato. | |
| if not force: | |
| cached = _cached("bcv", BCV_TTL) | |
| if cached: | |
| return cached | |
| async with _lock("bcv"): | |
| # Double-check: mientras esperΓ‘bamos el lock, otro ya pudo haber refrescado | |
| if not force: | |
| cached = _cached("bcv", BCV_TTL) | |
| if cached: | |
| return cached | |
| headers = { | |
| "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", | |
| "Accept-Language": "es-VE,es;q=0.9", | |
| } | |
| # verify=False porque bcv.org.ve tiene cadena de certificados incompleta (problema del BCV) | |
| try: | |
| response = await _http_nv.get("https://www.bcv.org.ve/", headers=headers) | |
| response.raise_for_status() | |
| except (httpx.TimeoutException, httpx.RequestError, httpx.HTTPStatusError) as e: | |
| reason = _classify_fetch_error(e) | |
| stats.record_fetch_error("bcv", reason, str(e)) | |
| logger.warning("BCV fetch fallΓ³ (%s): %s", reason, e) | |
| raise HTTPException(status_code=503, detail="No se pudo contactar al BCV") from e | |
| soup = BeautifulSoup(response.text, "lxml") | |
| currency_ids = { | |
| "Usd": "dolar", | |
| "Eur": "euro", | |
| "Cny": "yuan", | |
| "Try": "lira", | |
| "Rub": "rublo", | |
| } | |
| rates = {} | |
| for suffix, div_id in currency_ids.items(): | |
| div = soup.find(id=div_id) | |
| tag = div.find("strong") if div else None | |
| rates[f"bcv{suffix}"] = _parse_bcv_rate(tag.text) if tag else None | |
| if all(v is None for v in rates.values()): | |
| stats.record_fetch_error("bcv", "parse_error", "todas las tasas dieron None") | |
| logger.error("BCV: all rates are None β scraping failed") | |
| raise HTTPException(status_code=503, detail="No se pudo obtener las tasas BCV") | |
| stats.record_fetch_success("bcv") | |
| updated_tag = soup.find("span", {"class": re.compile(r"date-display")}) | |
| updated_at = updated_tag.text.strip() if updated_tag else None | |
| data = {**rates, "updatedAt": updated_at} | |
| _store("bcv", data) | |
| # Mantiene {current, previous} para la "tasa del viernes". Solo corre en un | |
| # scrape real (no en cache hits) y con fecha valor presente, asΓ que el costo | |
| # en Firestore es raro y no se corrompe el estado si falla leer la fecha. | |
| if history.is_enabled() and data.get("updatedAt"): | |
| try: | |
| previous = await history.update_bcv_state(data) | |
| _store("bcv_previous", previous or {}) | |
| except Exception as e: | |
| logger.warning("update_bcv_state fallΓ³: %s", e) | |
| return data | |
| async def _bcv_previous() -> dict | None: | |
| """Tasa BCV inmediatamente anterior (la 'del viernes' durante el fin de semana). | |
| Cacheada en memoria; se relee de Firestore al vencer el TTL del BCV. {} = sin dato.""" | |
| cached = _cached("bcv_previous", BCV_TTL) | |
| if cached is not None: | |
| return cached or None | |
| previous = await history.get_bcv_previous() | |
| _store("bcv_previous", previous or {}) | |
| return previous | |
| async def fetch_p2p() -> dict: | |
| cached = _cached("p2p", P2P_TTL) | |
| if cached: | |
| return cached | |
| async with _lock("p2p"): | |
| # Double-check: mientras esperΓ‘bamos el lock, otro ya pudo haber refrescado | |
| cached = _cached("p2p", P2P_TTL) | |
| if cached: | |
| return cached | |
| headers = { | |
| "User-Agent": "Mozilla/5.0", | |
| "Content-Type": "application/json", | |
| } | |
| body_base = { | |
| "fiat": "VES", | |
| "page": 1, | |
| "rows": 20, | |
| "asset": "USDT", | |
| "countries": [], | |
| "proMerchantAds": False, | |
| "shieldMerchantAds": False, | |
| "publisherType": None, | |
| "payTypes": [], | |
| "classifies": ["mass", "profession"], | |
| } | |
| # BUY = compradores de USDT (tab "Vender" en Binance, ordenado de mayor a menor) | |
| # SELL = vendedores de USDT (tab "Comprar" en Binance, ordenado de menor a mayor) | |
| buy_ads_res, sell_ads_res = await asyncio.gather( | |
| _http.post( | |
| "https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search", | |
| json={**body_base, "tradeType": "BUY"}, | |
| headers=headers, | |
| ), | |
| _http.post( | |
| "https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search", | |
| json={**body_base, "tradeType": "SELL"}, | |
| headers=headers, | |
| ), | |
| ) | |
| buy_ads_res.raise_for_status() | |
| sell_ads_res.raise_for_status() | |
| def first_eligible_price(ads: list) -> float | None: | |
| """ | |
| 1. Salta los primeros 3 anuncios y promedia precios de ads[3..5] como referencia. | |
| 2. fiat_ref = promedio * 20 (~20 USDT en VES). | |
| 3. Devuelve el primer anuncio donde minSingleTransAmount <= fiat_ref <= maxSingleTransAmount. | |
| Fallback: primer anuncio desde Γndice 3 con min <= fiat_ref (sin chequeo de max). | |
| """ | |
| if not ads: | |
| return None | |
| sample = [] | |
| for item in ads[3:6]: | |
| try: | |
| sample.append(float(item["adv"]["price"])) | |
| except (KeyError, ValueError, TypeError): | |
| pass | |
| if not sample: | |
| return None | |
| return round(sum(sample) / len(sample), 2) | |
| p2p_buy = first_eligible_price(sell_ads_res.json().get("data", [])) | |
| p2p_sell = first_eligible_price(buy_ads_res.json().get("data", [])) | |
| data = {"p2pBuyMax": p2p_buy, "p2pSellMax": p2p_sell} | |
| _store("p2p", data) | |
| return data | |
| async def fetch_p2p_safe() -> dict: | |
| try: | |
| data = await fetch_p2p() | |
| stats.record_fetch_success("p2p") | |
| return data | |
| except Exception as e: | |
| reason = _classify_fetch_error(e) | |
| stats.record_fetch_error("p2p", reason, str(e)) | |
| logger.error("fetch_p2p failed: %s", e, exc_info=True) | |
| return {"p2pBuyMax": None, "p2pSellMax": None} | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # v2 β Fetchers aislados (no afectan a /v1) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def fetch_p2p_v2(fiat: str) -> dict: | |
| cache_key = f"p2p_v2:{fiat}" | |
| cached = _cached(cache_key, P2P_V2_TTL) | |
| if cached: | |
| return cached | |
| async with _lock(cache_key): | |
| cached = _cached(cache_key, P2P_V2_TTL) | |
| if cached: | |
| return cached | |
| headers = { | |
| "User-Agent": "Mozilla/5.0", | |
| "Content-Type": "application/json", | |
| } | |
| body_base = { | |
| "fiat": fiat, | |
| "page": 1, | |
| "rows": 20, | |
| "asset": "USDT", | |
| "countries": [], | |
| "proMerchantAds": False, | |
| "shieldMerchantAds": False, | |
| "publisherType": None, | |
| "payTypes": [], | |
| "classifies": ["mass", "profession"], | |
| } | |
| logger.info("fetch_p2p_v2 fiat=%s", fiat) | |
| buy_ads_res, sell_ads_res = await asyncio.gather( | |
| _http.post(BINANCE_P2P_URL, json={**body_base, "tradeType": "BUY"}, headers=headers), | |
| _http.post(BINANCE_P2P_URL, json={**body_base, "tradeType": "SELL"}, headers=headers), | |
| ) | |
| buy_ads_res.raise_for_status() | |
| sell_ads_res.raise_for_status() | |
| def first_eligible_price(ads: list) -> float | None: | |
| if not ads: | |
| return None | |
| sample = [] | |
| for item in ads[3:6]: | |
| try: | |
| sample.append(float(item["adv"]["price"])) | |
| except (KeyError, ValueError, TypeError): | |
| pass | |
| if not sample: | |
| return None | |
| return round(sum(sample) / len(sample), 2) | |
| p2p_buy = first_eligible_price(sell_ads_res.json().get("data", [])) | |
| p2p_sell = first_eligible_price(buy_ads_res.json().get("data", [])) | |
| data = {"p2pBuyMax": p2p_buy, "p2pSellMax": p2p_sell} | |
| _store(cache_key, data) | |
| return data | |
| async def fetch_p2p_v2_safe(fiat: str) -> dict: | |
| try: | |
| data = await fetch_p2p_v2(fiat) | |
| stats.record_fetch_success("p2p_v2") | |
| return data | |
| except Exception as e: | |
| reason = _classify_fetch_error(e) | |
| stats.record_fetch_error("p2p_v2", reason, f"fiat={fiat}: {e}") | |
| logger.error("fetch_p2p_v2(%s) failed: %s", fiat, e, exc_info=True) | |
| return {"p2pBuyMax": None, "p2pSellMax": None} | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # v2 β Caso especial BR: Binance P2P no sirve anuncios pΓΊblicos para USDT/BRL | |
| # (confirmado en vivo: `data: []` de forma consistente). En vez de un fallback | |
| # genΓ©rico para todos los paΓses, se usa el ticker spot pΓΊblico de OKX | |
| # (sin autenticaciΓ³n) solo para este paΓs, igual que VE tiene su propia rama | |
| # especial mΓ‘s abajo en rates_v2. | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| OKX_TICKER_URL = "https://www.okx.com/api/v5/market/ticker" | |
| async def fetch_okx_brl() -> dict: | |
| cache_key = "okx_v2:BRL" | |
| cached = _cached(cache_key, P2P_V2_TTL) | |
| if cached: | |
| return cached | |
| async with _lock(cache_key): | |
| # Double-check: mientras esperΓ‘bamos el lock, otro ya pudo haber refrescado | |
| cached = _cached(cache_key, P2P_V2_TTL) | |
| if cached: | |
| return cached | |
| logger.info("fetch_okx_brl instId=USDT-BRL") | |
| response = await _http.get(OKX_TICKER_URL, params={"instId": "USDT-BRL"}) | |
| response.raise_for_status() | |
| payload = response.json() | |
| if payload.get("code") != "0": | |
| raise ValueError(f"OKX code={payload.get('code')!r} msg={payload.get('msg')!r}") | |
| rows = payload.get("data") or [] | |
| if not rows: | |
| raise ValueError("OKX devolviΓ³ data vacΓo para USDT-BRL") | |
| ticker = rows[0] | |
| try: | |
| ask = float(ticker["askPx"]) | |
| bid = float(ticker["bidPx"]) | |
| except (KeyError, ValueError, TypeError) as e: | |
| raise ValueError(f"OKX ticker con campos invΓ‘lidos: {ticker}") from e | |
| # askPx = precio al que alguien COMPRA USDT (anΓ‘logo a p2pBuyMax). | |
| # bidPx = precio al que alguien VENDE USDT (anΓ‘logo a p2pSellMax). | |
| # Mismo contrato de salida que fetch_p2p_v2 para que rates_v2 no tenga | |
| # que distinguir el origen del dato al armar la respuesta. | |
| data = {"p2pBuyMax": round(ask, 4), "p2pSellMax": round(bid, 4)} | |
| _store(cache_key, data) | |
| return data | |
| async def fetch_okx_brl_safe() -> dict: | |
| try: | |
| data = await fetch_okx_brl() | |
| stats.record_fetch_success("okx_brl") | |
| return data | |
| except Exception as e: | |
| reason = _classify_fetch_error(e) | |
| stats.record_fetch_error("okx_brl", reason, str(e)) | |
| logger.error("fetch_okx_brl failed: %s", e, exc_info=True) | |
| return {"p2pBuyMax": None, "p2pSellMax": None} | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Muestreador de histΓ³rico: cada 15 min registra BCV + USDT de TODAS las fiats, | |
| # sin depender de que un usuario de ese paΓs pida tasas. Los fetchers ya hacen | |
| # el registro (con dedupe por valor), asΓ que aquΓ solo se fuerza el fetch. | |
| # | |
| # Notas de operaciΓ³n: | |
| # - Con --workers 2 el bucle corre en ambos procesos: el jitter inicial los | |
| # desincroniza y la identidad por bucket de 5 min evita duplicados en la DB. | |
| # El costo extra son ~4 llamadas/min a Binance en el peor caso β irrelevante. | |
| # - Si el Space duerme (sin trΓ‘fico), el muestreo se pausa: quedan huecos en el | |
| # histΓ³rico, no errores. Con usuarios activos el Space casi nunca duerme. | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| HISTORY_SAMPLE_INTERVAL = 60 * 15 | |
| HISTORY_SAMPLE_SPACING = 2 # segundos entre fiats para no ametrallar a Binance | |
| async def _history_sampler(): | |
| import random | |
| await asyncio.sleep(random.uniform(5, 120)) # desincronizar los 2 workers | |
| fiats = sorted(set(SUPPORTED_COUNTRIES.values())) | |
| while True: | |
| try: | |
| bcv = await fetch_bcv() | |
| history.record_bcv(bcv) # dedupe por valor: solo graba si la tasa cambiΓ³ | |
| except Exception as e: | |
| logger.warning("sampler: fetch_bcv fallΓ³: %s", e) | |
| for fiat in fiats: | |
| # BR: mismo caso especial que en rates_v2 β Binance P2P no tiene | |
| # anuncios para USDT/BRL, se usa el ticker spot de OKX en su lugar. | |
| data = await fetch_okx_brl_safe() if fiat == "BRL" else await fetch_p2p_v2_safe(fiat) | |
| history.record_p2p(fiat, data.get("p2pBuyMax"), data.get("p2pSellMax")) | |
| await asyncio.sleep(HISTORY_SAMPLE_SPACING) | |
| await asyncio.sleep(HISTORY_SAMPLE_INTERVAL) | |
| def validate_country(country: str | None) -> str: | |
| if not country: | |
| raise HTTPException(status_code=400, detail="Query param 'country' es requerido") | |
| if not COUNTRY_CODE_PATTERN.match(country): | |
| raise HTTPException( | |
| status_code=400, | |
| detail="CΓ³digo de paΓs debe ser ISO 3166-1 alpha-2 (2 letras mayΓΊsculas)", | |
| ) | |
| if country not in SUPPORTED_COUNTRIES: | |
| raise HTTPException(status_code=400, detail=f"PaΓs '{country}' no estΓ‘ soportado en esta versiΓ³n") | |
| return country | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Endpoints | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def root(): | |
| return {"status": "ok", "service": "Tazas API"} | |
| async def rates(): | |
| bcv_data, p2p_data = await asyncio.gather( | |
| fetch_bcv(), | |
| fetch_p2p_safe(), | |
| ) | |
| return {**bcv_data, **p2p_data} | |
| async def bcv(): | |
| return await fetch_bcv() | |
| async def p2p(): | |
| return await fetch_p2p() | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # v2 β Endpoint multi-paΓs (aislado de /v1) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def rates_v2(country: str | None = None): | |
| cc = validate_country(country) | |
| fiat = SUPPORTED_COUNTRIES[cc] | |
| logger.info("/v2/rates country=%s fiat=%s", cc, fiat) | |
| if cc == "VE": | |
| bcv_data, ve_p2p, prev = await asyncio.gather( | |
| fetch_bcv(), | |
| fetch_p2p_v2_safe("VES"), | |
| _bcv_previous(), | |
| ) | |
| return { | |
| "venezuela": {**bcv_data, **ve_p2p, "previous": prev}, | |
| "local": None, | |
| } | |
| # BR: Binance P2P no sirve anuncios pΓΊblicos para USDT/BRL (data: [] confirmado | |
| # en vivo). Caso especial: se consulta el ticker spot de OKX en su lugar. | |
| local_fetch = fetch_okx_brl_safe() if cc == "BR" else fetch_p2p_v2_safe(fiat) | |
| bcv_data, ve_p2p, local_p2p, prev = await asyncio.gather( | |
| fetch_bcv(), | |
| fetch_p2p_v2_safe("VES"), | |
| local_fetch, | |
| _bcv_previous(), | |
| ) | |
| return { | |
| "venezuela": {**bcv_data, **ve_p2p, "previous": prev}, | |
| "local": { | |
| "countryCode": cc, | |
| "currency": fiat, | |
| "usdtBuy": local_p2p.get("p2pBuyMax"), | |
| "usdtSell": local_p2p.get("p2pSellMax"), | |
| "updatedAt": None, | |
| }, | |
| } | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # v2 β HistΓ³rico (persistido en Firestore) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def history_v2(country: str | None = None, days: int = 30): | |
| """ | |
| HistΓ³rico de tasas de los ΓΊltimos `days` dΓas (mΓ‘x 35). | |
| - bcv: puntos {t, usd, eur, cny, try, rub} β el BCV cambia ~1 vez/dΓa. | |
| - p2p: puntos {t, buy, sell} de USDT/VES β fluctΓΊa durante el dΓa. | |
| - local: puntos {t, buy, sell} de USDT/{fiat} β null para VE/dolarizados. | |
| `t` es epoch en segundos (UTC), redondeado a buckets de 5 minutos. | |
| """ | |
| cc = validate_country(country) | |
| if not history.is_enabled(): | |
| raise HTTPException(status_code=503, detail="HistΓ³rico no disponible") | |
| days = max(1, min(days, 35)) | |
| fiat = SUPPORTED_COUNTRIES[cc] | |
| include_local = cc != "VE" | |
| tasks = [history.get_history("BCV", days), history.get_history("VES", days)] | |
| if include_local: | |
| tasks.append(history.get_history(fiat, days)) | |
| results = await asyncio.gather(*tasks) | |
| return { | |
| "days": days, | |
| "bcv": results[0], | |
| "p2p": results[1], | |
| "local": { | |
| "countryCode": cc, | |
| "currency": fiat, | |
| "points": results[2], | |
| } if include_local else None, | |
| } | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Webhook β refresco inmediato del BCV (disparado por changedetection.io) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # GET + POST para que sirva cualquier pinger externo gratuito (cron-job.org, | |
| # UptimeRobot, GitHub Actions, etc.), incluidos los que solo hacen GET. | |
| async def bcv_refresh_webhook( | |
| token: str | None = Query(default=None), | |
| x_webhook_token: str | None = Header(default=None), | |
| ): | |
| """ | |
| Un servicio externo (cron gratuito) golpea este endpoint cada pocos minutos. | |
| Fuerza un scrape fresco del BCV (ignora el cachΓ© de 4h) y registra el valor | |
| nuevo en el histΓ³rico de inmediato. record_bcv deduplica por valor: si el | |
| BCV no cambiΓ³, no escribe nada. De paso, el ping mantiene despierto el Space | |
| (para que el muestreador interno de USDT tambiΓ©n corra). | |
| Protegido por secreto compartido (env WEBHOOK_SECRET), vΓa query `?token=` | |
| o header `X-Webhook-Token`. No usa App Check: el llamador es externo. | |
| """ | |
| secret = os.getenv("WEBHOOK_SECRET") | |
| if not secret: | |
| raise HTTPException(status_code=404, detail="Not Found") | |
| provided = x_webhook_token or token or "" | |
| # compare_digest: comparaciΓ³n de tiempo constante (no filtra el secreto por timing). | |
| # 404 en vez de 401: a un escΓ‘ner sin el token, el endpoint le parece inexistente. | |
| if not hmac.compare_digest(provided, secret): | |
| raise HTTPException(status_code=404, detail="Not Found") | |
| # Throttle: con token vΓ‘lido pero llamadas muy seguidas, servir el ΓΊltimo valor | |
| # sin re-scrapear. Acota el scrape a 1 cada FORCED_REFRESH_MIN_INTERVAL seg. | |
| global _last_forced_refresh | |
| now = time.time() | |
| if now - _last_forced_refresh < FORCED_REFRESH_MIN_INTERVAL: | |
| cached = _cached("bcv", BCV_TTL) or {} | |
| return {"status": "throttled", "bcvUsd": cached.get("bcvUsd")} | |
| _last_forced_refresh = now | |
| data = await fetch_bcv(force=True) | |
| history.record_bcv(data) | |
| return { | |
| "status": "refreshed", | |
| "bcvUsd": data.get("bcvUsd"), | |
| "updatedAt": data.get("updatedAt"), | |
| } | |