fix(collect): handle login target close race
Tests / Python 3.11 / Windows (push) Has been cancelled
Tests / Python 3.11 / Windows (push) Has been cancelled
This commit is contained in:
+41
-2
@@ -22,12 +22,12 @@ def _base(host=None):
|
||||
return f"http://{host or CDP_HOST}"
|
||||
|
||||
|
||||
def http_get(path, host=None):
|
||||
def http_get(path, host=None, timeout=10):
|
||||
import requests
|
||||
|
||||
s = requests.Session()
|
||||
s.trust_env = False # 忽略环境代理
|
||||
return s.get(f"{_base(host)}{path}", timeout=10).json()
|
||||
return s.get(f"{_base(host)}{path}", timeout=timeout).json()
|
||||
|
||||
|
||||
def close_tab(target_id, host=None):
|
||||
@@ -43,6 +43,45 @@ def close_tab(target_id, host=None):
|
||||
return response.ok
|
||||
|
||||
|
||||
def wait_target_closed(target_id, host=None, timeout=2.0, poll_interval=0.1):
|
||||
"""Wait briefly for a closed target to disappear from Chrome's target list."""
|
||||
|
||||
if not target_id:
|
||||
return True
|
||||
timeout = max(0.0, float(timeout))
|
||||
poll_interval = max(0.01, float(poll_interval))
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
remaining = max(0.0, deadline - time.monotonic())
|
||||
request_timeout = max(0.05, min(1.0, remaining))
|
||||
try:
|
||||
targets = http_get("/json", host=host, timeout=request_timeout)
|
||||
except Exception:
|
||||
targets = None
|
||||
if targets is not None and not any(
|
||||
str(target.get("id") or "") == str(target_id)
|
||||
for target in targets
|
||||
):
|
||||
return True
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
return False
|
||||
time.sleep(min(poll_interval, remaining))
|
||||
|
||||
|
||||
def close_tab_and_wait(target_id, host=None, timeout=2.0, poll_interval=0.1):
|
||||
"""Request target closure and confirm disappearance within a bounded budget."""
|
||||
|
||||
if not close_tab(target_id, host=host):
|
||||
return False
|
||||
return wait_target_closed(
|
||||
target_id,
|
||||
host=host,
|
||||
timeout=timeout,
|
||||
poll_interval=poll_interval,
|
||||
)
|
||||
|
||||
|
||||
def activate_tab(target_id, host=None):
|
||||
"""Bring an existing Chrome target/page to the foreground."""
|
||||
|
||||
|
||||
Reference in New Issue
Block a user