async def send_message(self, message: Message) -> MessageResponse: attempt = 0 while True: attempt += 1 if attempt > self.MAX_ATTEMPTS: logger.warning('Trying to send message %s: attempt #%s', message.message_id, attempt) logger.debug('Message %s: waiting for connection', message.message_id) try: connection = await self.acquire() except ConnectionError: logger.warning( 'Could not send notification %s due to ' 'connection problem', message.message_id) await asyncio.sleep(1) continue logger.debug('Message %s: connection %s acquired', message.message_id, connection) try: response = await connection.send_message(message) return response except ConnectionClosed: logger.warning( 'Could not send message %s: ' 'ConnectionClosed', message.message_id) except Exception as e: logger.error('Could not send message %s: %s', message.message_id, e)
def _on_stream_destroyed(self, reason=None): reason = reason or ConnectionClosed() logger.debug('Stream of %s was destroyed: %s', self, reason) self.xmpp_client.stop() if self.inactivity_timer: self.inactivity_timer.cancel() for request in self.requests.values(): if not request.done(): request.set_exception(reason)
async def maintain_min_connections_open(self): while self.maintain_connections_task: self.connections = [ connection for connection in self.connections if not connection.stream_destroyed ] missing_connections = max( 0, self.min_connections - len(self.connections)) if missing_connections > 0: logger.debug('Creating %d missing connections', missing_connections) for _ in range(missing_connections): asyncio.ensure_future(self.acquire()) await asyncio.sleep(1) if self.maintain_connections_task: for connection in self.connections[-missing_connections:]: connection.refresh_inactivity_timer()
async def send_message(self, message): attempt = 0 while True: attempt += 1 if attempt > self.MAX_ATTEMPTS: logger.warning('Trying to send message %s: attempt #%s', message.message_id, attempt) logger.debug('Message %s: waiting for connection', message.message_id) connection = await self.acquire() logger.debug('Message %s: connection %s acquired', message.message_id, connection) try: response = await connection.send_message(message) return response except ConnectionClosed: logger.warning( 'Could not send message %s: ' 'ConnectionClosed', message.message_id) except Exception as e: logger.error('Could not send message %s: %s', message.message_id, e)
def close(self): if self.inactivity_timer: self.inactivity_timer.cancel() logger.debug('Closing connection %s', self) self.xmpp_client.stop()
def discard_connection(self, connection): logger.debug('Connection %s discarded', connection) self.connections.remove(connection) logger.info('Connection released (total: %d)', len(self.connections))