Skip to content

Commit

Permalink
Discard a request if the caller already left
Browse files Browse the repository at this point in the history
No need to perform some inference that won't be fetched anyway

Signed-off-by: Raphael Glon <oOraph@users.noreply.github.com>
  • Loading branch information
oOraph committed Aug 27, 2024
1 parent 7f7255a commit 5b9fd98
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions api_inference_community/routes.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import base64
import io
import ipaddress
import logging
import os
import time
from typing import Any, Dict

import psutil
from api_inference_community.validation import (
AUDIO,
AUDIO_INPUTS,
Expand All @@ -27,8 +29,65 @@
logger = logging.getLogger(__name__)


async def already_left(request: Request) -> bool:
"""
Check if the caller has already left without waiting for the answer to come. This can help during burst to relieve
the pressure on the worker by cancelling jobs whose results don't matter as they won't be fetched anyway
:param request:
:return: bool
"""
# NOTE(rg): Starlette method request.is_disconnected is totally broken, consumes the payload, does not return
# the correct status. So we use the good old way to identify if the caller is still there.
# In any case, if we are not sure, we return False
logger.info("Checking if request caller already left")
try:
client = request.client
host = client.host
if not host:
return False

port = int(client.port)
host = ipaddress.ip_address(host)

if port <= 0 or port > 65535:
logger.warning("Unexpected source port format for caller %s", port)
return False

for connection in psutil.net_connections(kind="tcp"):
if connection.status != "ESTABLISHED":
continue
if not connection.laddr:
continue
if int(connection.laddr.port) != port:
continue
if (
not connection.laddr.ip
or ipaddress.ip_address(connection.laddr.ip) != host
):
continue
logger.info(
"Found caller connection still established, caller is most likely still there, %s",
connection,
)
return False
except Exception as e:
logger.warning(
"Unexpected error while checking if caller already left, assuming still there"
)
logger.exception(e)
return False

logger.info("No connection found matching to the caller, probably left")
return True


async def pipeline_route(request: Request) -> Response:
start = time.time()

if already_left(request):
logger.info("Discarding request as the caller already left")
return Response(status_code=204)

payload = await request.body()
task = os.environ["TASK"]
if os.getenv("DEBUG", "0") in {"1", "true"}:
Expand Down

0 comments on commit 5b9fd98

Please sign in to comment.