Fix connection leak issue

This commit is contained in:
ManiMozaffar 2023-09-21 14:13:04 +03:00
parent fc065becb0
commit 28a12652a3
1 changed files with 28 additions and 22 deletions

View File

@ -1,27 +1,26 @@
#!/usr/bin/env python3
# this module is part of undetected_chromedriver
import asyncio import asyncio
import json import json
import logging import logging
import threading import threading
import time
from selenium import webdriver
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class Reactor(threading.Thread): class Reactor(threading.Thread):
def __init__(self, driver: "Chrome"): def __init__(self, driver: webdriver.Chrome):
super().__init__() super().__init__()
self.driver = driver self.driver = driver
self.loop = asyncio.new_event_loop() self.loop = asyncio.new_event_loop()
self.paused = False
self.lock = threading.Lock() self.lock = threading.Lock()
self.event = threading.Event() self.event = threading.Event()
self.daemon = True self.daemon = True
self.handlers = {} self.handlers = {}
def add_event_handler(self, method_name, callback: callable): def add_event_handler(self, method_name, callback):
""" """
Parameters Parameters
@ -39,9 +38,16 @@ class Reactor(threading.Thread):
with self.lock: with self.lock:
self.handlers[method_name.lower()] = callback self.handlers[method_name.lower()] = callback
@property def terminate(self, timeout=10):
def running(self): self.event.set()
return not self.event.is_set() start_time = time.time()
while not self.paused:
elapsed_time = time.time() - start_time
if elapsed_time >= timeout:
break
time.sleep(0.1)
self.loop.close()
return None
def run(self): def run(self):
try: try:
@ -58,12 +64,12 @@ class Reactor(threading.Thread):
and getattr(self.driver.service, "process", None) and getattr(self.driver.service, "process", None)
and self.driver.service.process.poll() and self.driver.service.process.poll()
): ):
await asyncio.sleep(self.driver._delay or 0.25) await asyncio.sleep(self.driver._delay or 0.25) # type: ignore
else: else:
break break
async def listen(self): async def listen(self):
while self.running: while not self.event.is_set():
await self._wait_service_started() await self._wait_service_started()
await asyncio.sleep(1) await asyncio.sleep(1)
@ -74,9 +80,11 @@ class Reactor(threading.Thread):
for entry in log_entries: for entry in log_entries:
try: try:
obj_serialized: str = entry.get("message") obj_serialized: str = entry.get("message")
obj = json.loads(obj_serialized) obj: dict[str, dict] = json.loads(obj_serialized)
message = obj.get("message") message = obj.get("message")
method = message.get("method") assert message is not None
method: str | None = message.get("method")
assert isinstance(method, str)
if "*" in self.handlers: if "*" in self.handlers:
await self.loop.run_in_executor( await self.loop.run_in_executor(
@ -86,13 +94,11 @@ class Reactor(threading.Thread):
await self.loop.run_in_executor( await self.loop.run_in_executor(
None, self.handlers[method.lower()], message None, self.handlers[method.lower()], message
) )
except Exception as error:
logging.debug("exception ignored :", error)
raise error from None
# print(type(message), message) except Exception as error:
except Exception as e: logging.debug("exception ignored :", error)
raise e from None
except Exception as e: self.paused = True
if "invalid session id" in str(e):
pass
else:
logging.debug("exception ignored :", e)