From 4d5f16f2aa6ee1ffe0c3d26055e1851081239c67 Mon Sep 17 00:00:00 2001 From: Lonami Exo Date: Fri, 22 Sep 2017 12:44:09 +0200 Subject: [PATCH] Fix background thread could not reconnect properly --- telethon/telegram_bare_client.py | 4 ++-- telethon/telegram_client.py | 10 +++++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/telethon/telegram_bare_client.py b/telethon/telegram_bare_client.py index e25cc52d..3ee96835 100644 --- a/telethon/telegram_bare_client.py +++ b/telethon/telegram_bare_client.py @@ -3,7 +3,7 @@ from datetime import timedelta from hashlib import md5 from io import BytesIO from os import path -from threading import RLock +from threading import Lock from . import helpers as utils from .crypto import rsa, CdnDecrypter @@ -84,7 +84,7 @@ class TelegramBareClient: # Two threads may be calling reconnect() when the connection is lost, # we only want one to actually perform the reconnection. - self._connect_lock = RLock() + self._connect_lock = Lock() # Cache "exported" senders 'dc_id: TelegramBareClient' and # their corresponding sessions not to recreate them all diff --git a/telethon/telegram_client.py b/telethon/telegram_client.py index 91224417..637309d3 100644 --- a/telethon/telegram_client.py +++ b/telethon/telegram_client.py @@ -243,7 +243,10 @@ class TelegramClient(TelegramBareClient): *args will be ignored. """ - if self._on_read_thread(): + # This is only valid when the read thread is reconnecting, + # that is, the connection lock is locked. + on_read_thread = self._on_read_thread() + if on_read_thread and not self._connect_lock.locked(): raise AssertionError('Cannot invoke requests from the ReadThread') self.updates.check_error() @@ -254,8 +257,9 @@ class TelegramClient(TelegramBareClient): # will be the one which should be reading (but is invoking the # request) thus not being available to read it "in the background" # and it's needed to call receive. + call_receive = on_read_thread or self._recv_thread is None return super().invoke( - request, call_receive=self._recv_thread is None, + request, call_receive=call_receive, retries=kwargs.get('retries', 5) ) @@ -271,7 +275,7 @@ class TelegramClient(TelegramBareClient): self._reconnect(new_dc=e.new_dc) return self.invoke(request) - except ConnectionResetError: + except ConnectionResetError as e: if self._connect_lock.locked(): # We are connecting and we don't want to reconnect there... raise