#!/usr/bin/env python3
import http.server
import os
import socketserver

PORT = 8080
ROOT = os.path.dirname(os.path.abspath(__file__))


class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *a, **kw):
        super().__init__(*a, directory=ROOT, **kw)

    def do_GET(self):
        if self.path.startswith('/x'):
            # Tiny throwaway response for the worker's fetch() spam so that
            # each request finishes immediately and the worker can issue the
            # next CreateThrottles() call.
            self.send_response(200)
            self.send_header('Content-Type', 'text/plain')
            self.send_header('Cache-Control', 'no-store')
            self.send_header('Content-Length', '1')
            self.end_headers()
            self.wfile.write(b'x')
            return
        return super().do_GET()

    def log_message(self, fmt, *args):
        # Silence per-request logging; we issue thousands of /x requests.
        pass


class ThreadingTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    allow_reuse_address = True
    daemon_threads = True


if __name__ == '__main__':
    with ThreadingTCPServer(('127.0.0.1', PORT), Handler) as httpd:
        print(f'Serving POC on http://127.0.0.1:{PORT}/poc.html')
        httpd.serve_forever()
