Spaces:
Running

andervier commited on
Commit
58ca004
·
1 Parent(s): ce356ce

feat(api): metricas de uso en Firestore, campo previous BCV y debug App Check temporal

Browse files
Files changed (3) hide show
  1. history.py +53 -0
  2. main.py +96 -4
  3. stats.py +101 -0
history.py CHANGED
@@ -71,6 +71,12 @@ def is_enabled() -> bool:
71
  return _enabled
72
 
73
 
 
 
 
 
 
 
74
  # ──────────────────────────────────────────────
75
  # Escritura (fire-and-forget desde el muestreador)
76
  # ──────────────────────────────────────────────
@@ -216,3 +222,50 @@ def _normalize_points(raw) -> list[dict]:
216
  by_t[p["t"]] = p
217
  return list(by_t.values())
218
  return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  return _enabled
72
 
73
 
74
+ def get_db():
75
+ """Cliente Firestore compartido (o None si el histórico está deshabilitado).
76
+ Lo reutiliza stats.py para volcar métricas sin abrir otra conexión."""
77
+ return _db
78
+
79
+
80
  # ──────────────────────────────────────────────
81
  # Escritura (fire-and-forget desde el muestreador)
82
  # ──────────────────────────────────────────────
 
222
  by_t[p["t"]] = p
223
  return list(by_t.values())
224
  return []
225
+
226
+
227
+ # ──────────────────────────────────────────────
228
+ # Estado BCV: {current, previous} para la "tasa del viernes"
229
+ # ──────────────────────────────────────────────
230
+ # El fin de semana rige la tasa publicada el viernes (fecha valor "Lunes"); la
231
+ # tasa "del viernes" que algunos usuarios prefieren es la publicación INMEDIATA-
232
+ # MENTE anterior (fecha valor "Viernes"). Guardamos {current, previous} en un doc
233
+ # aparte para servirla sin reconstruirla en el cliente. Se desplaza current->previous
234
+ # solo cuando cambia el `updatedAt` (fecha valor) — idempotente entre los 2 workers.
235
+ BCV_STATE_COLLECTION = "bcv_state"
236
+ BCV_STATE_DOC = "latest"
237
+
238
+
239
+ async def update_bcv_state(current: dict) -> dict | None:
240
+ """Actualiza {current, previous} si el `updatedAt` scrapeado es nuevo.
241
+ Devuelve el `previous` resultante (o None). No tumba el scrape si Firestore falla."""
242
+ if not _enabled:
243
+ return None
244
+ try:
245
+ doc = _db.collection(BCV_STATE_COLLECTION).document(BCV_STATE_DOC)
246
+ snap = await doc.get()
247
+ state = snap.to_dict() if snap.exists else {}
248
+ stored_current = state.get("current") or {}
249
+ # Idempotente: si el worker vecino ya guardó esta misma publicación,
250
+ # no volver a desplazar (previous quedaría corrupto).
251
+ if stored_current.get("updatedAt") == current.get("updatedAt"):
252
+ return state.get("previous")
253
+ previous = stored_current or None
254
+ await doc.set({"current": current, "previous": previous})
255
+ return previous
256
+ except Exception as e:
257
+ logger.error("update_bcv_state falló: %s", e)
258
+ return None
259
+
260
+
261
+ async def get_bcv_previous() -> dict | None:
262
+ """Lee el `previous` (tasa del viernes) del estado BCV, o None."""
263
+ if not _enabled:
264
+ return None
265
+ try:
266
+ snap = await _db.collection(BCV_STATE_COLLECTION).document(BCV_STATE_DOC).get()
267
+ if snap.exists:
268
+ return (snap.to_dict() or {}).get("previous")
269
+ except Exception as e:
270
+ logger.error("get_bcv_previous falló: %s", e)
271
+ return None
main.py CHANGED
@@ -14,6 +14,7 @@ import os
14
  from jwt import PyJWKClient
15
 
16
  import history
 
17
 
18
  logging.basicConfig(level=logging.WARNING)
19
  logger = logging.getLogger(__name__)
@@ -94,9 +95,12 @@ async def lifespan(app: FastAPI):
94
  _http_nv = httpx.AsyncClient(timeout=15, follow_redirects=True, verify=False, limits=limits)
95
  history.init()
96
  sampler = asyncio.create_task(_history_sampler()) if history.is_enabled() else None
 
97
  yield
98
  if sampler:
99
  sampler.cancel()
 
 
100
  await _http.aclose()
101
  await _http_nv.aclose()
102
 
@@ -115,6 +119,23 @@ app.add_middleware(
115
  allow_headers=["*"],
116
  )
117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  # ──────────────────────────────────────────────
119
  # Firebase App Check
120
  # ──────────────────────────────────────────────
@@ -146,6 +167,53 @@ def verify_app_check(x_firebase_appcheck: str = Header(None)):
146
  raise HTTPException(status_code=401, detail="Token App Check inválido")
147
 
148
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  # ──────────────────────────────────────────────
150
  # Helpers
151
  # ──────────────────────────────────────────────
@@ -212,9 +280,31 @@ async def fetch_bcv(force: bool = False) -> dict:
212
 
213
  data = {**rates, "updatedAt": updated_at}
214
  _store("bcv", data)
 
 
 
 
 
 
 
 
 
 
 
215
  return data
216
 
217
 
 
 
 
 
 
 
 
 
 
 
 
218
  async def fetch_p2p() -> dict:
219
  cached = _cached("p2p", P2P_TTL)
220
  if cached:
@@ -486,23 +576,25 @@ async def rates_v2(country: str | None = None):
486
  logger.info("/v2/rates country=%s fiat=%s", cc, fiat)
487
 
488
  if cc == "VE":
489
- bcv_data, ve_p2p = await asyncio.gather(
490
  fetch_bcv(),
491
  fetch_p2p_v2_safe("VES"),
 
492
  )
493
  return {
494
- "venezuela": {**bcv_data, **ve_p2p},
495
  "local": None,
496
  }
497
 
498
- bcv_data, ve_p2p, local_p2p = await asyncio.gather(
499
  fetch_bcv(),
500
  fetch_p2p_v2_safe("VES"),
501
  fetch_p2p_v2_safe(fiat),
 
502
  )
503
 
504
  return {
505
- "venezuela": {**bcv_data, **ve_p2p},
506
  "local": {
507
  "countryCode": cc,
508
  "currency": fiat,
 
14
  from jwt import PyJWKClient
15
 
16
  import history
17
+ import stats
18
 
19
  logging.basicConfig(level=logging.WARNING)
20
  logger = logging.getLogger(__name__)
 
95
  _http_nv = httpx.AsyncClient(timeout=15, follow_redirects=True, verify=False, limits=limits)
96
  history.init()
97
  sampler = asyncio.create_task(_history_sampler()) if history.is_enabled() else None
98
+ stats_task = stats.start(history.get_db)
99
  yield
100
  if sampler:
101
  sampler.cancel()
102
+ if stats_task:
103
+ stats_task.cancel()
104
  await _http.aclose()
105
  await _http_nv.aclose()
106
 
 
119
  allow_headers=["*"],
120
  )
121
 
122
+
123
+ @app.middleware("http")
124
+ async def _stats_middleware(request, call_next):
125
+ # Mide throughput/latencia/errores por endpoint. Si call_next lanza, cuenta 500.
126
+ # DEBUG TEMPORAL: captura qué llega en los endpoints de datos (App Check).
127
+ path = request.url.path
128
+ if path.startswith("/v1") or path.startswith("/v2"):
129
+ await _capture_request_debug(request)
130
+ started = time.perf_counter()
131
+ status = 500
132
+ try:
133
+ response = await call_next(request)
134
+ status = response.status_code
135
+ return response
136
+ finally:
137
+ stats.record(request.url.path, status, time.perf_counter() - started)
138
+
139
  # ──────────────────────────────────────────────
140
  # Firebase App Check
141
  # ──────────────────────────────────────────────
 
167
  raise HTTPException(status_code=401, detail="Token App Check inválido")
168
 
169
 
170
+ # ──────────────────────────────────────────────
171
+ # DEBUG TEMPORAL — App Check: qué llega en las peticiones
172
+ # ──────────────────────────────────────────────
173
+ # Escribe en Firestore appcheck_debug/last la última petición a /v1|/v2: si trae
174
+ # token App Check, sus claims SIN verificar (sub/aud/exp) + si el sub coincide con
175
+ # el esperado. Funciona con DISABLE_APP_CHECK=1 (servicio arriba), así ves qué
176
+ # manda el celular sin cortar a nadie. NO guarda el token (es credencial), solo su
177
+ # longitud y claims. Throttle 5s para no floodear Firestore. QUITAR al resolver.
178
+ _last_appcheck_debug = 0.0
179
+
180
+
181
+ async def _capture_request_debug(request) -> None:
182
+ global _last_appcheck_debug
183
+ db = history.get_db()
184
+ if db is None:
185
+ return
186
+ now = time.time()
187
+ if now - _last_appcheck_debug < 5:
188
+ return
189
+ _last_appcheck_debug = now
190
+
191
+ token = request.headers.get("x-firebase-appcheck")
192
+ info = {
193
+ "ts": int(now),
194
+ "path": request.url.path,
195
+ "method": request.method,
196
+ "userAgent": request.headers.get("user-agent"),
197
+ "hasToken": token is not None,
198
+ "disableAppCheck": os.getenv("DISABLE_APP_CHECK"),
199
+ "expectedSub": APP_ID,
200
+ "expectedAud": f"projects/{PROJECT_NUMBER}",
201
+ }
202
+ if token:
203
+ info["tokenLen"] = len(token)
204
+ try:
205
+ claims = jwt.decode(token, options={"verify_signature": False})
206
+ info["claims"] = {k: claims.get(k) for k in ("sub", "aud", "iss", "exp", "iat")}
207
+ info["subMatches"] = claims.get("sub") == APP_ID
208
+ except Exception as e:
209
+ info["decodeError"] = f"{type(e).__name__}: {e}"
210
+
211
+ try:
212
+ await db.collection("appcheck_debug").document("last").set(info)
213
+ except Exception as e:
214
+ logger.error("appcheck debug capture falló: %s", e)
215
+
216
+
217
  # ──────────────────────────────────────────────
218
  # Helpers
219
  # ──────────────────────────────────────────────
 
280
 
281
  data = {**rates, "updatedAt": updated_at}
282
  _store("bcv", data)
283
+
284
+ # Mantiene {current, previous} para la "tasa del viernes". Solo corre en un
285
+ # scrape real (no en cache hits) y con fecha valor presente, así que el costo
286
+ # en Firestore es raro y no se corrompe el estado si falla leer la fecha.
287
+ if history.is_enabled() and data.get("updatedAt"):
288
+ try:
289
+ previous = await history.update_bcv_state(data)
290
+ _store("bcv_previous", previous or {})
291
+ except Exception as e:
292
+ logger.warning("update_bcv_state falló: %s", e)
293
+
294
  return data
295
 
296
 
297
+ async def _bcv_previous() -> dict | None:
298
+ """Tasa BCV inmediatamente anterior (la 'del viernes' durante el fin de semana).
299
+ Cacheada en memoria; se relee de Firestore al vencer el TTL del BCV. {} = sin dato."""
300
+ cached = _cached("bcv_previous", BCV_TTL)
301
+ if cached is not None:
302
+ return cached or None
303
+ previous = await history.get_bcv_previous()
304
+ _store("bcv_previous", previous or {})
305
+ return previous
306
+
307
+
308
  async def fetch_p2p() -> dict:
309
  cached = _cached("p2p", P2P_TTL)
310
  if cached:
 
576
  logger.info("/v2/rates country=%s fiat=%s", cc, fiat)
577
 
578
  if cc == "VE":
579
+ bcv_data, ve_p2p, prev = await asyncio.gather(
580
  fetch_bcv(),
581
  fetch_p2p_v2_safe("VES"),
582
+ _bcv_previous(),
583
  )
584
  return {
585
+ "venezuela": {**bcv_data, **ve_p2p, "previous": prev},
586
  "local": None,
587
  }
588
 
589
+ bcv_data, ve_p2p, local_p2p, prev = await asyncio.gather(
590
  fetch_bcv(),
591
  fetch_p2p_v2_safe("VES"),
592
  fetch_p2p_v2_safe(fiat),
593
+ _bcv_previous(),
594
  )
595
 
596
  return {
597
+ "venezuela": {**bcv_data, **ve_p2p, "previous": prev},
598
  "local": {
599
  "countryCode": cc,
600
  "currency": fiat,
stats.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Métricas de uso en memoria + flush periódico a Firestore.
3
+
4
+ Objetivo: una guía aproximada de carga (¿me están martillando? ¿necesito escalar?),
5
+ NO analítica de usuarios. Se mide throughput, errores y latencia — no "usuarios
6
+ únicos", que en una API sin estado es poco fiable.
7
+
8
+ Diseño para HF Spaces (2 workers uvicorn):
9
+ - Cada worker cuenta en memoria sus propias peticiones (contador por proceso).
10
+ - Cada FLUSH_INTERVAL vuelca su snapshot a un único doc Firestore
11
+ `api_stats/live`, bajo el campo `worker_{pid}`. El doc se revisa directo en la
12
+ consola de Firestore (no hay endpoint público → nada que proteger).
13
+ - El lector suma los workers con `ts` reciente; los PID viejos (tras reinicio del
14
+ Space) quedan con `ts` antiguo y se ignoran a ojo.
15
+
16
+ Sin FIREBASE_SERVICE_ACCOUNT (Firestore deshabilitado) el flush simplemente no
17
+ corre; los contadores en memoria siguen, inofensivos.
18
+ """
19
+
20
+ import asyncio
21
+ import logging
22
+ import os
23
+ import time
24
+ from collections import defaultdict
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+ STATS_COLLECTION = "api_stats"
29
+ STATS_DOC = "live"
30
+ FLUSH_INTERVAL = 120 # segundos entre flushes (2 min → ~720 escrituras/día/worker)
31
+ MINUTE_WINDOW = 60 # minutos de historial req/min que se conservan
32
+
33
+ _pid = os.getpid()
34
+ _started = time.time()
35
+ _total = 0
36
+ _errors_5xx = 0
37
+ _by_path: dict[str, int] = defaultdict(int)
38
+ _by_status: dict[str, int] = defaultdict(int)
39
+ _latency_sum = 0.0
40
+ _latency_max = 0.0
41
+ _per_minute: dict[int, int] = defaultdict(int) # minuto_epoch → nº de peticiones
42
+
43
+
44
+ def record(path: str, status: int, elapsed: float) -> None:
45
+ """Registra una petición. `elapsed` en segundos."""
46
+ global _total, _errors_5xx, _latency_sum, _latency_max
47
+ _total += 1
48
+ _by_path[path] += 1
49
+ _by_status[str(status)] += 1
50
+ if status >= 500:
51
+ _errors_5xx += 1
52
+ _latency_sum += elapsed
53
+ if elapsed > _latency_max:
54
+ _latency_max = elapsed
55
+
56
+ minute = int(time.time()) // 60 * 60
57
+ _per_minute[minute] += 1
58
+ # Podar la ventana rodante para que el dict no crezca sin límite.
59
+ cutoff = minute - MINUTE_WINDOW * 60
60
+ for stale in [m for m in _per_minute if m < cutoff]:
61
+ del _per_minute[stale]
62
+
63
+
64
+ def snapshot() -> dict:
65
+ avg_latency = (_latency_sum / _total) if _total else 0.0
66
+ return {
67
+ "pid": _pid,
68
+ "ts": int(time.time()),
69
+ "uptimeSec": round(time.time() - _started),
70
+ "totalRequests": _total,
71
+ "errors5xx": _errors_5xx,
72
+ "avgLatencyMs": round(avg_latency * 1000, 1),
73
+ "maxLatencyMs": round(_latency_max * 1000, 1),
74
+ "byPath": dict(_by_path),
75
+ "byStatus": dict(_by_status),
76
+ # req/min de la última hora: mapa {minuto_epoch: nº}. Da la curva de carga.
77
+ "perMinute": {str(k): v for k, v in sorted(_per_minute.items())},
78
+ }
79
+
80
+
81
+ async def _flush_loop(get_db) -> None:
82
+ while True:
83
+ await asyncio.sleep(FLUSH_INTERVAL)
84
+ db = get_db()
85
+ if db is None:
86
+ continue
87
+ try:
88
+ await db.collection(STATS_COLLECTION).document(STATS_DOC).set(
89
+ {f"worker_{_pid}": snapshot()}, merge=True
90
+ )
91
+ except Exception as e:
92
+ logger.error("stats flush falló: %s", e)
93
+
94
+
95
+ def start(get_db) -> "asyncio.Task | None":
96
+ """Arranca el flush en background. `get_db` es un callable que devuelve el
97
+ cliente Firestore (o None). Devuelve la task para poder cancelarla al cerrar."""
98
+ try:
99
+ return asyncio.get_running_loop().create_task(_flush_loop(get_db))
100
+ except RuntimeError:
101
+ return None # sin event loop (tests)