From 65b5bacbee65d143906dd3aa45663144787ba293 Mon Sep 17 00:00:00 2001 From: Dave Shawley Date: Thu, 11 Mar 2021 07:03:18 -0500 Subject: [PATCH] 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. --- sprockets_statsd/statsd.py | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/sprockets_statsd/statsd.py b/sprockets_statsd/statsd.py index 11e0223..933f23b 100644 --- a/sprockets_statsd/statsd.py +++ b/sprockets_statsd/statsd.py @@ -155,7 +155,8 @@ class Processor(asyncio.Protocol): while not self.should_terminate: try: await self._connect_if_necessary() - await self._process_metric() + if self.connected.is_set(): + await self._process_metric() except asyncio.CancelledError: self.logger.info('task cancelled, exiting') break @@ -221,14 +222,11 @@ class Processor(asyncio.Protocol): async def _process_metric(self): processing_failed_send = False - if self._failed_sends: - self.logger.debug('using previous send attempt') - metric = self._failed_sends[0] - processing_failed_send = True - else: + if not self._failed_sends: try: metric = await asyncio.wait_for(self.queue.get(), 0.1) self.logger.debug('received %r from queue', metric) + self.queue.task_done() except asyncio.TimeoutError: return else: @@ -240,15 +238,17 @@ class Processor(asyncio.Protocol): self.logger.debug('preventing send on closed transport') self._failed_sends.append(metric) return + else: + self.logger.debug('using previous send attempt') + metric = self._failed_sends[0] + processing_failed_send = True self.transport.write(metric) - if 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: + if not self.transport.is_closing(): self.logger.debug('sent %r to statsd', metric) if processing_failed_send: self._failed_sends.pop(0) - else: - self.queue.task_done() + else: + # 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')