Spaces:
Running

andervier commited on
Commit
35bc8f7
Β·
1 Parent(s): 3b2a304

feat: webhook /webhook/bcv-refresh para refresco inmediato del BCV (secreto + throttle + 404)

Browse files
Files changed (2) hide show
  1. NOTAS_DEV.md +15 -0
  2. main.py +67 -8
NOTAS_DEV.md CHANGED
@@ -47,6 +47,21 @@ X-Firebase-AppCheck: {token JWT}
47
  | GET | `/v1/p2p` | Solo tasas Binance P2P |
48
  | GET | `/v2/rates` | Tasas multi-paΓ­s (`?country=CO`) |
49
  | GET | `/v2/history` | HistΓ³rico de tasas (`?country=CO&days=30`, mΓ‘x 35) |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
  ### HistΓ³rico (`/v2/history`) β€” Firestore
52
 
 
47
  | GET | `/v1/p2p` | Solo tasas Binance P2P |
48
  | GET | `/v2/rates` | Tasas multi-paΓ­s (`?country=CO`) |
49
  | GET | `/v2/history` | HistΓ³rico de tasas (`?country=CO&days=30`, mΓ‘x 35) |
50
+ | POST | `/webhook/bcv-refresh` | Refresco inmediato del BCV (changedetection.io) |
51
+
52
+ ### Webhook `/webhook/bcv-refresh` β€” changedetection.io
53
+
54
+ - changedetection.io vigila `https://www.bcv.org.ve/` y, al detectar un cambio,
55
+ llama a este endpoint. La API hace un scrape FRESCO del BCV (ignora el cachΓ©
56
+ de 4h) y registra el valor nuevo en el histΓ³rico de inmediato.
57
+ - Protegido con un secreto compartido: **env `WEBHOOK_SECRET`** en el Space.
58
+ Se envΓ­a por query `?token=XXX` o header `X-Webhook-Token: XXX`.
59
+ - MΓ©todo POST. Sin App Check (el llamador es externo, no la app).
60
+ - Ejemplo de URL a configurar en changedetection.io:
61
+ `https://andervier-tazas-api.hf.space/webhook/bcv-refresh?token=TU_SECRETO`
62
+ - Nota: esto mantiene FRESCO el dato del servidor. La notificaciΓ³n al telΓ©fono
63
+ sigue dependiendo del worker (cada 30 min); para push instantΓ‘neo harΓ­a falta
64
+ FCM (no incluido).
65
 
66
  ### HistΓ³rico (`/v2/history`) β€” Firestore
67
 
main.py CHANGED
@@ -1,5 +1,5 @@
1
  from contextlib import asynccontextmanager
2
- from fastapi import FastAPI, Depends, HTTPException, Header
3
  from fastapi.middleware.cors import CORSMiddleware
4
  from fastapi.responses import ORJSONResponse
5
  from bs4 import BeautifulSoup
@@ -7,6 +7,7 @@ import httpx
7
  import asyncio
8
  import time
9
  import re
 
10
  import jwt
11
  import logging
12
  import os
@@ -24,6 +25,12 @@ _cache: dict = {}
24
  BCV_TTL = 60 * 60 * 4 # 4 horas (BCV actualiza una vez al dΓ­a)
25
  P2P_TTL = 60 * 2 # 2 minutos
26
 
 
 
 
 
 
 
27
  # ──────────────────────────────────────────────
28
  # v2 β€” Constantes (aislamiento total respecto a v1)
29
  # ──────────────────────────────────────────────
@@ -156,17 +163,21 @@ def _parse_bcv_rate(text: str) -> float | None:
156
  # ──────────────────────────────────────────────
157
  # Fetchers
158
  # ──────────────────────────────────────────────
159
- async def fetch_bcv() -> dict:
160
- cached = _cached("bcv", BCV_TTL)
161
- if cached:
162
- return cached
163
-
164
- async with _lock("bcv"):
165
- # Double-check: mientras esperΓ‘bamos el lock, otro ya pudo haber refrescado
166
  cached = _cached("bcv", BCV_TTL)
167
  if cached:
168
  return cached
169
 
 
 
 
 
 
 
 
170
  headers = {
171
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
172
  "Accept-Language": "es-VE,es;q=0.9",
@@ -539,3 +550,51 @@ async def history_v2(country: str | None = None, days: int = 30):
539
  "points": results[2],
540
  } if include_local else None,
541
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from contextlib import asynccontextmanager
2
+ from fastapi import FastAPI, Depends, HTTPException, Header, Query
3
  from fastapi.middleware.cors import CORSMiddleware
4
  from fastapi.responses import ORJSONResponse
5
  from bs4 import BeautifulSoup
 
7
  import asyncio
8
  import time
9
  import re
10
+ import hmac
11
  import jwt
12
  import logging
13
  import os
 
25
  BCV_TTL = 60 * 60 * 4 # 4 horas (BCV actualiza una vez al dΓ­a)
26
  P2P_TTL = 60 * 2 # 2 minutos
27
 
28
+ # Throttle del webhook: aunque llegue con token vΓ‘lido, no se re-scrapea el BCV
29
+ # mΓ‘s de una vez cada N segundos. Neutraliza un flood con token vΓ‘lido (evita
30
+ # martillar a bcv.org.ve y quemar CPU). El cron legΓ­timo (cada 2 min) nunca lo toca.
31
+ _last_forced_refresh = 0.0
32
+ FORCED_REFRESH_MIN_INTERVAL = 30 # segundos
33
+
34
  # ──────────────────────────────────────────────
35
  # v2 β€” Constantes (aislamiento total respecto a v1)
36
  # ──────────────────────────────────────────────
 
163
  # ──────────────────────────────────────────────
164
  # Fetchers
165
  # ──────────────────────────────────────────────
166
+ async def fetch_bcv(force: bool = False) -> dict:
167
+ # force=True omite el cachΓ©: lo usa el webhook cuando changedetection.io
168
+ # avisa que la pΓ‘gina del BCV cambiΓ³, para traer la tasa nueva de inmediato.
169
+ if not force:
 
 
 
170
  cached = _cached("bcv", BCV_TTL)
171
  if cached:
172
  return cached
173
 
174
+ async with _lock("bcv"):
175
+ # Double-check: mientras esperΓ‘bamos el lock, otro ya pudo haber refrescado
176
+ if not force:
177
+ cached = _cached("bcv", BCV_TTL)
178
+ if cached:
179
+ return cached
180
+
181
  headers = {
182
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
183
  "Accept-Language": "es-VE,es;q=0.9",
 
550
  "points": results[2],
551
  } if include_local else None,
552
  }
553
+
554
+
555
+ # ──────────────────────────────────────────────
556
+ # Webhook β€” refresco inmediato del BCV (disparado por changedetection.io)
557
+ # ──────────────────────────────────────────────
558
+ # GET + POST para que sirva cualquier pinger externo gratuito (cron-job.org,
559
+ # UptimeRobot, GitHub Actions, etc.), incluidos los que solo hacen GET.
560
+ @app.api_route("/webhook/bcv-refresh", methods=["GET", "POST"])
561
+ async def bcv_refresh_webhook(
562
+ token: str | None = Query(default=None),
563
+ x_webhook_token: str | None = Header(default=None),
564
+ ):
565
+ """
566
+ Un servicio externo (cron gratuito) golpea este endpoint cada pocos minutos.
567
+ Fuerza un scrape fresco del BCV (ignora el cachΓ© de 4h) y registra el valor
568
+ nuevo en el histΓ³rico de inmediato. record_bcv deduplica por valor: si el
569
+ BCV no cambiΓ³, no escribe nada. De paso, el ping mantiene despierto el Space
570
+ (para que el muestreador interno de USDT tambiΓ©n corra).
571
+
572
+ Protegido por secreto compartido (env WEBHOOK_SECRET), vΓ­a query `?token=`
573
+ o header `X-Webhook-Token`. No usa App Check: el llamador es externo.
574
+ """
575
+ secret = os.getenv("WEBHOOK_SECRET")
576
+ if not secret:
577
+ raise HTTPException(status_code=404, detail="Not Found")
578
+
579
+ provided = x_webhook_token or token or ""
580
+ # compare_digest: comparaciΓ³n de tiempo constante (no filtra el secreto por timing).
581
+ # 404 en vez de 401: a un escΓ‘ner sin el token, el endpoint le parece inexistente.
582
+ if not hmac.compare_digest(provided, secret):
583
+ raise HTTPException(status_code=404, detail="Not Found")
584
+
585
+ # Throttle: con token vΓ‘lido pero llamadas muy seguidas, servir el ΓΊltimo valor
586
+ # sin re-scrapear. Acota el scrape a 1 cada FORCED_REFRESH_MIN_INTERVAL seg.
587
+ global _last_forced_refresh
588
+ now = time.time()
589
+ if now - _last_forced_refresh < FORCED_REFRESH_MIN_INTERVAL:
590
+ cached = _cached("bcv", BCV_TTL) or {}
591
+ return {"status": "throttled", "bcvUsd": cached.get("bcvUsd")}
592
+ _last_forced_refresh = now
593
+
594
+ data = await fetch_bcv(force=True)
595
+ history.record_bcv(data)
596
+ return {
597
+ "status": "refreshed",
598
+ "bcvUsd": data.get("bcvUsd"),
599
+ "updatedAt": data.get("updatedAt"),
600
+ }