File size: 14,632 Bytes
5bd11be 6df3e2a 52d7bab 5bd11be 52d7bab 3973917 5bd11be a6d044b 5bd11be 07a5369 efe271e 5bd11be 89d0143 33e05b5 5bd11be 89d0143 78f1f37 07a5369 78f1f37 07a5369 78f1f37 0b40f25 78f1f37 0b40f25 78f1f37 3973917 78f1f37 52d7bab 07a5369 52d7bab 07a5369 52d7bab 7706a1b 52d7bab 7706a1b 52d7bab 7706a1b 52d7bab 7706a1b 52d7bab 89d0143 5bd11be | 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 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 | """
Queue Server - hosted on Hugging Face Spaces
============================================
Acts as the neutral relay between the public GUI and local mirrors.
Run with:
pip install fastapi uvicorn
uvicorn server:app --host 0.0.0.0 --port 7860
Environment variables:
QUEUE_API_KEY - shared secret for authenticating mirrors and GUI clients
JOB_TTL - seconds before a pending job is considered timed out (default 30)
POLL_INTERVAL - seconds between mirror poll cycles, informational only (default 2)
"""
import asyncio
import os
import time
import logging
from contextlib import asynccontextmanager
from typing import Optional
import json
from fastapi import Request, Response
import asyncio
from fastapi.responses import StreamingResponse
from fastapi import FastAPI, HTTPException, Header, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
# In-memory stream buffers: job_id -> asyncio.Queue
_stream_queues: dict[str, asyncio.Queue] = {}
_stream_lock = asyncio.Lock()
STRIP_HEADERS = {
"content-length",
"content-encoding",
"transfer-encoding",
"connection",
"host",
"x-api-key",
# HuggingFace injected headers
"x-forwarded-for",
"x-forwarded-proto",
"x-forwarded-port",
"x-amzn-trace-id",
"x-direct-url",
"x-ip-token",
"x-request-id",
# General proxy headers
"x-real-ip",
"x-scheme",
"x-envoy-expected-rq-timeout-ms",
}
# ---------------------------------------------------------------------------
# Import shared models (copy shared/models.py next to this file on HF Space)
# ---------------------------------------------------------------------------
from models import APIJob, ClaimRequest, CompleteRequest, JobStatus
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("queue-server")
# ---------------------------------------------------------------------------
# In-memory store. Swap for Redis on Upstash for production persistence.
# ---------------------------------------------------------------------------
_jobs: dict[str, APIJob] = {}
_lock = asyncio.Lock()
API_KEY = os.environ.get("QUEUE_API_KEY", "changeme")
JOB_TTL = 300 #float(os.environ.get("JOB_TTL", 30))
# ---------------------------------------------------------------------------
# Background task: reap timed-out jobs
# ---------------------------------------------------------------------------
async def _reaper():
while True:
await asyncio.sleep(5)
now = time.time()
async with _lock:
for job in list(_jobs.values()):
if job.status in (JobStatus.PENDING, JobStatus.CLAIMED):
age = now - job.created_at
if age > job.ttl:
job.status = JobStatus.TIMEOUT
log.info(f"Job {job.job_id} timed out after {age:.1f}s")
@asynccontextmanager
async def lifespan(app: FastAPI):
task = asyncio.create_task(_reaper())
yield
task.cancel()
app = FastAPI(title="API Proxy Queue", lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Tighten this in production
allow_methods=["*"],
allow_headers=["*"],
)
# ---------------------------------------------------------------------------
# Auth helper
# ---------------------------------------------------------------------------
def _check_auth(x_api_key: Optional[str], authorization: Optional[str] = None):
# Accept via x-api-key or Authorization: Bearer <key>
bearer = None
if authorization and authorization.startswith("Bearer "):
bearer = authorization[7:]
if x_api_key == API_KEY or bearer == API_KEY:
return
#temporary skip auth
return
# raise HTTPException(status_code=401, detail="Invalid API key")
# ---------------------------------------------------------------------------
# Routes: Client-facing (GUI / caller side)
# ---------------------------------------------------------------------------
@app.post("/jobs", response_model=APIJob, summary="Submit a new API job")
async def submit_job(
job_in: APIJob,
x_api_key: Optional[str] = Header(default=None),
):
_check_auth(x_api_key)
job_in.ttl = JOB_TTL
job_in.status = JobStatus.PENDING
async with _lock:
_jobs[job_in.job_id] = job_in
log.info(f"Job {job_in.job_id} submitted: {job_in.method} {job_in.endpoint}")
return job_in
@app.get("/jobs/{job_id}", response_model=APIJob, summary="Poll for a job's result")
async def get_job(
job_id: str,
x_api_key: Optional[str] = Header(default=None),
):
_check_auth(x_api_key)
async with _lock:
job = _jobs.get(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
return job
@app.get("/jobs/{job_id}/wait", response_model=APIJob, summary="Long-poll until job completes or times out")
async def wait_for_job(
job_id: str,
timeout: float = 25.0,
x_api_key: Optional[str] = Header(default=None),
):
"""
Blocks up to `timeout` seconds waiting for the job to complete.
Much more efficient than client-side polling.
"""
_check_auth(x_api_key)
deadline = time.time() + min(timeout, JOB_TTL)
while time.time() < deadline:
async with _lock:
job = _jobs.get(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
if job.status in (JobStatus.COMPLETED, JobStatus.FAILED, JobStatus.TIMEOUT):
return job
await asyncio.sleep(0.3)
# Return current state even if still pending
async with _lock:
return _jobs[job_id]
# ---------------------------------------------------------------------------
# Routes: Mirror-facing
# ---------------------------------------------------------------------------
@app.post("/mirror/claim", response_model=Optional[APIJob], summary="Mirror claims a pending job it can serve")
async def claim_job(
claim: ClaimRequest,
x_api_key: Optional[str] = Header(default=None),
):
"""
The mirror sends its ID and the list of endpoint prefixes it can serve.
The server atomically assigns the first matching pending job.
Returns null if nothing is available.
"""
_check_auth(x_api_key)
now = time.time()
async with _lock:
for job in _jobs.values():
if job.status != JobStatus.PENDING:
continue
# Check TTL
if now - job.created_at > job.ttl:
continue
# Check target mirror constraint
if job.target_mirror and job.target_mirror != claim.mirror_id:
continue
# Check endpoint match
if not any(job.endpoint.startswith(ep) for ep in claim.available_endpoints):
continue
# Atomic claim
job.status = JobStatus.CLAIMED
job.claimed_at = now
log.info(f"Job {job.job_id} claimed by mirror '{claim.mirror_id}'")
return job
return None
@app.post("/mirror/complete", summary="Mirror posts the result of a completed job")
async def complete_job(
result: CompleteRequest,
x_api_key: Optional[str] = Header(default=None),
):
_check_auth(x_api_key)
async with _lock:
job = _jobs.get(result.job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
if job.status != JobStatus.CLAIMED:
raise HTTPException(status_code=409, detail=f"Job is in state '{job.status}', cannot complete")
job.status = JobStatus.FAILED if result.error else JobStatus.COMPLETED
job.completed_at = time.time()
job.response_status_code = result.response_status_code
job.response_headers = result.response_headers
job.response_body = result.response_body
job.error = result.error
log.info(f"Job {result.job_id} completed by mirror '{result.mirror_id}' → {result.response_status_code}")
return {"ok": True}
@app.post("/mirror/poll", response_model=Optional[APIJob], summary="Long-poll: blocks until a job is available")
async def long_poll(
claim: ClaimRequest,
timeout: float = 20.0,
x_api_key: Optional[str] = Header(default=None),
):
"""
Holds the connection open until a matching job appears or timeout expires.
Returns the claimed job immediately when one is available, or null on timeout.
"""
_check_auth(x_api_key)
deadline = time.time() + min(timeout, 250.0)
while time.time() < deadline:
now = time.time()
async with _lock:
for job in _jobs.values():
if job.status != JobStatus.PENDING:
continue
if now - job.created_at > job.ttl:
continue
if job.target_mirror and job.target_mirror != claim.mirror_id:
continue
if not any(job.endpoint.startswith(ep) for ep in claim.available_endpoints):
continue
# Atomic claim
job.status = JobStatus.CLAIMED
job.claimed_at = now
log.info(f"Job {job.job_id} claimed by '{claim.mirror_id}' via long-poll")
return job
await asyncio.sleep(0.3) # small sleep to yield, not a poll interval
return None # timeout, mirror will reconnect immediately
@app.api_route("/proxy/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH"])
async def proxy(
path: str,
request: Request,
x_api_key: Optional[str] = Header(default=None),
authorization: Optional[str] = Header(default=None),
):
"""
Transparent proxy endpoint. Accepts any HTTP call, queues it internally,
waits for a mirror to process it, and returns the result directly.
Caller just does:
requests.post("https://your-space.hf.space/proxy/api/giulia/infer", json=...)
"""
_check_auth(x_api_key, authorization)
# Parse the incoming request into a job
try:
body = await request.json()
except Exception:
body = None
# Strip HF-injected and hop-by-hop headers before storing in the job
clean_headers = {
k: v for k, v in request.headers.items()
if k.lower() not in STRIP_HEADERS
}
job = APIJob(
method=request.method,
endpoint="/" + path,
headers=clean_headers,
query_params=dict(request.query_params),
body=body,
ttl=JOB_TTL,
)
async with _lock:
_jobs[job.job_id] = job
log.info(f"Proxy job {job.job_id}: {job.method} /{path}")
# Wait for mirror to complete it
deadline = time.time() + JOB_TTL
while time.time() < deadline:
async with _lock:
j = _jobs[job.job_id]
if j.status == JobStatus.COMPLETED:
return Response(
content=json.dumps(j.response_body),
status_code=j.response_status_code,
headers={k: v for k, v in j.response_headers.items()
if k.lower() not in STRIP_HEADERS},
media_type="application/json",
)
if j.status in (JobStatus.FAILED, JobStatus.TIMEOUT):
raise HTTPException(
status_code=502,
detail=j.error or "Job timed out waiting for a mirror"
)
await asyncio.sleep(0.3)
raise HTTPException(status_code=504, detail="Gateway timeout")
@app.api_route("/proxy_stream/{path:path}", methods=["GET", "POST"])
async def proxy_stream(
path: str,
request: Request,
x_api_key: Optional[str] = Header(default=None),
authorization: Optional[str] = Header(default=None),
):
_check_auth(x_api_key, authorization)
try:
body = await request.json()
except Exception:
body = None
clean_headers = {
k: v for k, v in request.headers.items()
if k.lower() not in STRIP_HEADERS
}
job = APIJob(
method=request.method,
endpoint="/" + path,
headers=clean_headers,
query_params=dict(request.query_params),
body=body,
ttl=JOB_TTL,
)
queue = asyncio.Queue()
async with _lock:
_jobs[job.job_id] = job
async with _stream_lock:
_stream_queues[job.job_id] = queue
log.info(f"Stream proxy job {job.job_id}: {job.method} /{path}")
async def event_generator():
try:
while True:
try:
chunk = await asyncio.wait_for(queue.get(), timeout=JOB_TTL)
except asyncio.TimeoutError:
break
if chunk is None: # sentinel: stream done
break
yield chunk
finally:
async with _stream_lock:
_stream_queues.pop(job.job_id, None)
return StreamingResponse(
event_generator(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
"Connection": "keep-alive",
},
)
@app.post("/mirror/stream_chunk", summary="Mirror pushes an SSE chunk")
async def stream_chunk(
request: Request,
job_id: str,
x_api_key: Optional[str] = Header(default=None),
):
_check_auth(x_api_key)
chunk = (await request.body()).decode()
async with _stream_lock:
queue = _stream_queues.get(job_id)
if not queue:
raise HTTPException(status_code=404, detail="No active stream for this job")
await queue.put(chunk)
return {"ok": True}
@app.post("/mirror/stream_end", summary="Mirror signals stream is complete")
async def stream_end(
job_id: str,
x_api_key: Optional[str] = Header(default=None),
):
_check_auth(x_api_key)
async with _stream_lock:
queue = _stream_queues.get(job_id)
if queue:
await queue.put(None) # sentinel
return {"ok": True}
# ---------------------------------------------------------------------------
# Debug / health
# ---------------------------------------------------------------------------
@app.get("/health")
async def health():
async with _lock:
counts = {s.value: 0 for s in JobStatus}
for job in _jobs.values():
counts[job.status.value] += 1
return {"status": "ok", "jobs": counts}
@app.get("/jobs", summary="List all jobs (debug)")
async def list_jobs(
x_api_key: Optional[str] = Header(default=None),
):
_check_auth(x_api_key)
async with _lock:
return list(_jobs.values())
|