"""Owned local HTTP gateway: total connection deadlines and bounded async I/O.""" import asyncio from collections import Counter import socket from threading import Event, Thread import httpx # One shared wall-clock window for cancellation, transport closure and slot release. CLEANUP_WINDOW_SECONDS = 1.0 HALF_CLOSE_HEADER = 'x-local-s2s-half-close' LIMITS = {'/v1/audio/transcriptions': (1100000, 65536), '/v1/chat/completions': (1048576, 1048576), '/v1/audio/speech': (16384, 1440000)} class ComponentServer: def __init__(self, key, *, port=8766, transport=None, timeout=30, inactivity=None): if not key or not key.isascii() or any(c.isspace() for c in key): raise ValueError('LOCAL_COMPONENT_CREDENTIAL_REQUIRED') self.key, self.transport, self.timeout = key, transport, timeout self.inactivity = min(timeout, 5) if inactivity is None else min(timeout, inactivity) if self.timeout <= 0 or self.inactivity <= 0: raise ValueError('LOCAL_COMPONENT_DEADLINE_REQUIRED') self.counts = Counter() self.socket = socket.socket() self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(('127.0.0.1', port)) self.socket.listen(4) self.socket.setblocking(False) self.server_port = self.socket.getsockname()[1] self.ready, self.done = Event(), Event() self.loop = self.stopping = None self.requests = {} def serve_forever(self): try: asyncio.run(self._run()) finally: self.socket.close() self.done.set() async def _run(self): self.loop, self.stopping = asyncio.get_running_loop(), asyncio.Event() server = await asyncio.start_server(self._accept, sock=self.socket, limit=16384) self.ready.set() try: await self.stopping.wait() finally: server.close() await server.wait_closed() tasks = list(self.requests) for task, writer in list(self.requests.items()): writer.close() task.cancel() if tasks: await asyncio.wait(tasks, timeout=1) self.counts['shutdown_pending'] = sum(not t.done() for t in tasks) def _accept(self, reader, writer): accepted = self.loop.time() if self.stopping.is_set() or len(self.requests) >= 3: self.counts['rejected'] += 1 writer.close() return writer.transport.set_write_buffer_limits(high=16384, low=4096) task = self.loop.create_task(self._serve(reader, writer, accepted + self.timeout)) self.requests[task] = writer self.counts['accepted'] += 1 task.add_done_callback(self._finished) def _finished(self, task): self.requests.pop(task, None) self.counts['released'] += 1 if not task.cancelled(): task.exception() async def _write(self, writer, data): writer.write(data) await asyncio.wait_for(writer.drain(), self.inactivity) async def _error(self, writer, status): await self._write(writer, f'HTTP/1.1 {status} Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n'.encode()) async def _watch_downstream(self, reader, writer, receive_only): # FIN cannot distinguish full close from SHUT_WR. By contract it cancels # ordinary requests; explicit receive-only clients may still read a reply. try: extra = await reader.read(1) if not extra and receive_only: await writer.wait_closed() # still observe a reset/transport loss except (OSError, ValueError): pass async def _forward(self, client, writer, path, fields, body, response): request = client.build_request('POST', 'https://openrouter.ai/api' + path, headers={'Authorization': 'Bearer ' + self.key, 'Content-Type': fields.get('content-type', 'application/json'), 'Accept-Encoding': 'identity'}, content=bytes(body)) # The owner closes the response independently, even if cancellation or a # stalled stream prevents this operation from reaching normal completion. result = await client.send(request, stream=True) response.append(result) if result.status_code != 200: await self._error(writer, 502) return media = result.headers.get('content-type', '').split(';')[0] expected = ('audio/pcm', 'application/octet-stream') if path.endswith('/speech') else ('application/json', 'text/event-stream') if media not in expected or result.headers.get('content-encoding', 'identity') != 'identity': await self._error(writer, 502) return await self._write(writer, ('HTTP/1.1 200 OK\r\nContent-Type: ' + media + '\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n').encode('ascii')) total = 0 # No 8192-byte accumulation: small SSE/PCM arrivals stay observable. async for raw in result.aiter_bytes(): total += len(raw) if total > LIMITS[path][1]: raise ValueError('Response capacity') for offset in range(0, len(raw), 8192): part = raw[offset:offset + 8192] await self._write(writer, f'{len(part):x}\r\n'.encode() + part + b'\r\n') if not total: raise ValueError('Empty component response') await self._write(writer, b'0\r\n\r\n') async def _close_owned(self, writer, tasks, client, response): writer.close() for task in tasks: task.cancel() # Close all transports independently; one stalled close must not defer # another. asyncio.wait bounds the entire cleanup, including task joins. closing = [asyncio.create_task(writer.wait_closed())] if client is not None: closing.append(asyncio.create_task(client.aclose())) closing.extend(asyncio.create_task(result.aclose()) for result in response) done, pending = await asyncio.wait(set(tasks) | set(closing), timeout=CLEANUP_WINDOW_SECONDS) for task in done: if not task.cancelled(): error = task.exception() if task in closing and error is not None: self.counts['close_errors'] += 1 if pending: self.counts['close_errors'] += len(pending) writer.transport.abort() for task in pending: task.cancel() task.add_done_callback(lambda t: None if t.cancelled() else t.exception()) async def _serve(self, reader, writer, deadline): client, tasks, response = None, [], [] try: async with asyncio.timeout_at(deadline): # Header acquisition has its own short bound, including partial headers. header = await asyncio.wait_for(reader.readuntil(b'\r\n\r\n'), self.inactivity) lines = header.decode('ascii').split('\r\n') method, path, version = lines[0].split(' ') fields = {} for line in lines[1:-2]: key, value = line.split(':', 1) key = key.lower() if key in fields: raise ValueError('Repeated header') fields[key] = value.strip() if method != 'POST' or path not in LIMITS or version not in ('HTTP/1.0', 'HTTP/1.1'): await self._error(writer, 403) return request_limit, _ = LIMITS[path] size = int(fields.get('content-length', '-1')) if 'transfer-encoding' in fields or not 0 < size <= request_limit: await self._error(writer, 413) return body = bytearray() while len(body) < size: part = await asyncio.wait_for(reader.read(min(8192, size - len(body))), self.inactivity) if not part: raise ValueError('Incomplete request') body.extend(part) if fields.get('authorization') != 'Bearer local-components': await self._error(writer, 403) return half_close = fields.get(HALF_CLOSE_HEADER) if half_close not in (None, 'receive-response'): await self._error(writer, 400) return self.counts[path] += 1 # one admitted provider attempt, including failed probes client = httpx.AsyncClient(transport=self.transport, timeout=httpx.Timeout(self.inactivity, connect=self.inactivity), follow_redirects=False, trust_env=False) forwarding = asyncio.create_task(self._forward(client, writer, path, fields, body, response)) watching = asyncio.create_task(self._watch_downstream(reader, writer, half_close == 'receive-response')) tasks.extend((forwarding, watching)) done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) if forwarding in done: forwarding.result() else: self.counts['disconnected'] += 1 except TimeoutError: self.counts['expired'] += 1 except asyncio.CancelledError: self.counts['cancelled'] += 1 raise except (ValueError, OSError, UnicodeError, asyncio.IncompleteReadError, asyncio.LimitOverrunError, httpx.HTTPError): self.counts['failures'] += 1 finally: # No successful terminal chunk is fabricated on any failure path. await self._close_owned(writer, tasks, client, response) def shutdown(self): if self.loop is not None and self.loop.is_running(): self.loop.call_soon_threadsafe(self.stopping.set) self.done.wait(2) def server_close(self): self.socket.close() def start_components(key, timeout=30): server = ComponentServer(key, timeout=timeout) thread = Thread(target=server.serve_forever, daemon=True) thread.start() if not server.ready.wait(5): server.server_close() raise ValueError('LOCAL_COMPONENT_STARTUP_DEADLINE') return server, thread