Spaces:
Running

andervier commited on
Commit
959e4bb
Β·
1 Parent(s): 74a336b

perf: persistent httpx client, asyncio locks, orjson, uvloop, 2 workers

Browse files
Files changed (3) hide show
  1. Dockerfile +1 -1
  2. main.py +180 -139
  3. requirements.txt +2 -0
Dockerfile CHANGED
@@ -11,4 +11,4 @@ COPY main.py .
11
 
12
  EXPOSE 7860
13
 
14
- CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
 
11
 
12
  EXPOSE 7860
13
 
14
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "2", "--loop", "uvloop", "--log-level", "warning"]
main.py CHANGED
@@ -1,5 +1,7 @@
 
1
  from fastapi import FastAPI, Depends, HTTPException, Header
2
  from fastapi.middleware.cors import CORSMiddleware
 
3
  from bs4 import BeautifulSoup
4
  import httpx
5
  import asyncio
@@ -10,10 +12,62 @@ import logging
10
  import os
11
  from jwt import PyJWKClient
12
 
13
- logging.basicConfig(level=logging.INFO)
14
  logger = logging.getLogger(__name__)
15
 
16
- app = FastAPI(title="Tazas API", version="1.0.0")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  app.add_middleware(
19
  CORSMiddleware,
@@ -54,24 +108,8 @@ def verify_app_check(x_firebase_appcheck: str = Header(None)):
54
 
55
 
56
  # ──────────────────────────────────────────────
57
- # Cache simple en memoria
58
  # ──────────────────────────────────────────────
59
- _cache: dict = {}
60
- BCV_TTL = 60 * 60 * 4 # 4 horas (BCV actualiza una vez al dΓ­a)
61
- P2P_TTL = 60 * 20 # 20 minutos
62
-
63
-
64
- def _cached(key: str, ttl: int):
65
- entry = _cache.get(key)
66
- if entry and (time.time() - entry["ts"]) < ttl:
67
- return entry["data"]
68
- return None
69
-
70
-
71
- def _store(key: str, data: dict):
72
- _cache[key] = {"ts": time.time(), "data": data}
73
-
74
-
75
  def _parse_bcv_rate(text: str) -> float | None:
76
  """Convierte '36,85' o '36.853,12' a float."""
77
  cleaned = text.strip().replace("Bs.", "").replace("S", "").strip()
@@ -91,42 +129,47 @@ async def fetch_bcv() -> dict:
91
  if cached:
92
  return cached
93
 
94
- headers = {
95
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
96
- "Accept-Language": "es-VE,es;q=0.9",
97
- }
 
98
 
99
- # verify=False porque bcv.org.ve tiene cadena de certificados incompleta (problema del BCV)
100
- async with httpx.AsyncClient(timeout=15, follow_redirects=True, verify=False) as client:
101
- response = await client.get("https://www.bcv.org.ve/", headers=headers)
102
- response.raise_for_status()
103
 
104
- soup = BeautifulSoup(response.text, "lxml")
 
 
105
 
106
- currency_ids = {
107
- "Usd": "dolar",
108
- "Eur": "euro",
109
- "Cny": "yuan",
110
- "Try": "lira",
111
- "Rub": "rublo",
112
- }
113
 
114
- rates = {}
115
- for suffix, div_id in currency_ids.items():
116
- div = soup.find(id=div_id)
117
- tag = div.find("strong") if div else None
118
- rates[f"bcv{suffix}"] = _parse_bcv_rate(tag.text) if tag else None
 
 
119
 
120
- if all(v is None for v in rates.values()):
121
- logger.error("BCV: all rates are None β€” scraping failed")
122
- raise HTTPException(status_code=503, detail="No se pudo obtener las tasas BCV")
 
 
123
 
124
- updated_tag = soup.find("span", {"class": re.compile(r"date-display")})
125
- updated_at = updated_tag.text.strip() if updated_tag else None
 
126
 
127
- data = {**rates, "updatedAt": updated_at}
128
- _store("bcv", data)
129
- return data
 
 
 
130
 
131
 
132
  async def fetch_p2p() -> dict:
@@ -134,100 +177,107 @@ async def fetch_p2p() -> dict:
134
  if cached:
135
  return cached
136
 
137
- headers = {
138
- "User-Agent": "Mozilla/5.0",
139
- "Content-Type": "application/json",
140
- }
141
- body_base = {
142
- "fiat": "VES",
143
- "page": 1,
144
- "rows": 20,
145
- "asset": "USDT",
146
- "countries": [],
147
- "proMerchantAds": False,
148
- "shieldMerchantAds": False,
149
- "publisherType": None,
150
- "payTypes": [],
151
- "classifies": ["mass", "profession"],
152
- }
 
 
 
 
 
 
153
 
154
- async with httpx.AsyncClient(timeout=10) as client:
155
  # BUY = compradores de USDT (tab "Vender" en Binance, ordenado de mayor a menor)
156
  # SELL = vendedores de USDT (tab "Comprar" en Binance, ordenado de menor a mayor)
157
  buy_ads_res, sell_ads_res = await asyncio.gather(
158
- client.post(
159
  "https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search",
160
  json={**body_base, "tradeType": "BUY"},
161
  headers=headers,
162
  ),
163
- client.post(
164
  "https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search",
165
  json={**body_base, "tradeType": "SELL"},
166
  headers=headers,
167
  ),
168
  )
169
- buy_ads_res.raise_for_status()
170
- sell_ads_res.raise_for_status()
171
-
172
- def first_eligible_price(ads: list) -> float | None:
173
- """
174
- 1. Promedia los precios de los anuncios 2, 3 y 4 (Γ­ndices 1-3) como referencia.
175
- 2. fiat_ref = promedio * 20 (~20 USDT en VES).
176
- 3. Devuelve el primer anuncio donde minSingleTransAmount <= fiat_ref <= maxSingleTransAmount,
177
- es decir, uno que realmente acepte esa transacciΓ³n.
178
- Fallback: primer anuncio desde Γ­ndice 1 con min <= fiat_ref (sin chequeo de max).
179
- """
180
- if not ads:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
  return None
182
 
183
- # Paso 1: promedio de ads[3..5] (saltamos los primeros 3)
184
- sample = []
185
- for item in ads[3:6]:
186
- try:
187
- sample.append(float(item["adv"]["price"]))
188
- except (KeyError, ValueError, TypeError):
189
- pass
190
-
191
- if not sample:
192
- return None
193
 
194
- avg_price = sum(sample) / len(sample)
195
- fiat_ref = avg_price * 20 # ~20 USDT en VES
196
-
197
- # Paso 2: primer anuncio que acepte la transacciΓ³n (min <= fiat_ref <= max)
198
- for item in ads:
199
- adv = item.get("adv", {})
200
- try:
201
- price = float(adv["price"])
202
- surplus = float(adv.get("surplusAmount", 0))
203
- min_fiat = float(adv.get("minSingleTransAmount", 0))
204
- max_fiat = float(adv.get("maxSingleTransAmount", float("inf")))
205
- if surplus > 0 and min_fiat <= fiat_ref <= max_fiat:
206
- return price
207
- except (KeyError, ValueError, TypeError):
208
- continue
209
-
210
- # Fallback: primer anuncio desde Γ­ndice 3 con min <= fiat_ref
211
- for item in ads[3:]:
212
- adv = item.get("adv", {})
213
- try:
214
- price = float(adv["price"])
215
- surplus = float(adv.get("surplusAmount", 0))
216
- min_fiat = float(adv.get("minSingleTransAmount", 0))
217
- if surplus > 0 and min_fiat <= fiat_ref:
218
- return price
219
- except (KeyError, ValueError, TypeError):
220
- continue
221
- return None
222
 
223
- # Compra: vendedores de USDT (SELL ads), primer precio = el mΓ‘s barato disponible
224
- p2p_buy = first_eligible_price(sell_ads_res.json().get("data", []))
225
- # Venta: compradores de USDT (BUY ads), primer precio = el mΓ‘s alto disponible
226
- p2p_sell = first_eligible_price(buy_ads_res.json().get("data", []))
227
 
228
- data = {"p2pBuyMax": p2p_buy, "p2pSellMax": p2p_sell}
229
- _store("p2p", data)
230
- return data
 
 
 
231
 
232
 
233
  # ──────────────────────────────────────────────
@@ -252,14 +302,6 @@ async def bcv():
252
  return await fetch_bcv()
253
 
254
 
255
- async def fetch_p2p_safe() -> dict:
256
- try:
257
- return await fetch_p2p()
258
- except Exception as e:
259
- logger.error("fetch_p2p failed: %s", e, exc_info=True)
260
- return {"p2pBuyMax": None, "p2pSellMax": None}
261
-
262
-
263
  @app.get("/v1/p2p", dependencies=[Depends(verify_app_check)])
264
  async def p2p():
265
  return await fetch_p2p()
@@ -275,13 +317,12 @@ async def p2p_debug():
275
  "publisherType": None, "payTypes": [],
276
  "classifies": ["mass", "profession"],
277
  }
278
- async with httpx.AsyncClient(timeout=10) as client:
279
- buy_res, sell_res = await asyncio.gather(
280
- client.post("https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search",
281
- json={**body_base, "tradeType": "BUY"}, headers=headers),
282
- client.post("https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search",
283
- json={**body_base, "tradeType": "SELL"}, headers=headers),
284
- )
285
 
286
  def extract(ads):
287
  return [
 
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
6
  import httpx
7
  import asyncio
 
12
  import os
13
  from jwt import PyJWKClient
14
 
15
+ logging.basicConfig(level=logging.WARNING)
16
  logger = logging.getLogger(__name__)
17
 
18
+ # ──────────────────────────────────────────────
19
+ # Cache + locks anti-thundering-herd
20
+ # ──────────────────────────────────────────────
21
+ _cache: dict = {}
22
+ BCV_TTL = 60 * 60 * 4 # 4 horas (BCV actualiza una vez al dΓ­a)
23
+ P2P_TTL = 60 * 20 # 20 minutos
24
+
25
+ # Un Lock por clave: si el cachΓ© vence y llegan 1000 requests simultΓ‘neas,
26
+ # solo la primera hace el fetch β€” las demΓ‘s esperan y consumen el cachΓ©.
27
+ _locks: dict[str, asyncio.Lock] = {}
28
+
29
+
30
+ def _lock(key: str) -> asyncio.Lock:
31
+ if key not in _locks:
32
+ _locks[key] = asyncio.Lock()
33
+ return _locks[key]
34
+
35
+
36
+ def _cached(key: str, ttl: int):
37
+ entry = _cache.get(key)
38
+ if entry and (time.time() - entry["ts"]) < ttl:
39
+ return entry["data"]
40
+ return None
41
+
42
+
43
+ def _store(key: str, data: dict):
44
+ _cache[key] = {"ts": time.time(), "data": data}
45
+
46
+
47
+ # ──────────────────────────────────────────────
48
+ # Clientes HTTP persistentes (reutilizan conexiones TCP/TLS)
49
+ # ──────────────────────────────────────────────
50
+ _http: httpx.AsyncClient | None = None # Binance / general
51
+ _http_nv: httpx.AsyncClient | None = None # BCV (verify=False β€” cert roto del BCV)
52
+
53
+
54
+ @asynccontextmanager
55
+ async def lifespan(app: FastAPI):
56
+ global _http, _http_nv
57
+ limits = httpx.Limits(max_connections=10, max_keepalive_connections=5)
58
+ _http = httpx.AsyncClient(timeout=10, limits=limits)
59
+ _http_nv = httpx.AsyncClient(timeout=15, follow_redirects=True, verify=False, limits=limits)
60
+ yield
61
+ await _http.aclose()
62
+ await _http_nv.aclose()
63
+
64
+
65
+ app = FastAPI(
66
+ title="Tazas API",
67
+ version="1.0.0",
68
+ lifespan=lifespan,
69
+ default_response_class=ORJSONResponse, # orjson: serializaciΓ³n JSON en C (5-10x mΓ‘s rΓ‘pido)
70
+ )
71
 
72
  app.add_middleware(
73
  CORSMiddleware,
 
108
 
109
 
110
  # ──────────────────────────────────────────────
111
+ # Helpers
112
  # ──────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  def _parse_bcv_rate(text: str) -> float | None:
114
  """Convierte '36,85' o '36.853,12' a float."""
115
  cleaned = text.strip().replace("Bs.", "").replace("S", "").strip()
 
129
  if cached:
130
  return cached
131
 
132
+ async with _lock("bcv"):
133
+ # Double-check: mientras esperΓ‘bamos el lock, otro ya pudo haber refrescado
134
+ cached = _cached("bcv", BCV_TTL)
135
+ if cached:
136
+ return cached
137
 
138
+ headers = {
139
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
140
+ "Accept-Language": "es-VE,es;q=0.9",
141
+ }
142
 
143
+ # verify=False porque bcv.org.ve tiene cadena de certificados incompleta (problema del BCV)
144
+ response = await _http_nv.get("https://www.bcv.org.ve/", headers=headers)
145
+ response.raise_for_status()
146
 
147
+ soup = BeautifulSoup(response.text, "lxml")
 
 
 
 
 
 
148
 
149
+ currency_ids = {
150
+ "Usd": "dolar",
151
+ "Eur": "euro",
152
+ "Cny": "yuan",
153
+ "Try": "lira",
154
+ "Rub": "rublo",
155
+ }
156
 
157
+ rates = {}
158
+ for suffix, div_id in currency_ids.items():
159
+ div = soup.find(id=div_id)
160
+ tag = div.find("strong") if div else None
161
+ rates[f"bcv{suffix}"] = _parse_bcv_rate(tag.text) if tag else None
162
 
163
+ if all(v is None for v in rates.values()):
164
+ logger.error("BCV: all rates are None β€” scraping failed")
165
+ raise HTTPException(status_code=503, detail="No se pudo obtener las tasas BCV")
166
 
167
+ updated_tag = soup.find("span", {"class": re.compile(r"date-display")})
168
+ updated_at = updated_tag.text.strip() if updated_tag else None
169
+
170
+ data = {**rates, "updatedAt": updated_at}
171
+ _store("bcv", data)
172
+ return data
173
 
174
 
175
  async def fetch_p2p() -> dict:
 
177
  if cached:
178
  return cached
179
 
180
+ async with _lock("p2p"):
181
+ # Double-check: mientras esperΓ‘bamos el lock, otro ya pudo haber refrescado
182
+ cached = _cached("p2p", P2P_TTL)
183
+ if cached:
184
+ return cached
185
+
186
+ headers = {
187
+ "User-Agent": "Mozilla/5.0",
188
+ "Content-Type": "application/json",
189
+ }
190
+ body_base = {
191
+ "fiat": "VES",
192
+ "page": 1,
193
+ "rows": 10,
194
+ "asset": "USDT",
195
+ "countries": [],
196
+ "proMerchantAds": False,
197
+ "shieldMerchantAds": False,
198
+ "publisherType": None,
199
+ "payTypes": [],
200
+ "classifies": ["mass", "profession"],
201
+ }
202
 
 
203
  # BUY = compradores de USDT (tab "Vender" en Binance, ordenado de mayor a menor)
204
  # SELL = vendedores de USDT (tab "Comprar" en Binance, ordenado de menor a mayor)
205
  buy_ads_res, sell_ads_res = await asyncio.gather(
206
+ _http.post(
207
  "https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search",
208
  json={**body_base, "tradeType": "BUY"},
209
  headers=headers,
210
  ),
211
+ _http.post(
212
  "https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search",
213
  json={**body_base, "tradeType": "SELL"},
214
  headers=headers,
215
  ),
216
  )
217
+ buy_ads_res.raise_for_status()
218
+ sell_ads_res.raise_for_status()
219
+
220
+ def first_eligible_price(ads: list) -> float | None:
221
+ """
222
+ 1. Salta los primeros 3 anuncios y promedia precios de ads[3..5] como referencia.
223
+ 2. fiat_ref = promedio * 20 (~20 USDT en VES).
224
+ 3. Devuelve el primer anuncio donde minSingleTransAmount <= fiat_ref <= maxSingleTransAmount.
225
+ Fallback: primer anuncio desde Γ­ndice 3 con min <= fiat_ref (sin chequeo de max).
226
+ """
227
+ if not ads:
228
+ return None
229
+
230
+ sample = []
231
+ for item in ads[3:6]:
232
+ try:
233
+ sample.append(float(item["adv"]["price"]))
234
+ except (KeyError, ValueError, TypeError):
235
+ pass
236
+
237
+ if not sample:
238
+ return None
239
+
240
+ avg_price = sum(sample) / len(sample)
241
+ fiat_ref = avg_price * 20 # ~20 USDT en VES
242
+
243
+ for item in ads:
244
+ adv = item.get("adv", {})
245
+ try:
246
+ price = float(adv["price"])
247
+ surplus = float(adv.get("surplusAmount", 0))
248
+ min_fiat = float(adv.get("minSingleTransAmount", 0))
249
+ max_fiat = float(adv.get("maxSingleTransAmount", float("inf")))
250
+ if surplus > 0 and min_fiat <= fiat_ref <= max_fiat:
251
+ return price
252
+ except (KeyError, ValueError, TypeError):
253
+ continue
254
+
255
+ for item in ads[3:]:
256
+ adv = item.get("adv", {})
257
+ try:
258
+ price = float(adv["price"])
259
+ surplus = float(adv.get("surplusAmount", 0))
260
+ min_fiat = float(adv.get("minSingleTransAmount", 0))
261
+ if surplus > 0 and min_fiat <= fiat_ref:
262
+ return price
263
+ except (KeyError, ValueError, TypeError):
264
+ continue
265
  return None
266
 
267
+ p2p_buy = first_eligible_price(sell_ads_res.json().get("data", []))
268
+ p2p_sell = first_eligible_price(buy_ads_res.json().get("data", []))
 
 
 
 
 
 
 
 
269
 
270
+ data = {"p2pBuyMax": p2p_buy, "p2pSellMax": p2p_sell}
271
+ _store("p2p", data)
272
+ return data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273
 
 
 
 
 
274
 
275
+ async def fetch_p2p_safe() -> dict:
276
+ try:
277
+ return await fetch_p2p()
278
+ except Exception as e:
279
+ logger.error("fetch_p2p failed: %s", e, exc_info=True)
280
+ return {"p2pBuyMax": None, "p2pSellMax": None}
281
 
282
 
283
  # ──────────────────────────────────────────────
 
302
  return await fetch_bcv()
303
 
304
 
 
 
 
 
 
 
 
 
305
  @app.get("/v1/p2p", dependencies=[Depends(verify_app_check)])
306
  async def p2p():
307
  return await fetch_p2p()
 
317
  "publisherType": None, "payTypes": [],
318
  "classifies": ["mass", "profession"],
319
  }
320
+ buy_res, sell_res = await asyncio.gather(
321
+ _http.post("https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search",
322
+ json={**body_base, "tradeType": "BUY"}, headers=headers),
323
+ _http.post("https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search",
324
+ json={**body_base, "tradeType": "SELL"}, headers=headers),
325
+ )
 
326
 
327
  def extract(ads):
328
  return [
requirements.txt CHANGED
@@ -4,3 +4,5 @@ httpx==0.28.1
4
  PyJWT[crypto]==2.10.1
5
  beautifulsoup4==4.12.3
6
  lxml==5.3.0
 
 
 
4
  PyJWT[crypto]==2.10.1
5
  beautifulsoup4==4.12.3
6
  lxml==5.3.0
7
+ uvloop==0.21.0
8
+ orjson==3.10.15