"""Bridge a FastAPI request into the Gradio request context. This is load-bearing for ZeroGPU quota attribution, not a convenience. ``spaces`` resolves the caller's identity like this:: spaces/zero/wrappers.py request = gradio_request_var().get(None) spaces/utils.py gradio_request_var() -> gradio.context.LocalContext.request spaces/zero/client.py _get_headers(request) -> headers['x-ip-token'] ``LocalContext.request`` is a contextvar that Gradio only populates inside its own event handlers. A FastAPI route that calls a ``@spaces.GPU`` function without setting it hands ZeroGPU ``headers = {}``, which drops the caller's X-IP-Token and silently falls back to IP-based quota — i.e. every API request would bill the wrong identity. ``gradio_request`` sets the contextvar for the duration of the call and resets it afterwards, so v1 requests are attributed exactly like Gradio ones. """ from __future__ import annotations from contextlib import contextmanager import gradio as gr from gradio.context import LocalContext # The header HF's router attaches to identify the end user (spaces/zero/client.py). IP_TOKEN_HEADER = "x-ip-token" @contextmanager def gradio_request(request): """Expose a Starlette request to Gradio/ZeroGPU as a ``gr.Request``. Yields the wrapped request so handlers can pass it on to pipeline entries, which use it for CPU rate-limit identity and client-disconnect detection. """ wrapped = gr.Request(request=request) token = LocalContext.request.set(wrapped) try: yield wrapped finally: LocalContext.request.reset(token) def bind_gradio_request(request): """Set the contextvar for this step only, and return the wrapped request. The streaming routes cannot use ``gradio_request``: Starlette pulls a sync generator one step at a time through the threadpool, each step in its own copy of the context, so a token taken in one step cannot be reset in a later one — ``ContextVar.reset`` raises "created in a different Context". Nothing leaks by not resetting. The copy is discarded when the step ends, so the value lives exactly as long as the step that set it — which is the step that must also start the work, so the pipeline's own context snapshot carries it. """ wrapped = gr.Request(request=request) LocalContext.request.set(wrapped) return wrapped def has_ip_token(request) -> bool: """Whether HF's router attached an identity token to this request.""" return IP_TOKEN_HEADER in {k.lower() for k in request.headers}