Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,65 +1,26 @@
|
|
| 1 |
import os
|
| 2 |
import logging
|
| 3 |
-
import
|
| 4 |
-
from fastapi import FastAPI, Request, Response, HTTPException, BackgroundTasks
|
| 5 |
import httpx
|
| 6 |
import uvicorn
|
| 7 |
-
from contextlib import asynccontextmanager
|
| 8 |
|
| 9 |
-
# --- SETUP ---
|
| 10 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
| 11 |
logger = logging.getLogger(__name__)
|
| 12 |
|
| 13 |
-
|
| 14 |
-
SELF_URL = f"https://{SPACE_HOST}" if SPACE_HOST else "http://localhost:7860"
|
| 15 |
|
| 16 |
-
|
| 17 |
-
"""Фоновий таск, який пінгує простір, але з ЖОРСТКИМ інтервалом, щоб уникнути DDOS-петлі"""
|
| 18 |
-
# Даємо серверу 30 секунд на повний запуск
|
| 19 |
-
await asyncio.sleep(30)
|
| 20 |
-
|
| 21 |
-
async with httpx.AsyncClient() as client:
|
| 22 |
-
while True:
|
| 23 |
-
try:
|
| 24 |
-
logger.info(f"⏰ Sending Scheduled Keep-Alive Ping to: {SELF_URL}/")
|
| 25 |
-
response = await client.get(f"{SELF_URL}/", timeout=15.0)
|
| 26 |
-
logger.info(f"✅ Self-ping response status: {response.status_code}")
|
| 27 |
-
|
| 28 |
-
# Якщо зловили ліміт від Hugging Face, залягаємо на дно на 15 хвилин
|
| 29 |
-
if response.status_code == 429:
|
| 30 |
-
logger.warning("⚠️ Hit HF Rate Limit (429). Backing off for 15 minutes...")
|
| 31 |
-
await asyncio.sleep(900)
|
| 32 |
-
continue
|
| 33 |
-
|
| 34 |
-
except Exception as e:
|
| 35 |
-
logger.warning(f"⚠️ Self-ping network error: {e}")
|
| 36 |
-
|
| 37 |
-
# Завжди спимо 25 хвилин (1500 секунд) ПІСЛЯ завершення спроби запиту.
|
| 38 |
-
# Це повністю ламає нескінченну спам-петлю.
|
| 39 |
-
logger.info("💤 Ping task sleeping for 25 minutes...")
|
| 40 |
-
await asyncio.sleep(1500)
|
| 41 |
-
|
| 42 |
-
@asynccontextmanager
|
| 43 |
-
async def lifespan(app: FastAPI):
|
| 44 |
-
"""Керування життєвим циклом програми: запускає пінгер при стартрі"""
|
| 45 |
-
ping_task = asyncio.create_task(self_pinger())
|
| 46 |
-
yield
|
| 47 |
-
ping_task.cancel()
|
| 48 |
-
|
| 49 |
-
# Передаємо фіксований lifespan у FastAPI
|
| 50 |
-
app = FastAPI(lifespan=lifespan)
|
| 51 |
-
|
| 52 |
-
# Читаємо налаштування з Secrets твого публічного Спейсу
|
| 53 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 54 |
TARGET_SPACE_URL = os.getenv("TARGET_SPACE_URL")
|
| 55 |
|
| 56 |
async def forward_to_private_space(payload: dict, headers: dict):
|
| 57 |
-
"""Асинхронний
|
| 58 |
if not TARGET_SPACE_URL:
|
| 59 |
-
logger.error("❌ TARGET_SPACE_URL environment variable is missing!")
|
| 60 |
return
|
| 61 |
|
| 62 |
-
# Динамічно збираємо
|
| 63 |
base_url = TARGET_SPACE_URL.rstrip("/")
|
| 64 |
if not base_url.endswith("/api/v1/email-webhook"):
|
| 65 |
final_url = f"{base_url}/api/v1/email-webhook"
|
|
@@ -68,25 +29,28 @@ async def forward_to_private_space(payload: dict, headers: dict):
|
|
| 68 |
|
| 69 |
async with httpx.AsyncClient() as client:
|
| 70 |
try:
|
| 71 |
-
logger.info(f"🚀 Forwarding
|
|
|
|
| 72 |
response = await client.post(final_url, json=payload, headers=headers, timeout=60.0)
|
| 73 |
logger.info(f"📥 Private Space responded with status: {response.status_code}")
|
| 74 |
|
| 75 |
if response.status_code == 429:
|
| 76 |
-
logger.error("❌ Private space returned 429.
|
|
|
|
|
|
|
| 77 |
except httpx.RequestError as exc:
|
| 78 |
-
logger.error(f"❌
|
| 79 |
|
| 80 |
@app.get("/")
|
| 81 |
async def root():
|
| 82 |
-
return {"status": "online", "message": "
|
| 83 |
|
| 84 |
@app.post("/listener")
|
| 85 |
@app.post("/listener/")
|
| 86 |
@app.post("/api/v1/email-webhook")
|
| 87 |
async def email_webhook_bridge(request: Request, bg: BackgroundTasks):
|
| 88 |
if not TARGET_SPACE_URL or not HF_TOKEN:
|
| 89 |
-
logger.error("Bridge configuration missing: Check HF_TOKEN and TARGET_SPACE_URL
|
| 90 |
raise HTTPException(status_code=500, detail="Bridge configuration missing.")
|
| 91 |
|
| 92 |
try:
|
|
@@ -94,13 +58,15 @@ async def email_webhook_bridge(request: Request, bg: BackgroundTasks):
|
|
| 94 |
except Exception:
|
| 95 |
raise HTTPException(status_code=400, detail="Invalid JSON payload")
|
| 96 |
|
|
|
|
| 97 |
headers = {
|
| 98 |
"Authorization": f"Bearer {HF_TOKEN}",
|
| 99 |
"Content-Type": "application/json"
|
| 100 |
}
|
| 101 |
|
|
|
|
| 102 |
bg.add_task(forward_to_private_space, payload, headers)
|
| 103 |
-
return {"status": "accepted", "message": "Webhook
|
| 104 |
|
| 105 |
if __name__ == "__main__":
|
| 106 |
port = int(os.environ.get("PORT", 7860))
|
|
|
|
| 1 |
import os
|
| 2 |
import logging
|
| 3 |
+
from fastapi import FastAPI, Request, HTTPException, BackgroundTasks
|
|
|
|
| 4 |
import httpx
|
| 5 |
import uvicorn
|
|
|
|
| 6 |
|
| 7 |
+
# --- SETUP LOGGING ---
|
| 8 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
| 9 |
logger = logging.getLogger(__name__)
|
| 10 |
|
| 11 |
+
app = FastAPI()
|
|
|
|
| 12 |
|
| 13 |
+
# Читаємо змінні з Secrets твого публічного простору Hugging Face
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 15 |
TARGET_SPACE_URL = os.getenv("TARGET_SPACE_URL")
|
| 16 |
|
| 17 |
async def forward_to_private_space(payload: dict, headers: dict):
|
| 18 |
+
"""Асинхронний таск для пересилання даних на приватний бекенд"""
|
| 19 |
if not TARGET_SPACE_URL:
|
| 20 |
+
logger.error("❌ TARGET_SPACE_URL environment variable is missing in Secrets!")
|
| 21 |
return
|
| 22 |
|
| 23 |
+
# Динамічно збираємо чистий урл до приватного ендпоінту
|
| 24 |
base_url = TARGET_SPACE_URL.rstrip("/")
|
| 25 |
if not base_url.endswith("/api/v1/email-webhook"):
|
| 26 |
final_url = f"{base_url}/api/v1/email-webhook"
|
|
|
|
| 29 |
|
| 30 |
async with httpx.AsyncClient() as client:
|
| 31 |
try:
|
| 32 |
+
logger.info(f"🚀 Forwarding payload to private Space: {final_url}")
|
| 33 |
+
# Шлемо запит із токеном авторизації
|
| 34 |
response = await client.post(final_url, json=payload, headers=headers, timeout=60.0)
|
| 35 |
logger.info(f"📥 Private Space responded with status: {response.status_code}")
|
| 36 |
|
| 37 |
if response.status_code == 429:
|
| 38 |
+
logger.error("❌ Private space returned 429. HF still rate-limits this IP or Token is invalid.")
|
| 39 |
+
elif response.status_code == 200:
|
| 40 |
+
logger.info("✅ Successfully delivered to private core!")
|
| 41 |
except httpx.RequestError as exc:
|
| 42 |
+
logger.error(f"❌ Network error while forwarding to private Space: {exc}")
|
| 43 |
|
| 44 |
@app.get("/")
|
| 45 |
async def root():
|
| 46 |
+
return {"status": "online", "message": "Public Webhook Bridge is active (No-ping mode)"}
|
| 47 |
|
| 48 |
@app.post("/listener")
|
| 49 |
@app.post("/listener/")
|
| 50 |
@app.post("/api/v1/email-webhook")
|
| 51 |
async def email_webhook_bridge(request: Request, bg: BackgroundTasks):
|
| 52 |
if not TARGET_SPACE_URL or not HF_TOKEN:
|
| 53 |
+
logger.error("❌ Bridge configuration missing: Check HF_TOKEN and TARGET_SPACE_URL in Secrets.")
|
| 54 |
raise HTTPException(status_code=500, detail="Bridge configuration missing.")
|
| 55 |
|
| 56 |
try:
|
|
|
|
| 58 |
except Exception:
|
| 59 |
raise HTTPException(status_code=400, detail="Invalid JSON payload")
|
| 60 |
|
| 61 |
+
# Формуємо заголовки для проходження крізь приватний проксі Hugging Face
|
| 62 |
headers = {
|
| 63 |
"Authorization": f"Bearer {HF_TOKEN}",
|
| 64 |
"Content-Type": "application/json"
|
| 65 |
}
|
| 66 |
|
| 67 |
+
# Закидуємо в бекграунд, щоб миттєво відповісти серверам Resend (200 OK)
|
| 68 |
bg.add_task(forward_to_private_space, payload, headers)
|
| 69 |
+
return {"status": "accepted", "message": "Webhook queued."}
|
| 70 |
|
| 71 |
if __name__ == "__main__":
|
| 72 |
port = int(os.environ.get("PORT", 7860))
|