Files
leleka/scripts/strata-dual-request-proxy.py
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

131 lines
4.8 KiB
Python

#!/usr/bin/env python3
"""Experimental one-endpoint admission for two independent Strata workers.
Each upstream still owns one sequence. This proxy accepts two concurrent HTTP
requests and gives each a different worker; it does not batch model kernels.
Production serving must use the Rust control plane instead.
"""
import argparse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import hmac
import json
from pathlib import Path
import threading
import urllib.error
import urllib.request
class Pool:
def __init__(self, upstreams):
self.upstreams = upstreams
self.free = [True] * len(upstreams)
self.condition = threading.Condition()
def acquire(self):
with self.condition:
self.condition.wait_for(lambda: any(self.free))
# Serial turns stay on worker zero for prefix reuse. A concurrent
# second request goes to worker one.
index = self.free.index(True)
self.free[index] = False
return index
def release(self, index):
with self.condition:
self.free[index] = True
self.condition.notify()
class Handler(BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.1'
server_version = 'StrataDualExperiment/0.1'
def log_message(self, format, *args):
# Requests may contain private prompts and credentials.
pass
def do_GET(self):
self.forward()
def do_POST(self):
self.forward()
def forward(self):
if not hmac.compare_digest(self.headers.get('Authorization', ''),
'Bearer ' + self.server.api_key):
self.send_error(401)
return
if self.path not in ('/health', '/slots', '/v1/models', '/models',
'/v1/chat/completions', '/v1/completions'):
self.send_error(404)
return
try:
length = int(self.headers.get('Content-Length', '0'))
except ValueError:
self.send_error(400)
return
if length < 0 or length > 64 * 1024 * 1024:
self.send_error(413)
return
body = self.rfile.read(length) if length else None
index = self.server.pool.acquire()
response_started = False
try:
request = urllib.request.Request(
self.server.pool.upstreams[index] + self.path,
data=body if self.command == 'POST' else None,
method=self.command,
headers={
'Authorization': self.headers['Authorization'],
'Content-Type': self.headers.get('Content-Type', 'application/json'),
'Accept': self.headers.get('Accept', '*/*'),
},
)
try:
response = urllib.request.urlopen(request, timeout=900)
except urllib.error.HTTPError as error:
response = error
with response:
self.send_response(response.status)
self.send_header('Content-Type', response.headers.get('Content-Type',
'application/json'))
self.send_header('Connection', 'close')
self.end_headers()
response_started = True
self.close_connection = True
reader = getattr(response, 'read1', response.read)
while chunk := reader(65536):
self.wfile.write(chunk)
self.wfile.flush()
except (BrokenPipeError, ConnectionResetError):
pass
except (OSError, ValueError):
if not response_started:
self.send_error(502)
finally:
self.server.pool.release(index)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--host', default='127.0.0.1')
parser.add_argument('--port', type=int, default=18080)
parser.add_argument('--upstream', action='append', required=True)
parser.add_argument('--config', type=Path, required=True,
help='private Strata JSON config containing api_key')
options = parser.parse_args()
if len(options.upstream) != 2 or not 1 <= options.port <= 65535:
parser.error('exactly two --upstream values and a valid port are required')
config = json.loads(options.config.read_text())
with ThreadingHTTPServer((options.host, options.port), Handler) as server:
server.api_key = config['api_key']
server.pool = Pool([url.rstrip('/') for url in options.upstream])
print(json.dumps({'host': options.host, 'port': options.port,
'upstream_count': len(options.upstream)}), flush=True)
server.serve_forever(poll_interval=0.2)
if __name__ == '__main__':
main()