Skip to content

Commit e1aad44

Browse files
committed
fix _check_chrome_connection too fast and no retry
1 parent faba7d3 commit e1aad44

File tree

5 files changed

+81
-30
lines changed

5 files changed

+81
-30
lines changed

examples_async.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ async def test_tab_js(tab: AsyncTab):
204204
# test wait tags
205205
result = await tab.wait_tags("abcdabcdabcdabcd", max_wait_time=1)
206206
assert result == []
207-
assert await tab.wait_tag("title", max_wait_time=3)
207+
assert await tab.wait_tag("title", max_wait_time=5)
208208
assert await tab.includes("MIT License")
209209
assert not (await tab.includes("abcdabcdabcdabcd"))
210210
assert await tab.wait_includes("MIT License")
@@ -570,7 +570,8 @@ def on_shutdown(chromed):
570570
assert await tab.clear_browser_cache()
571571
logger.info("clear_browser_cache OK.")
572572
# close tab
573-
await tab.close()
573+
# await tab.close()
574+
# logger.info("close tab OK.")
574575
# test chrome.connect_tab
575576
async with chrome.connect_tab(chrome.server + "/json", True) as tab:
576577
await tab.wait_loading(2)

ichrome/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from .logs import logger
66
from .pool import ChromeEngine
77

8-
__version__ = "5.0.1"
8+
__version__ = "5.0.2"
99
__tips__ = "[github]: https://github.com/ClericPy/ichrome\n[cdp]: https://chromedevtools.github.io/devtools-protocol/\n[cmd args]: https://peter.sh/experiments/chromium-command-line-switches/"
1010
__all__ = [
1111
"ChromeDaemon",

ichrome/async_utils.py

Lines changed: 46 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,18 @@
1818
Coroutine,
1919
Dict,
2020
List,
21+
Literal,
2122
Optional,
2223
Set,
2324
Union,
2425
)
2526
from urllib.parse import quote_plus, urljoin
2627
from weakref import WeakValueDictionary
2728

29+
from aiohttp import ClientResponse, ClientSession
2830
from aiohttp.client import ClientWebSocketResponse
2931
from aiohttp.client_exceptions import ClientError
3032
from aiohttp.http import WebSocketError, WSMsgType
31-
from aiohttp import ClientSession, ClientResponse
3233

3334
from .base import (
3435
INF,
@@ -612,8 +613,7 @@ async def close(self, timeout=0) -> Union[dict, None]:
612613
"""[Page.close], close tab with cdp websocket. will lose ws, so timeout default to 0."""
613614
try:
614615
return await self.send("Page.close", timeout=timeout)
615-
except ChromeRuntimeError as error:
616-
logger.error(f"close tab failed for {error!r}")
616+
except ChromeRuntimeError:
617617
return None
618618

619619
async def crash(self, timeout=0) -> Union[dict, None]:
@@ -1752,7 +1752,13 @@ async def wait_findall(
17521752
self,
17531753
regex: str,
17541754
cssselector: str = "html",
1755-
attribute: str = "outerHTML",
1755+
attribute: Literal[
1756+
"outerHTML",
1757+
"innerHTML",
1758+
"textContent",
1759+
"innerText",
1760+
"outerText",
1761+
] = "outerHTML",
17561762
flags: str = "g",
17571763
max_wait_time: Optional[float] = None,
17581764
interval: float = 1,
@@ -1778,7 +1784,13 @@ async def findone(
17781784
self,
17791785
regex: str,
17801786
cssselector: str = "html",
1781-
attribute: str = "outerHTML",
1787+
attribute: Literal[
1788+
"outerHTML",
1789+
"innerHTML",
1790+
"textContent",
1791+
"innerText",
1792+
"outerText",
1793+
] = "outerHTML",
17821794
timeout=NotSet,
17831795
):
17841796
"find the string in html(select with given css)"
@@ -1793,7 +1805,13 @@ async def findall(
17931805
self,
17941806
regex: str,
17951807
cssselector: str = "html",
1796-
attribute: str = "outerHTML",
1808+
attribute: Literal[
1809+
"outerHTML",
1810+
"innerHTML",
1811+
"textContent",
1812+
"innerText",
1813+
"outerText",
1814+
] = "outerHTML",
17971815
flags: str = "g",
17981816
timeout=NotSet,
17991817
) -> list:
@@ -1851,7 +1869,13 @@ async def contains(
18511869
self,
18521870
text,
18531871
cssselector: str = "html",
1854-
attribute: str = "outerHTML",
1872+
attribute: Literal[
1873+
"outerHTML",
1874+
"innerHTML",
1875+
"textContent",
1876+
"innerText",
1877+
"outerText",
1878+
] = "outerHTML",
18551879
timeout=NotSet,
18561880
) -> bool:
18571881
"""alias for Tab.includes"""
@@ -1863,7 +1887,13 @@ async def includes(
18631887
self,
18641888
text,
18651889
cssselector: str = "html",
1866-
attribute: str = "outerHTML",
1890+
attribute: Literal[
1891+
"outerHTML",
1892+
"innerHTML",
1893+
"textContent",
1894+
"innerText",
1895+
"outerText",
1896+
] = "outerHTML",
18671897
timeout=NotSet,
18681898
) -> bool:
18691899
"""String.prototype.includes.
@@ -1882,7 +1912,13 @@ async def wait_includes(
18821912
self,
18831913
text: str,
18841914
cssselector: str = "html",
1885-
attribute: str = "outerHTML",
1915+
attribute: Literal[
1916+
"outerHTML",
1917+
"innerHTML",
1918+
"textContent",
1919+
"innerText",
1920+
"outerText",
1921+
] = "outerHTML",
18861922
max_wait_time: Optional[float] = None,
18871923
interval: float = 1,
18881924
timeout=NotSet,
@@ -3888,7 +3924,7 @@ async def __aexit__(self, *_):
38883924
if self.browserContextId:
38893925
try:
38903926
await self.browser.send("Target.disposeBrowserContext")
3891-
except ChromeRuntimeError:
3927+
except Exception:
38923928
pass
38933929
self.browserContextId = None
38943930
if self._need_init_chrome:

ichrome/daemon.py

Lines changed: 29 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,7 @@ class ChromeDaemon(object):
148148
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
149149
]
150150
SYSTEM_ENCODING = os.getenv("SYSTEM_ENCODING") or ""
151+
LAST_N_LINES_STDOUT = 5
151152

152153
def __init__(
153154
self,
@@ -510,16 +511,16 @@ def close_stdout_stderr(self, error_name=""):
510511
if f and not f.closed:
511512
try:
512513
if error_name and f is self.opened_files[1]:
513-
last_5_lines = []
514+
last_n_lines = []
514515
f.seek(0)
515516
for line in f:
516517
if not line.strip():
517518
continue
518-
last_5_lines.append(line)
519-
if len(last_5_lines) > 5:
520-
last_5_lines.pop(0)
521-
if last_5_lines:
522-
content = b"".join(last_5_lines)
519+
last_n_lines.append(line)
520+
if len(last_n_lines) > self.LAST_N_LINES_STDOUT:
521+
last_n_lines.pop(0)
522+
if last_n_lines:
523+
content = b"".join(last_n_lines)
523524
if self.SYSTEM_ENCODING:
524525
text = content.decode(self.SYSTEM_ENCODING)
525526
else:
@@ -529,9 +530,14 @@ def close_stdout_stderr(self, error_name=""):
529530
text = content.decode(
530531
"gb18030", errors="replace"
531532
)
532-
logger.error(
533-
f"stderr file last 5 lines for {error_name}: {text}"
534-
)
533+
if (
534+
self.LAST_N_LINES_STDOUT
535+
and error_name
536+
and error_name != "None"
537+
):
538+
logger.error(
539+
f"stderr file last {self.LAST_N_LINES_STDOUT} lines for {error_name!r}: {text}"
540+
)
535541
except Exception:
536542
pass
537543
f.close()
@@ -734,9 +740,7 @@ def shutdown(self, reason=None, exc_type=None):
734740
if self.on_shutdown:
735741
self.on_shutdown(self)
736742
self.kill(True)
737-
self.close_stdout_stderr(
738-
error_name=getattr(exc_type, "__name__", repr(exc_type))
739-
)
743+
self.close_stdout_stderr(error_name=getattr(exc_type, "__name__", ""))
740744
if self.after_shutdown:
741745
self.after_shutdown(self)
742746
if self.clear_after_shutdown:
@@ -939,8 +943,18 @@ async def launch_chrome(self):
939943

940944
async def _check_chrome_connection(self):
941945
async with ClientSession() as session:
942-
r = await session.head(self.server, timeout=self._timeout)
943-
return r.ok
946+
start = time.time()
947+
for _ in range(20):
948+
try:
949+
r = await session.head(self.server, timeout=self._timeout)
950+
return r.ok
951+
except Exception:
952+
if time.time() - start > self.MAX_WAIT_CHECKING_SECONDS:
953+
break
954+
await asyncio.sleep(0.1)
955+
raise ChromeRuntimeError(
956+
f"check_chrome_connection failed for {self.server} not ok."
957+
)
944958

945959
async def check_connection(self):
946960
"check chrome connection ok"
@@ -1072,7 +1086,7 @@ async def shutdown(self, reason=None, exc_type=None):
10721086
await async_run(self.kill, True)
10731087
await async_run(
10741088
self.close_stdout_stderr,
1075-
error_name=getattr(exc_type, "__name__", repr(exc_type)),
1089+
error_name=getattr(exc_type, "__name__", ""),
10761090
)
10771091
if self.after_shutdown:
10781092
await ensure_awaitable(self.after_shutdown(self))

ichrome/pool.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,10 +105,10 @@ def cancel_task(self):
105105
except AttributeError:
106106
pass
107107

108-
def cancel(self):
108+
def cancel(self, msg=None):
109109
logger.info(f"[canceled] {self}")
110110
self.cancel_task()
111-
super().cancel()
111+
super().cancel(msg=msg)
112112

113113
def __lt__(self, other):
114114
return self.expire_time < other.expire_time

0 commit comments

Comments
 (0)