Spaces:
Running

andervier commited on
Commit
d5fc8e2
Β·
1 Parent(s): ebc8a27

feat: historico de tasas en Firestore + endpoint /v2/history + muestreador cada 15 min

Browse files
Files changed (5) hide show
  1. Dockerfile +1 -1
  2. NOTAS_DEV.md +24 -6
  3. history.py +166 -0
  4. main.py +78 -0
  5. requirements.txt +1 -0
Dockerfile CHANGED
@@ -7,7 +7,7 @@ WORKDIR /app
7
  COPY requirements.txt .
8
  RUN pip install --no-cache-dir -r requirements.txt
9
 
10
- COPY main.py .
11
 
12
  EXPOSE 7860
13
 
 
7
  COPY requirements.txt .
8
  RUN pip install --no-cache-dir -r requirements.txt
9
 
10
+ COPY main.py history.py ./
11
 
12
  EXPOSE 7860
13
 
NOTAS_DEV.md CHANGED
@@ -39,12 +39,30 @@ Todos los endpoints `/v1/*` requieren el header:
39
  X-Firebase-AppCheck: {token JWT}
40
  ```
41
 
42
- | MΓ©todo | Ruta | DescripciΓ³n |
43
- |--------|-------------|--------------------------------------|
44
- | GET | `/` | Health check β†’ `{"status":"ok"}` |
45
- | GET | `/v1/rates` | Todas las tasas (BCV + P2P) |
46
- | GET | `/v1/bcv` | Solo tasas BCV |
47
- | GET | `/v1/p2p` | Solo tasas Binance P2P |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
  ### Respuesta de `/v1/rates`
50
 
 
39
  X-Firebase-AppCheck: {token JWT}
40
  ```
41
 
42
+ | MΓ©todo | Ruta | DescripciΓ³n |
43
+ |--------|---------------|----------------------------------------------------|
44
+ | GET | `/` | Health check β†’ `{"status":"ok"}` |
45
+ | GET | `/v1/rates` | Todas las tasas (BCV + P2P) |
46
+ | GET | `/v1/bcv` | Solo tasas BCV |
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
+
53
+ - Persistencia en Firestore (proyecto Firebase de Tazas), colecciΓ³n `rate_history`.
54
+ - Documentos MENSUALES por serie: `BCV_2026-07`, `VES_2026-07`, `COP_2026-07`…
55
+ cada uno con un array `points` (`{t, ...}`, `t` = epoch UTC en buckets de 5 min).
56
+ - Escritura oportunista: los fetchers registran solo datos frescos y solo si el
57
+ valor cambiΓ³; `ArrayUnion` + bucket de 5 min evita duplicados entre los 2 workers.
58
+ - Lectura: ≀2 docs por serie para 35 dΓ­as; meses pasados cacheados 24h en memoria.
59
+ - Muestreador activo: bucle interno que cada 15 min fetchea BCV + USDT de TODAS
60
+ las fiats soportadas (registro con dedupe), para que el histΓ³rico no dependa
61
+ del trΓ‘fico de usuarios por paΓ­s. Si el Space duerme, el muestreo se pausa
62
+ (quedan huecos, no errores).
63
+ - **Requiere el secret `FIREBASE_SERVICE_ACCOUNT`** en el Space (JSON completo de
64
+ la service account). Sin Γ©l, el histΓ³rico se deshabilita y la API sigue normal.
65
+ - Respuesta: `{days, bcv: [{t,usd,eur,cny,try,rub}], p2p: [{t,buy,sell}], local: {currency, points} | null}`.
66
 
67
  ### Respuesta de `/v1/rates`
68
 
history.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ HistΓ³rico de tasas persistido en Firestore.
3
+
4
+ DiseΓ±o pensado para HF Spaces (disco efΓ­mero, 2 workers uvicorn) y para no
5
+ saturar el tier gratis de Firebase:
6
+
7
+ - Escritura OPORTUNISTA: los fetchers llaman record_*() solo cuando traen
8
+ datos frescos; se escribe ΓΊnicamente si el valor cambiΓ³ (dedupe por worker).
9
+ - Identidad determinista de puntos: el timestamp se redondea a buckets de
10
+ 5 min, asΓ­ si los 2 workers registran el mismo dato, ArrayUnion no duplica.
11
+ - Documentos MENSUALES por serie (BCV_2026-07, VES_2026-07, COP_2026-07...):
12
+ leer 35 dΓ­as cuesta ≀2 lecturas por serie, y los meses pasados son
13
+ inmutables β†’ se cachean en memoria y las lecturas repetidas cuestan 0.
14
+
15
+ Requiere el secret FIREBASE_SERVICE_ACCOUNT (JSON de la service account del
16
+ proyecto Firebase). Sin Γ©l, el histΓ³rico queda deshabilitado y la API sigue
17
+ funcionando normal.
18
+ """
19
+
20
+ import asyncio
21
+ import json
22
+ import logging
23
+ import os
24
+ import time
25
+ from datetime import datetime, timedelta, timezone
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ COLLECTION = "rate_history"
30
+ BUCKET_SECONDS = 300 # identidad de punto: bucket de 5 min
31
+ MAX_DAYS = 35
32
+
33
+ # CachΓ© de lecturas: el mes actual expira rΓ‘pido; los pasados son inmutables.
34
+ CURRENT_MONTH_TTL = 60 * 10
35
+ PAST_MONTH_TTL = 60 * 60 * 24
36
+
37
+ _db = None # firestore.AsyncClient
38
+ _enabled = False
39
+ _last_values: dict[str, dict] = {} # dedupe por worker: serie β†’ ΓΊltimos valores escritos
40
+ _read_cache: dict[str, dict] = {} # doc_id β†’ {"ts": epoch, "points": [...]}
41
+
42
+
43
+ def init() -> None:
44
+ """Inicializa Firestore desde el secret. Nunca tumba la API si falta."""
45
+ global _db, _enabled
46
+ raw = os.getenv("FIREBASE_SERVICE_ACCOUNT")
47
+ if not raw:
48
+ logger.warning("FIREBASE_SERVICE_ACCOUNT no configurado β€” histΓ³rico deshabilitado")
49
+ return
50
+ try:
51
+ from google.cloud import firestore
52
+ from google.oauth2 import service_account
53
+
54
+ info = json.loads(raw)
55
+ creds = service_account.Credentials.from_service_account_info(
56
+ info, scopes=["https://www.googleapis.com/auth/datastore"]
57
+ )
58
+ _db = firestore.AsyncClient(project=info["project_id"], credentials=creds)
59
+ _enabled = True
60
+ logger.warning("HistΓ³rico habilitado (proyecto %s)", info["project_id"])
61
+ except Exception as e:
62
+ logger.error("No se pudo inicializar Firestore: %s", e, exc_info=True)
63
+
64
+
65
+ def is_enabled() -> bool:
66
+ return _enabled
67
+
68
+
69
+ # ──────────────────────────────────────────────
70
+ # Escritura (fire-and-forget desde los fetchers)
71
+ # ──────────────────────────────────────────────
72
+ def record_bcv(data: dict) -> None:
73
+ values = {
74
+ k: data.get(src)
75
+ for k, src in (("usd", "bcvUsd"), ("eur", "bcvEur"), ("cny", "bcvCny"),
76
+ ("try", "bcvTry"), ("rub", "bcvRub"))
77
+ if data.get(src) is not None
78
+ }
79
+ _schedule("BCV", values)
80
+
81
+
82
+ def record_p2p(fiat: str, buy: float | None, sell: float | None) -> None:
83
+ values = {}
84
+ if buy is not None:
85
+ values["buy"] = buy
86
+ if sell is not None:
87
+ values["sell"] = sell
88
+ _schedule(fiat, values)
89
+
90
+
91
+ def _schedule(series: str, values: dict) -> None:
92
+ if not _enabled or not values:
93
+ return
94
+ if _last_values.get(series) == values:
95
+ return # nada cambiΓ³ desde la ΓΊltima escritura de este worker
96
+ try:
97
+ asyncio.get_running_loop().create_task(_append(series, values))
98
+ except RuntimeError:
99
+ pass # sin event loop (tests) β€” no registrar
100
+
101
+
102
+ async def _append(series: str, values: dict) -> None:
103
+ from google.cloud import firestore
104
+
105
+ now = int(time.time())
106
+ bucket = now // BUCKET_SECONDS * BUCKET_SECONDS
107
+ point = {"t": bucket, **values}
108
+ month = datetime.fromtimestamp(now, tz=timezone.utc).strftime("%Y-%m")
109
+ try:
110
+ doc = _db.collection(COLLECTION).document(f"{series}_{month}")
111
+ await doc.set({"points": firestore.ArrayUnion([point])}, merge=True)
112
+ _last_values[series] = values
113
+ # El doc del mes actual cambiΓ³: invalidar su cachΓ© de lectura local.
114
+ _read_cache.pop(f"{series}_{month}", None)
115
+ except Exception as e:
116
+ logger.error("No se pudo registrar histΓ³rico %s: %s", series, e)
117
+
118
+
119
+ # ──────────────────────────────────────────────
120
+ # Lectura
121
+ # ──────────────────────────────────────────────
122
+ async def get_history(series: str, days: int) -> list[dict]:
123
+ """Puntos de la serie en los ΓΊltimos `days` dΓ­as, ordenados por timestamp."""
124
+ if not _enabled:
125
+ return []
126
+ days = max(1, min(days, MAX_DAYS))
127
+ now = datetime.now(tz=timezone.utc)
128
+ cutoff = int((now - timedelta(days=days)).timestamp())
129
+
130
+ points: list[dict] = []
131
+ for month in _months_between(now - timedelta(days=days), now):
132
+ points.extend(await _read_month(series, month, is_current=(month == now.strftime("%Y-%m"))))
133
+ return sorted((p for p in points if p.get("t", 0) >= cutoff), key=lambda p: p["t"])
134
+
135
+
136
+ def _months_between(start: datetime, end: datetime) -> list[str]:
137
+ months = []
138
+ cursor = datetime(start.year, start.month, 1, tzinfo=timezone.utc)
139
+ while cursor <= end:
140
+ months.append(cursor.strftime("%Y-%m"))
141
+ cursor = datetime(
142
+ cursor.year + (cursor.month == 12),
143
+ cursor.month % 12 + 1,
144
+ 1,
145
+ tzinfo=timezone.utc,
146
+ )
147
+ return months
148
+
149
+
150
+ async def _read_month(series: str, month: str, is_current: bool) -> list[dict]:
151
+ doc_id = f"{series}_{month}"
152
+ ttl = CURRENT_MONTH_TTL if is_current else PAST_MONTH_TTL
153
+ cached = _read_cache.get(doc_id)
154
+ if cached and (time.time() - cached["ts"]) < ttl:
155
+ return cached["points"]
156
+
157
+ try:
158
+ snap = await _db.collection(COLLECTION).document(doc_id).get()
159
+ points = list((snap.to_dict() or {}).get("points") or []) if snap.exists else []
160
+ except Exception as e:
161
+ logger.error("No se pudo leer histΓ³rico %s: %s", doc_id, e)
162
+ # Fallback: servir cachΓ© vencido antes que nada.
163
+ return cached["points"] if cached else []
164
+
165
+ _read_cache[doc_id] = {"ts": time.time(), "points": points}
166
+ return points
main.py CHANGED
@@ -12,6 +12,8 @@ import logging
12
  import os
13
  from jwt import PyJWKClient
14
 
 
 
15
  logging.basicConfig(level=logging.WARNING)
16
  logger = logging.getLogger(__name__)
17
 
@@ -83,7 +85,11 @@ async def lifespan(app: FastAPI):
83
  limits = httpx.Limits(max_connections=10, max_keepalive_connections=5)
84
  _http = httpx.AsyncClient(timeout=10, limits=limits)
85
  _http_nv = httpx.AsyncClient(timeout=15, follow_redirects=True, verify=False, limits=limits)
 
 
86
  yield
 
 
87
  await _http.aclose()
88
  await _http_nv.aclose()
89
 
@@ -195,6 +201,7 @@ async def fetch_bcv() -> dict:
195
 
196
  data = {**rates, "updatedAt": updated_at}
197
  _store("bcv", data)
 
198
  return data
199
 
200
 
@@ -270,6 +277,7 @@ async def fetch_p2p() -> dict:
270
 
271
  data = {"p2pBuyMax": p2p_buy, "p2pSellMax": p2p_sell}
272
  _store("p2p", data)
 
273
  return data
274
 
275
 
@@ -339,6 +347,7 @@ async def fetch_p2p_v2(fiat: str) -> dict:
339
 
340
  data = {"p2pBuyMax": p2p_buy, "p2pSellMax": p2p_sell}
341
  _store(cache_key, data)
 
342
  return data
343
 
344
 
@@ -350,6 +359,36 @@ async def fetch_p2p_v2_safe(fiat: str) -> dict:
350
  return {"p2pBuyMax": None, "p2pSellMax": None}
351
 
352
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
353
  def validate_country(country: str | None) -> str:
354
  if not country:
355
  raise HTTPException(status_code=400, detail="Query param 'country' es requerido")
@@ -462,3 +501,42 @@ async def rates_v2(country: str | None = None):
462
  "updatedAt": None,
463
  },
464
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  import os
13
  from jwt import PyJWKClient
14
 
15
+ import history
16
+
17
  logging.basicConfig(level=logging.WARNING)
18
  logger = logging.getLogger(__name__)
19
 
 
85
  limits = httpx.Limits(max_connections=10, max_keepalive_connections=5)
86
  _http = httpx.AsyncClient(timeout=10, limits=limits)
87
  _http_nv = httpx.AsyncClient(timeout=15, follow_redirects=True, verify=False, limits=limits)
88
+ history.init()
89
+ sampler = asyncio.create_task(_history_sampler()) if history.is_enabled() else None
90
  yield
91
+ if sampler:
92
+ sampler.cancel()
93
  await _http.aclose()
94
  await _http_nv.aclose()
95
 
 
201
 
202
  data = {**rates, "updatedAt": updated_at}
203
  _store("bcv", data)
204
+ history.record_bcv(rates)
205
  return data
206
 
207
 
 
277
 
278
  data = {"p2pBuyMax": p2p_buy, "p2pSellMax": p2p_sell}
279
  _store("p2p", data)
280
+ history.record_p2p("VES", p2p_buy, p2p_sell)
281
  return data
282
 
283
 
 
347
 
348
  data = {"p2pBuyMax": p2p_buy, "p2pSellMax": p2p_sell}
349
  _store(cache_key, data)
350
+ history.record_p2p(fiat, p2p_buy, p2p_sell)
351
  return data
352
 
353
 
 
359
  return {"p2pBuyMax": None, "p2pSellMax": None}
360
 
361
 
362
+ # ──────────────────────────────────────────────
363
+ # Muestreador de histΓ³rico: cada 15 min registra BCV + USDT de TODAS las fiats,
364
+ # sin depender de que un usuario de ese paΓ­s pida tasas. Los fetchers ya hacen
365
+ # el registro (con dedupe por valor), asΓ­ que aquΓ­ solo se fuerza el fetch.
366
+ #
367
+ # Notas de operaciΓ³n:
368
+ # - Con --workers 2 el bucle corre en ambos procesos: el jitter inicial los
369
+ # desincroniza y la identidad por bucket de 5 min evita duplicados en la DB.
370
+ # El costo extra son ~4 llamadas/min a Binance en el peor caso β€” irrelevante.
371
+ # - Si el Space duerme (sin trΓ‘fico), el muestreo se pausa: quedan huecos en el
372
+ # histΓ³rico, no errores. Con usuarios activos el Space casi nunca duerme.
373
+ # ──────────────────────────────────────────────
374
+ HISTORY_SAMPLE_INTERVAL = 60 * 15
375
+ HISTORY_SAMPLE_SPACING = 2 # segundos entre fiats para no ametrallar a Binance
376
+
377
+ async def _history_sampler():
378
+ import random
379
+ await asyncio.sleep(random.uniform(5, 120)) # desincronizar los 2 workers
380
+ fiats = sorted(set(SUPPORTED_COUNTRIES.values()))
381
+ while True:
382
+ try:
383
+ await fetch_bcv() # registra solo si la tasa cambiΓ³
384
+ except Exception as e:
385
+ logger.warning("sampler: fetch_bcv fallΓ³: %s", e)
386
+ for fiat in fiats:
387
+ await fetch_p2p_v2_safe(fiat)
388
+ await asyncio.sleep(HISTORY_SAMPLE_SPACING)
389
+ await asyncio.sleep(HISTORY_SAMPLE_INTERVAL)
390
+
391
+
392
  def validate_country(country: str | None) -> str:
393
  if not country:
394
  raise HTTPException(status_code=400, detail="Query param 'country' es requerido")
 
501
  "updatedAt": None,
502
  },
503
  }
504
+
505
+
506
+ # ──────────────────────────────────────────────
507
+ # v2 β€” HistΓ³rico (persistido en Firestore)
508
+ # ──────────────────────────────────────────────
509
+ @app.get("/v2/history", dependencies=[Depends(verify_app_check)])
510
+ async def history_v2(country: str | None = None, days: int = 30):
511
+ """
512
+ HistΓ³rico de tasas de los ΓΊltimos `days` dΓ­as (mΓ‘x 35).
513
+
514
+ - bcv: puntos {t, usd, eur, cny, try, rub} β€” el BCV cambia ~1 vez/dΓ­a.
515
+ - p2p: puntos {t, buy, sell} de USDT/VES β€” fluctΓΊa durante el dΓ­a.
516
+ - local: puntos {t, buy, sell} de USDT/{fiat} β€” null para VE/dolarizados.
517
+
518
+ `t` es epoch en segundos (UTC), redondeado a buckets de 5 minutos.
519
+ """
520
+ cc = validate_country(country)
521
+ if not history.is_enabled():
522
+ raise HTTPException(status_code=503, detail="HistΓ³rico no disponible")
523
+
524
+ days = max(1, min(days, 35))
525
+ fiat = SUPPORTED_COUNTRIES[cc]
526
+ include_local = cc != "VE"
527
+
528
+ tasks = [history.get_history("BCV", days), history.get_history("VES", days)]
529
+ if include_local:
530
+ tasks.append(history.get_history(fiat, days))
531
+ results = await asyncio.gather(*tasks)
532
+
533
+ return {
534
+ "days": days,
535
+ "bcv": results[0],
536
+ "p2p": results[1],
537
+ "local": {
538
+ "countryCode": cc,
539
+ "currency": fiat,
540
+ "points": results[2],
541
+ } if include_local else None,
542
+ }
requirements.txt CHANGED
@@ -6,3 +6,4 @@ beautifulsoup4==4.12.3
6
  lxml==5.3.0
7
  uvloop==0.21.0
8
  orjson==3.10.15
 
 
6
  lxml==5.3.0
7
  uvloop==0.21.0
8
  orjson==3.10.15
9
+ google-cloud-firestore==2.20.0