Reorder logic to emphasize common paths.

I snuck in a call to verify that the connected event is set before the
call to _process_metric.  This closes a small loophole where the
transport could be None inside of _process_metric.
This commit is contained in:
Dave Shawley 2021-03-11 07:03:18 -05:00
parent 00759ed20b
commit 65b5bacbee
No known key found for this signature in database
GPG key ID: 44A9C9992CCFAB82

View file

@ -155,7 +155,8 @@ class Processor(asyncio.Protocol):
while not self.should_terminate: while not self.should_terminate:
try: try:
await self._connect_if_necessary() await self._connect_if_necessary()
await self._process_metric() if self.connected.is_set():
await self._process_metric()
except asyncio.CancelledError: except asyncio.CancelledError:
self.logger.info('task cancelled, exiting') self.logger.info('task cancelled, exiting')
break break
@ -221,14 +222,11 @@ class Processor(asyncio.Protocol):
async def _process_metric(self): async def _process_metric(self):
processing_failed_send = False processing_failed_send = False
if self._failed_sends: if not self._failed_sends:
self.logger.debug('using previous send attempt')
metric = self._failed_sends[0]
processing_failed_send = True
else:
try: try:
metric = await asyncio.wait_for(self.queue.get(), 0.1) metric = await asyncio.wait_for(self.queue.get(), 0.1)
self.logger.debug('received %r from queue', metric) self.logger.debug('received %r from queue', metric)
self.queue.task_done()
except asyncio.TimeoutError: except asyncio.TimeoutError:
return return
else: else:
@ -240,15 +238,17 @@ class Processor(asyncio.Protocol):
self.logger.debug('preventing send on closed transport') self.logger.debug('preventing send on closed transport')
self._failed_sends.append(metric) self._failed_sends.append(metric)
return return
else:
self.logger.debug('using previous send attempt')
metric = self._failed_sends[0]
processing_failed_send = True
self.transport.write(metric) self.transport.write(metric)
if self.transport.is_closing(): if not self.transport.is_closing():
# Writing to a transport does not raise exceptions, it
# will close the transport if a low-level error occurs.
self.logger.debug('transport closed by writing')
else:
self.logger.debug('sent %r to statsd', metric) self.logger.debug('sent %r to statsd', metric)
if processing_failed_send: if processing_failed_send:
self._failed_sends.pop(0) self._failed_sends.pop(0)
else: else:
self.queue.task_done() # Writing to a transport does not raise exceptions, it
# will close the transport if a low-level error occurs.
self.logger.debug('transport closed by writing')