pgjones / hypercorn

Hypercorn is an ASGI and WSGI Server based on Hyper libraries and inspired by Gunicorn.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Hypercorn on a background thread?

jernst opened this issue · comments

I'm trying to run Hypercorn on a background thread. (The main Thread wants to run http client calls against an app served by Hypercorn.) This works, except for shutdown. My shutdown is only happening once "one more" http request has come in, not immediately, and I don't understand why.

import asyncio
import time
from threading import Thread
from typing import List

from hypercorn.asyncio import serve
from hypercorn.config import Config

class HttpServer(Thread):
    """
    Embedded HTTP Server
    """
    def __init__(self, config: Config):
        super().__init__()

        self._config = config
        self._shutdown_event = asyncio.Event()

    def start(self):
        super().start()
        print( "XXX start done" )

    def stop(self):
        self._shutdown_event.set()
        print( "XXX stop done" )

    def run(self):
        print('XXX Starting HttpServer')
        loop = asyncio.new_event_loop()

        loop.run_until_complete(serve(self._wsgi, self._config, shutdown_trigger=self._shutdown_event.wait))
        print('XXX Stopping HttpServer')

    def _wsgi(self,env, start_fn):
        print( "XXX serving" )
        start_fn('200 OK', [('Content-Type', 'text/plain')])
        return [b"Hello World!\n"]

config = Config()
config.bind = ['0.0.0.0:8888']

http = HttpServer(config)

http.start()

time.sleep(5) # Issue HTTP client requests here, for now done using curl from outside
print( "AFTER sleep" )
http.stop()

time.sleep(1000)

If I run this, the main thread goes into the second sleep statement and does not print "XXX Stopping HttpServer". Only once an additional HTTP request has come in (while main thread is in the second sleep) does the run method end with "XXX Stopping HttpServer".

How do I do this properly?

Duplicate of #145?

Yep, see that discussion for resolution