Add task-bench, which has Haiku fix planted bugs at a base and a head and prints what each side took
CI / tests (pull_request) Failing after 4m9s
CI / tests (pull_request) Failing after 4m9s
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
"""An HTTP proxy that tunnels `CONNECT` to the one `host:port` its first argument names and answers 403 to every other request.
|
||||
|
||||
task-bench runs it in a container of its own, as `python api_proxy.py <host:port> [<listen port>]`: the containers Haiku works in sit
|
||||
on a network with no route out, and reach the API through it and nothing else. It imports only the standard library, since that
|
||||
container holds nothing more."""
|
||||
import asyncio
|
||||
import contextlib
|
||||
import sys
|
||||
|
||||
PORT = 8080
|
||||
|
||||
|
||||
async def served(allowed: str, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
|
||||
"""Answers one client: a tunnel to `allowed` where its request is `CONNECT <allowed>`, else 403."""
|
||||
with contextlib.suppress(OSError, asyncio.IncompleteReadError, asyncio.LimitOverrunError):
|
||||
try:
|
||||
request = (await reader.readuntil(b"\r\n\r\n")).split(b"\r\n")[0].decode("latin-1").split()
|
||||
if len(request) != 3 or request[0] != "CONNECT" or request[1] != allowed:
|
||||
writer.write(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n")
|
||||
await writer.drain()
|
||||
return
|
||||
host, _, port = allowed.rpartition(":")
|
||||
there_reader, there_writer = await asyncio.open_connection(host, int(port))
|
||||
writer.write(b"HTTP/1.1 200 Connection established\r\n\r\n")
|
||||
await writer.drain()
|
||||
# Either side closing ends the tunnel, so the other copy is cancelled rather than left waiting.
|
||||
copies = [asyncio.ensure_future(copied(reader, there_writer)), asyncio.ensure_future(copied(there_reader, writer))]
|
||||
await asyncio.wait(copies, return_when=asyncio.FIRST_COMPLETED)
|
||||
for copy in copies:
|
||||
copy.cancel()
|
||||
there_writer.close()
|
||||
finally:
|
||||
writer.close()
|
||||
|
||||
|
||||
async def copied(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
|
||||
with contextlib.suppress(OSError):
|
||||
while data := await reader.read(65536):
|
||||
writer.write(data)
|
||||
await writer.drain()
|
||||
|
||||
|
||||
async def serve(allowed: str, port: int) -> None:
|
||||
server = await asyncio.start_server(lambda reader, writer: served(allowed, reader, writer), "0.0.0.0", port)
|
||||
async with server:
|
||||
await server.serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(serve(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else PORT))
|
||||
Reference in New Issue
Block a user