1919import asyncio
2020import logging
2121import os
22- from concurrent .futures .thread import ThreadPoolExecutor
2322from datetime import datetime , timedelta
2423from hashlib import sha1
2524from io import BytesIO
2625
2726import pyrogram
28- from pyrogram import __copyright__ , __license__ , __version__
27+ from pyrogram import __copyright__ , __license__ , __version__ , utils
2928from pyrogram import raw
3029from pyrogram .connection import Connection
3130from pyrogram .crypto import mtproto
@@ -51,7 +50,6 @@ class Session:
5150 MAX_RETRIES = 5
5251 ACKS_THRESHOLD = 8
5352 PING_INTERVAL = 5
54- EXECUTOR_SIZE_THRESHOLD = 512
5553
5654 notice_displayed = False
5755
@@ -69,8 +67,6 @@ class Session:
6967 64 : "[64] invalid container"
7068 }
7169
72- executor = ThreadPoolExecutor (2 , thread_name_prefix = "CryptoWorker" )
73-
7470 def __init__ (
7571 self ,
7672 client : "pyrogram.Client" ,
@@ -220,22 +216,12 @@ async def restart(self):
220216 await self .start ()
221217
222218 async def handle_packet (self , packet ):
223- if len (packet ) <= self .EXECUTOR_SIZE_THRESHOLD :
224- data = mtproto .unpack (
225- BytesIO (packet ),
226- self .session_id ,
227- self .auth_key ,
228- self .auth_key_id
229- )
230- else :
231- data = await self .loop .run_in_executor (
232- self .executor ,
233- mtproto .unpack ,
234- BytesIO (packet ),
235- self .session_id ,
236- self .auth_key ,
237- self .auth_key_id
238- )
219+ data = await utils .maybe_run_in_executor (
220+ mtproto .unpack , BytesIO (packet ), len (packet ), self .loop ,
221+ self .session_id ,
222+ self .auth_key ,
223+ self .auth_key_id
224+ )
239225
240226 messages = (
241227 data .body .messages
@@ -375,24 +361,13 @@ async def _send(self, data: TLObject, wait_response: bool = True, timeout: float
375361 log .debug (f"Sent:" )
376362 log .debug (message )
377363
378- if len (message ) <= self .EXECUTOR_SIZE_THRESHOLD :
379- payload = mtproto .pack (
380- message ,
381- self .current_salt .salt ,
382- self .session_id ,
383- self .auth_key ,
384- self .auth_key_id
385- )
386- else :
387- payload = await self .loop .run_in_executor (
388- self .executor ,
389- mtproto .pack ,
390- message ,
391- self .current_salt .salt ,
392- self .session_id ,
393- self .auth_key ,
394- self .auth_key_id
395- )
364+ payload = await utils .maybe_run_in_executor (
365+ mtproto .pack , message , len (message ), self .loop ,
366+ self .current_salt .salt ,
367+ self .session_id ,
368+ self .auth_key ,
369+ self .auth_key_id
370+ )
396371
397372 try :
398373 await self .connection .send (payload )
0 commit comments