understanding commited on
Commit
b0bf7d8
·
verified ·
1 Parent(s): 64e7343

Update bot/integrations/http.py

Browse files
Files changed (1) hide show
  1. bot/integrations/http.py +25 -23
bot/integrations/http.py CHANGED
@@ -4,15 +4,14 @@ from typing import Any, Dict, Optional
4
 
5
  import httpx
6
 
7
- # One global client (HF no persistence, but process lives)
8
  _client: Optional[httpx.AsyncClient] = None
9
 
10
 
11
  def get_client() -> httpx.AsyncClient:
12
  """
13
  Shared HTTP client for Worker calls.
14
- - Retries handled in request_json()
15
- - trust_env=False avoids weird proxy/env issues on HF
16
  """
17
  global _client
18
  if _client is not None:
@@ -56,16 +55,12 @@ async def request_json(
56
  backoff_base: float = 0.6,
57
  ) -> Dict[str, Any]:
58
  """
59
- Standard wrapper used by cf_worker1/cf_worker2.
60
- Returns a dict always:
61
- - on success: parsed JSON dict (or {"ok": True, "raw": "..."} if non-json)
62
- - on error: {"ok": False, "status": <int>, "err": "<msg>"}
63
-
64
- Handles DNS glitches like:
65
- [Errno -5] No address associated with hostname
66
  """
67
  c = get_client()
68
- last_err = None
69
 
70
  for attempt in range(retries):
71
  try:
@@ -77,26 +72,24 @@ async def request_json(
77
  data=data,
78
  )
79
 
80
- # Try parse JSON always
81
  try:
82
  j = r.json()
83
  except Exception:
84
  txt = (r.text or "").strip()
85
- j = {"ok": r.is_success, "raw": txt}
86
 
87
  if r.is_success:
88
- # if API didn't include ok, add it
89
- if isinstance(j, dict) and "ok" not in j:
90
- j["ok"] = True
91
- return j
92
 
93
- # non-2xx -> return error payload
94
  if isinstance(j, dict):
95
- # keep server error if present
96
  j.setdefault("ok", False)
97
  j.setdefault("status", r.status_code)
98
- if "err" not in j:
99
- j["err"] = f"http_{r.status_code}"
100
  return j
101
 
102
  return {"ok": False, "status": r.status_code, "err": f"http_{r.status_code}"}
@@ -109,8 +102,17 @@ async def request_json(
109
  except Exception as e:
110
  last_err = e
111
 
112
- # retry with exponential backoff
113
  if attempt < retries - 1:
114
  await asyncio.sleep(backoff_base * (2 ** attempt))
115
 
116
- return {"ok": False, "status": 0, "err": str(last_err) if last_err else "unknown_error"}
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  import httpx
6
 
7
+ # One global client
8
  _client: Optional[httpx.AsyncClient] = None
9
 
10
 
11
  def get_client() -> httpx.AsyncClient:
12
  """
13
  Shared HTTP client for Worker calls.
14
+ - trust_env=False avoids proxy/env issues on HF
 
15
  """
16
  global _client
17
  if _client is not None:
 
55
  backoff_base: float = 0.6,
56
  ) -> Dict[str, Any]:
57
  """
58
+ Returns dict always:
59
+ - success: JSON dict (adds ok=True if missing)
60
+ - error: {"ok": False, "status": <int>, "err": "<msg>"}
 
 
 
 
61
  """
62
  c = get_client()
63
+ last_err: Optional[BaseException] = None
64
 
65
  for attempt in range(retries):
66
  try:
 
72
  data=data,
73
  )
74
 
75
+ # parse JSON if possible
76
  try:
77
  j = r.json()
78
  except Exception:
79
  txt = (r.text or "").strip()
80
+ j = {"raw": txt}
81
 
82
  if r.is_success:
83
+ if isinstance(j, dict):
84
+ j.setdefault("ok", True)
85
+ return j
86
+ return {"ok": True, "raw": j}
87
 
88
+ # non-2xx
89
  if isinstance(j, dict):
 
90
  j.setdefault("ok", False)
91
  j.setdefault("status", r.status_code)
92
+ j.setdefault("err", f"http_{r.status_code}")
 
93
  return j
94
 
95
  return {"ok": False, "status": r.status_code, "err": f"http_{r.status_code}"}
 
102
  except Exception as e:
103
  last_err = e
104
 
 
105
  if attempt < retries - 1:
106
  await asyncio.sleep(backoff_base * (2 ** attempt))
107
 
108
+ return {"ok": False, "status": 0, "err": str(last_err) if last_err else "unknown_error"}
109
+
110
+
111
+ # ----------------- Backward-compatible helpers -----------------
112
+ # (your old files import these names)
113
+
114
+ async def post_json(url: str, payload: Dict[str, Any], headers: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
115
+ return await request_json("POST", url, headers=headers, json_body=payload)
116
+
117
+ async def get_json(url: str, headers: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
118
+ return await request_json("GET", url, headers=headers)