Spaces:
Sleeping

File size: 5,583 Bytes
8447fea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
664e057
 
 
 
 
 
 
 
 
 
8447fea
 
 
664e057
 
 
8447fea
 
664e057
8447fea
 
 
 
 
 
 
664e057
 
8447fea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os, time, json, hashlib, contextlib
from typing import List, Optional, AsyncIterator
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import httpx
import redis.asyncio as aioredis
import structlog

structlog.configure(
    processors=[
        structlog.processors.add_log_level,
        structlog.processors.TimeStamper(fmt="iso"),
        structlog.dev.ConsoleRenderer()
    ]
)
logger = structlog.get_logger()

REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379/0")
SEARXNG_URL = os.getenv("SEARXNG_URL", "http://localhost:8080")
CACHE_TTL = int(os.getenv("CACHE_TTL", "7200"))
RATE_LIMIT = int(os.getenv("RATE_LIMIT", "10"))
RATE_WINDOW = int(os.getenv("RATE_WINDOW", "60"))
TIMEOUT = float(os.getenv("TIMEOUT", "10.0"))

@contextlib.asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    global redis_client
    redis_client = aioredis.from_url(REDIS_URL, decode_responses=True)
    await redis_client.ping()
    logger.info("system_started", status="ok")
    yield
    if redis_client:
        await redis_client.aclose()

app = FastAPI(title="Design Search API", version="1.0.0", lifespan=lifespan)
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])

redis_client: Optional[aioredis.Redis] = None

class SearchReq(BaseModel):
    query: str
    limit: int = 5

class Result(BaseModel):
    title: str
    url: str
    snippet: Optional[str] = None

def get_client_ip(request: Request) -> str:
    forwarded = request.headers.get("X-Forwarded-For")
    if forwarded:
        return forwarded.split(",")[0].strip()
    return request.client.host

async def check_rate(ip: str) -> bool:
    key = f"ratelimit:{ip}"
    now = time.time()
    pipe = redis_client.pipeline()
    pipe.zremrangebyscore(key, 0, now - RATE_WINDOW)
    pipe.zadd(key, {str(now): now})
    pipe.zcard(key)
    pipe.expire(key, RATE_WINDOW)
    _, _, count, _ = await pipe.execute()
    return count <= RATE_LIMIT

async def get_cache(query: str) -> Optional[List[Result]]:
    h = hashlib.sha256(query.encode("utf-8")).hexdigest()
    data = await redis_client.get(f"cache:{h}")
    if not data:
        return None
    try:
        items = json.loads(data)
        return [Result(**item) for item in items]
    except Exception:
        return None

async def set_cache(query: str, results: List[Result]):
    h = hashlib.sha256(query.encode("utf-8")).hexdigest()
    payload = [r.model_dump() for r in results]
    await redis_client.setex(f"cache:{h}", CACHE_TTL, json.dumps(payload, ensure_ascii=False))

@app.post("/search", response_model=List[Result])
async def search(req: SearchReq, request: Request):
    ip = get_client_ip(request)
    if not await check_rate(ip):
        raise HTTPException(429, "Rate limit exceeded. Подождите 60 секунд.")

    q = req.query.strip()
    if not q:
        raise HTTPException(400, "Пустой запрос")

    cached = await get_cache(q)
    if cached:
        logger.info("cache_hit", query=q)
        return cached

    params = {
        "q": q,
        "format": "json",
        "language": "ru",
        "categories": "general",
        "limit": req.limit,
    }

    # Ждём готовности SearXNG (до 30 секунд)
    for _ in range(30):
        try:
            async with httpx.AsyncClient(timeout=2.0) as test_client:
                test_resp = await test_client.get(f"{SEARXNG_URL}/healthz")
                if test_resp.status_code == 200:
                    break
        except:
            await asyncio.sleep(1)
    
    async with httpx.AsyncClient(timeout=TIMEOUT) as client:
        try:
            resp = await client.get(f"{SEARXNG_URL}/search", params=params)
            if resp.status_code == 404:
                logger.error("searxng_404", url=f"{SEARXNG_URL}/search", query=q)
                raise HTTPException(502, "Поисковый сервис не настроен (404)")
            if resp.status_code != 200:
                logger.error("search_http_error", status=resp.status_code, query=q)
                raise HTTPException(502, f"Поисковый сервис вернул ошибку {resp.status_code}")
            data = resp.json()
        except httpx.RequestError as e:
            logger.error("search_request_error", error=str(e), query=q)
            raise HTTPException(502, "Поисковый сервис недоступен")
        except ValueError:
            logger.error("search_non_json_response", query=q)
            raise HTTPException(502, "Некорректный ответ от поискового сервиса")
        except HTTPException:
            raise
        except Exception as e:
            logger.error("search_unexpected_error", error=str(e), query=q)
            raise HTTPException(502, "Внутренняя ошибка поиска")

    results = []
    for r in data.get("results", [])[:req.limit]:
        results.append(Result(
            title=(r.get("title") or "Без заголовка").strip(),
            url=(r.get("url") or "").strip(),
            snippet=(r.get("content") or "")[:200].strip()
        ))

    if results:
        await set_cache(q, results)
        logger.info("search_success", results=len(results), query=q)

    return results

@app.get("/health")
def health():
    return {"status": "ok", "version": "1.0.0"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)