Don't use call in thread because it blocks the main serving thread

This commit is contained in:
Andrew Godwin 2016-02-21 12:31:48 +00:00
parent 1709522162
commit aa6c0a73e6
2 changed files with 16 additions and 21 deletions

View File

@ -34,6 +34,7 @@ class WebRequest(http.Request):
self._got_response_start = False
def process(self):
self.request_start = time.time()
# Get upgrade header
upgrade_header = None
if self.requestHeaders.hasHeader(b"Upgrade"):
@ -156,6 +157,7 @@ class WebRequest(http.Request):
"status": self.code,
"method": self.method.decode("ascii"),
"client": "%s:%s" % (self.client.host, self.client.port),
"time_taken": time.time() - self.request_start,
})
else:
logger.debug("HTTP response chunk for %s", self.reply_channel)

View File

@ -19,30 +19,23 @@ class Server(object):
def run(self):
self.factory = HTTPFactory(self.channel_layer, self.action_logger)
reactor.listenTCP(self.port, self.factory, interface=self.host)
reactor.callInThread(self.backend_reader)
reactor.callLater(0, self.backend_reader)
reactor.run(installSignalHandlers=self.signal_handlers)
def backend_reader(self):
"""
Run in a separate thread; reads messages from the backend.
"""
while True:
channels = self.factory.reply_channels()
# Quit if reactor is stopping
if not reactor.running:
logging.debug("Backend reader quitting due to reactor stop")
return
# Don't do anything if there's no channels to listen on
if channels:
channel, message = self.channel_layer.receive_many(channels, block=False)
if channel:
logging.debug("Server got message on %s", channel)
else:
time.sleep(0.1)
continue
# Wait around if there's nothing received
if channel is None:
time.sleep(0.05)
continue
# Deal with the message
self.factory.dispatch_reply(channel, message)
channels = self.factory.reply_channels()
# Quit if reactor is stopping
if not reactor.running:
logging.debug("Backend reader quitting due to reactor stop")
return
# Don't do anything if there's no channels to listen on
if channels:
channel, message = self.channel_layer.receive_many(channels, block=False)
if channel:
logging.debug("Server got message on %s", channel)
# Deal with the message
self.factory.dispatch_reply(channel, message)
reactor.callLater(0, self.backend_reader)