Spaces:
Sleeping

axeronis commited on
Commit
6738a3d
·
1 Parent(s): b8370de

Fix: Replace async DNS patching with synchronous requests fallback for HF

Browse files
backend/app/services/telegram_service.py CHANGED
@@ -1,5 +1,6 @@
1
  import httpx
2
- import socket
 
3
  from typing import Optional, Dict, Any, Union
4
  from app.core.config import settings
5
  from app.core.logging import get_logger
@@ -9,7 +10,7 @@ logger = get_logger(__name__)
9
  class TelegramService:
10
  """
11
  Service for interacting with Telegram Bot API.
12
- Includes DNS fallback for Hugging Face Spaces issues.
13
  """
14
 
15
  TELEGRAM_API_IP = "149.154.167.220" # Hardcoded backup IP for api.telegram.org
@@ -18,10 +19,11 @@ class TelegramService:
18
  self.base_url = "https://api.telegram.org/bot"
19
  self.token = settings.TELEGRAM_NOTIFICATION_TOKEN
20
 
21
- async def _make_request(self, method: str, url: str, **kwargs) -> httpx.Response:
22
  """
23
- Wrapper for httpx requests with DNS fallback.
24
- If hostname resolution fails, tries replacing hostname with hardcoded IP.
 
25
  """
26
  try:
27
  async with httpx.AsyncClient(timeout=30.0) as client:
@@ -31,35 +33,48 @@ class TelegramService:
31
  return await client.post(url, **kwargs)
32
  except (httpx.ConnectError, OSError) as e:
33
  if "No address associated with hostname" in str(e) or "[Errno -5]" in str(e):
34
- logger.warning(f"⚠️ DNS failure for {url}. Activating robust DNS patch for HF.")
35
- self._activate_dns_patch()
36
- # Retry with original URL (now that DNS is patched)
37
- async with httpx.AsyncClient(timeout=30.0) as client:
38
- if method.lower() == 'get':
39
- return await client.get(url, **kwargs)
40
- else:
41
- return await client.post(url, **kwargs)
42
  raise e
43
 
44
- def _activate_dns_patch(self):
45
  """
46
- Monkeypatch socket.getaddrinfo to resolve api.telegram.org manually.
47
- This fixes SNI and Host header issues that occur with direct IP URLs.
48
  """
49
- if getattr(socket, "_is_patched_by_microfunnel", False):
50
- return
51
-
52
- logger.info("🔧 Applying DNS monkeypatch for api.telegram.org -> 149.154.167.220")
53
- _orig_getaddrinfo = socket.getaddrinfo
54
-
55
- def _patched_getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
56
- if host == "api.telegram.org":
57
- # Return hardcoded valid Telegram IP
58
- return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (self.TELEGRAM_API_IP, port))]
59
- return _orig_getaddrinfo(host, port, family, type, proto, flags)
60
-
61
- socket.getaddrinfo = _patched_getaddrinfo
62
- socket._is_patched_by_microfunnel = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
  def _get_url(self, token: str, method: str) -> str:
65
  return f"{self.base_url}{token}/{method}"
 
1
  import httpx
2
+ import requests
3
+ import json
4
  from typing import Optional, Dict, Any, Union
5
  from app.core.config import settings
6
  from app.core.logging import get_logger
 
10
  class TelegramService:
11
  """
12
  Service for interacting with Telegram Bot API.
13
+ Includes custom synchronous fallback for HF Spaces DNS issues.
14
  """
15
 
16
  TELEGRAM_API_IP = "149.154.167.220" # Hardcoded backup IP for api.telegram.org
 
19
  self.base_url = "https://api.telegram.org/bot"
20
  self.token = settings.TELEGRAM_NOTIFICATION_TOKEN
21
 
22
+ async def _make_request(self, method: str, url: str, **kwargs) -> Any:
23
  """
24
+ Robust request wrapper.
25
+ 1. Tries standard async httpx request.
26
+ 2. If DNS fails, switches to synchronous 'requests' with direct IP.
27
  """
28
  try:
29
  async with httpx.AsyncClient(timeout=30.0) as client:
 
33
  return await client.post(url, **kwargs)
34
  except (httpx.ConnectError, OSError) as e:
35
  if "No address associated with hostname" in str(e) or "[Errno -5]" in str(e):
36
+ logger.warning(f"⚠️ DNS failure for {url}. Switching to synchronous direct IP fallback.")
37
+ return self._make_request_sync_fallback(method, url, **kwargs)
 
 
 
 
 
 
38
  raise e
39
 
40
+ def _make_request_sync_fallback(self, method: str, url: str, **kwargs) -> Any:
41
  """
42
+ Synchronous fallback using 'requests' library and direct IP.
43
+ Bypasses async/event loop DNS issues completely.
44
  """
45
+ try:
46
+ # Construct direct IP URL
47
+ fallback_url = url.replace("api.telegram.org", self.TELEGRAM_API_IP)
48
+
49
+ # Prepare headers with correct Host
50
+ headers = kwargs.get("headers", {})
51
+ headers["Host"] = "api.telegram.org"
52
+ kwargs["headers"] = headers
53
+
54
+ # Handle JSON/Data arguments adjustment for 'requests'
55
+ # httpx uses 'json', requests uses 'json' (compatible)
56
+ # httpx uses 'data', requests uses 'data' (compatible)
57
+ # httpx uses 'files', requests uses 'files' (compatible)
58
+
59
+ if method.lower() == 'get':
60
+ response = requests.get(fallback_url, verify=False, **kwargs)
61
+ else:
62
+ response = requests.post(fallback_url, verify=False, **kwargs)
63
+
64
+ # Mock an httpx-like response object to keep interface consistent
65
+ class MockResponse:
66
+ def __init__(self, r):
67
+ self.status_code = r.status_code
68
+ self.text = r.text
69
+ self.content = r.content
70
+ def json(self):
71
+ return json.loads(self.text)
72
+
73
+ return MockResponse(response)
74
+
75
+ except Exception as e:
76
+ logger.error(f"❌ Synchronous fallback also failed: {e}")
77
+ raise e
78
 
79
  def _get_url(self, token: str, method: str) -> str:
80
  return f"{self.base_url}{token}/{method}"