Spaces:
Running

File size: 11,037 Bytes
d5fc8e2
 
 
 
 
 
3b2a304
 
 
 
 
 
 
d5fc8e2
 
 
3b2a304
 
d5fc8e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b2a304
d5fc8e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58ca004
 
 
 
 
 
d5fc8e2
3b2a304
d5fc8e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce356ce
d5fc8e2
ce356ce
 
 
 
 
 
 
 
 
 
 
3b2a304
d5fc8e2
 
ce356ce
d5fc8e2
 
 
 
ce356ce
 
 
 
 
 
 
 
 
 
 
 
d5fc8e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b2a304
 
d5fc8e2
 
 
 
 
 
 
3b2a304
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58ca004
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
"""
Histórico de tasas persistido en Firestore.

Diseño pensado para HF Spaces (disco efímero, 2 workers uvicorn) y para no
saturar el tier gratis de Firebase:

- Un único escritor: el muestreador (cada 15 min) llama record_*(); se escribe
  solo si el valor cambió (dedupe por worker). No hay escritura oportunista
  desde los fetchers, para acotar el volumen de escrituras.
- Puntos como MAPA {bucket: valores} dentro del doc, indexados por franja de
  15 min. Una sola entrada por bucket: si dos fuentes escriben la misma franja
  con precios distintos, la última gana (antes, ArrayUnion apilaba ambas y
  duplicaba puntos con el mismo `t`).
- Documentos MENSUALES por serie (BCV_2026-07, VES_2026-07, COP_2026-07...):
  leer 35 días cuesta ≤2 lecturas por serie, y los meses pasados son
  inmutables → se cachean en memoria y las lecturas repetidas cuestan 0.
  Con 1 punto por franja de 15 min, un mes ≈ 3000 puntos (muy por debajo del
  límite de 1 MiB por documento de Firestore).

Requiere el secret FIREBASE_SERVICE_ACCOUNT (JSON de la service account del
proyecto Firebase). Sin él, el histórico queda deshabilitado y la API sigue
funcionando normal.
"""

import asyncio
import json
import logging
import os
import time
from datetime import datetime, timedelta, timezone

logger = logging.getLogger(__name__)

COLLECTION = "rate_history"
BUCKET_SECONDS = 900          # una entrada por franja de 15 min (= cadencia del muestreador)
MAX_DAYS = 35

# Caché de lecturas: el mes actual expira rápido; los pasados son inmutables.
CURRENT_MONTH_TTL = 60 * 10
PAST_MONTH_TTL = 60 * 60 * 24

_db = None                    # firestore.AsyncClient
_enabled = False
_last_values: dict[str, dict] = {}   # dedupe por worker: serie → últimos valores escritos
_read_cache: dict[str, dict] = {}    # doc_id → {"ts": epoch, "points": [...]}


def init() -> None:
    """Inicializa Firestore desde el secret. Nunca tumba la API si falta."""
    global _db, _enabled
    raw = os.getenv("FIREBASE_SERVICE_ACCOUNT")
    if not raw:
        logger.warning("FIREBASE_SERVICE_ACCOUNT no configurado — histórico deshabilitado")
        return
    try:
        from google.cloud import firestore
        from google.oauth2 import service_account

        info = json.loads(raw)
        creds = service_account.Credentials.from_service_account_info(
            info, scopes=["https://www.googleapis.com/auth/datastore"]
        )
        _db = firestore.AsyncClient(project=info["project_id"], credentials=creds)
        _enabled = True
        logger.warning("Histórico habilitado (proyecto %s)", info["project_id"])
    except Exception as e:
        logger.error("No se pudo inicializar Firestore: %s", e, exc_info=True)


def is_enabled() -> bool:
    return _enabled


def get_db():
    """Cliente Firestore compartido (o None si el histórico está deshabilitado).
    Lo reutiliza stats.py para volcar métricas sin abrir otra conexión."""
    return _db


# ──────────────────────────────────────────────
# Escritura (fire-and-forget desde el muestreador)
# ──────────────────────────────────────────────
def record_bcv(data: dict) -> None:
    values = {
        k: data.get(src)
        for k, src in (("usd", "bcvUsd"), ("eur", "bcvEur"), ("cny", "bcvCny"),
                       ("try", "bcvTry"), ("rub", "bcvRub"))
        if data.get(src) is not None
    }
    _schedule("BCV", values)


def record_p2p(fiat: str, buy: float | None, sell: float | None) -> None:
    values = {}
    if buy is not None:
        values["buy"] = buy
    if sell is not None:
        values["sell"] = sell
    _schedule(fiat, values)


def _schedule(series: str, values: dict) -> None:
    if not _enabled or not values:
        return
    if _last_values.get(series) == values:
        return  # nada cambió desde la última escritura de este worker
    try:
        asyncio.get_running_loop().create_task(_append(series, values))
    except RuntimeError:
        pass  # sin event loop (tests) — no registrar


async def _append(series: str, values: dict) -> None:
    now = int(time.time())
    month = datetime.fromtimestamp(now, tz=timezone.utc).strftime("%Y-%m")
    doc_id = f"{series}_{month}"
    try:
        doc = _db.collection(COLLECTION).document(doc_id)
        # Dedup robusto contra Firestore: cubre el hueco de _last_values (memoria)
        # tras un reinicio del Space. Si el último valor almacenado este mes es
        # idéntico, NO se escribe — así no se acumulan puntos del mismo monto.
        # Solo se lee aquí (no en el camino común, que ya cortó _schedule en memoria).
        last_stored = await _latest_stored_values(doc)
        if last_stored == values:
            _last_values[series] = values
            return
        # Mapa {bucket: valores} con merge: una sola entrada por franja de 15 min.
        bucket = now // BUCKET_SECONDS * BUCKET_SECONDS
        await doc.set({"points": {str(bucket): values}}, merge=True)
        _last_values[series] = values
        # El doc del mes actual cambió: invalidar su caché de lectura local.
        _read_cache.pop(doc_id, None)
    except Exception as e:
        logger.error("No se pudo registrar histórico %s: %s", series, e)


async def _latest_stored_values(doc) -> dict | None:
    """Valores (sin `t`) del punto más reciente del doc, o None si está vacío."""
    snap = await doc.get()
    if not snap.exists:
        return None
    points = _normalize_points((snap.to_dict() or {}).get("points"))
    if not points:
        return None
    latest = max(points, key=lambda p: p.get("t", 0))
    return {k: v for k, v in latest.items() if k != "t"}


# ──────────────────────────────────────────────
# Lectura
# ──────────────────────────────────────────────
async def get_history(series: str, days: int) -> list[dict]:
    """Puntos de la serie en los últimos `days` días, ordenados por timestamp."""
    if not _enabled:
        return []
    days = max(1, min(days, MAX_DAYS))
    now = datetime.now(tz=timezone.utc)
    cutoff = int((now - timedelta(days=days)).timestamp())

    points: list[dict] = []
    for month in _months_between(now - timedelta(days=days), now):
        points.extend(await _read_month(series, month, is_current=(month == now.strftime("%Y-%m"))))
    return sorted((p for p in points if p.get("t", 0) >= cutoff), key=lambda p: p["t"])


def _months_between(start: datetime, end: datetime) -> list[str]:
    months = []
    cursor = datetime(start.year, start.month, 1, tzinfo=timezone.utc)
    while cursor <= end:
        months.append(cursor.strftime("%Y-%m"))
        cursor = datetime(
            cursor.year + (cursor.month == 12),
            cursor.month % 12 + 1,
            1,
            tzinfo=timezone.utc,
        )
    return months


async def _read_month(series: str, month: str, is_current: bool) -> list[dict]:
    doc_id = f"{series}_{month}"
    ttl = CURRENT_MONTH_TTL if is_current else PAST_MONTH_TTL
    cached = _read_cache.get(doc_id)
    if cached and (time.time() - cached["ts"]) < ttl:
        return cached["points"]

    try:
        snap = await _db.collection(COLLECTION).document(doc_id).get()
        raw = (snap.to_dict() or {}).get("points") if snap.exists else None
        points = _normalize_points(raw)
    except Exception as e:
        logger.error("No se pudo leer histórico %s: %s", doc_id, e)
        # Fallback: servir caché vencido antes que nada.
        return cached["points"] if cached else []

    _read_cache[doc_id] = {"ts": time.time(), "points": points}
    return points


def _normalize_points(raw) -> list[dict]:
    """
    Normaliza el campo `points` a lista de {t, ...}.
    - Formato nuevo: mapa {bucket: {buy, sell}}.
    - Formato viejo (transición): lista [{t, buy, sell}], posiblemente con
      duplicados por el bug de ArrayUnion. Se colapsa por `t` (última gana).
    """
    if isinstance(raw, dict):
        out = []
        for key, val in raw.items():
            if not isinstance(val, dict):
                continue
            try:
                t = int(key)
            except (TypeError, ValueError):
                continue
            out.append({"t": t, **val})
        return out
    if isinstance(raw, list):
        by_t: dict[int, dict] = {}
        for p in raw:
            if isinstance(p, dict) and "t" in p:
                by_t[p["t"]] = p
        return list(by_t.values())
    return []


# ──────────────────────────────────────────────
# Estado BCV: {current, previous} para la "tasa del viernes"
# ──────────────────────────────────────────────
# El fin de semana rige la tasa publicada el viernes (fecha valor "Lunes"); la
# tasa "del viernes" que algunos usuarios prefieren es la publicación INMEDIATA-
# MENTE anterior (fecha valor "Viernes"). Guardamos {current, previous} en un doc
# aparte para servirla sin reconstruirla en el cliente. Se desplaza current->previous
# solo cuando cambia el `updatedAt` (fecha valor) — idempotente entre los 2 workers.
BCV_STATE_COLLECTION = "bcv_state"
BCV_STATE_DOC = "latest"


async def update_bcv_state(current: dict) -> dict | None:
    """Actualiza {current, previous} si el `updatedAt` scrapeado es nuevo.
    Devuelve el `previous` resultante (o None). No tumba el scrape si Firestore falla."""
    if not _enabled:
        return None
    try:
        doc = _db.collection(BCV_STATE_COLLECTION).document(BCV_STATE_DOC)
        snap = await doc.get()
        state = snap.to_dict() if snap.exists else {}
        stored_current = state.get("current") or {}
        # Idempotente: si el worker vecino ya guardó esta misma publicación,
        # no volver a desplazar (previous quedaría corrupto).
        if stored_current.get("updatedAt") == current.get("updatedAt"):
            return state.get("previous")
        previous = stored_current or None
        await doc.set({"current": current, "previous": previous})
        return previous
    except Exception as e:
        logger.error("update_bcv_state falló: %s", e)
        return None


async def get_bcv_previous() -> dict | None:
    """Lee el `previous` (tasa del viernes) del estado BCV, o None."""
    if not _enabled:
        return None
    try:
        snap = await _db.collection(BCV_STATE_COLLECTION).document(BCV_STATE_DOC).get()
        if snap.exists:
            return (snap.to_dict() or {}).get("previous")
    except Exception as e:
        logger.error("get_bcv_previous falló: %s", e)
    return None