Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f46c8b3e4 | ||
|
|
fc9161f812 |
No files matched your search
@@ -33,6 +33,7 @@ import contextlib
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import queue
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
@@ -3414,9 +3415,10 @@ class PageDispatcher(Dispatcher):
|
||||
# is a command whose answer only that same read loop can deliver.
|
||||
# Doing it here would block the reader waiting for a message the
|
||||
# reader is the one who has to receive.
|
||||
threading.Thread(
|
||||
target=self._announce_file_chooser, args=(params,),
|
||||
daemon=True).start()
|
||||
# ⛔ AND NOT STARTED HERE EITHER: `Thread.start` waits for the new thread to run, and this is the reader.
|
||||
# The browser's thread starter does it (`_ThreadStarter`).
|
||||
self.context.browser.thread_starter.start(
|
||||
target=self._announce_file_chooser, args=(params,))
|
||||
elif method == "Page.crashed":
|
||||
self.emit("crash")
|
||||
# ⛔ `Page.frameAttached` / `Page.frameDetached` ARE NOT READ HERE: the
|
||||
@@ -4777,6 +4779,51 @@ NO_OVERRIDE = "no-override"
|
||||
NO_OVERRIDE_OPTIONS = ("colorScheme", "reducedMotion", "forcedColors")
|
||||
|
||||
|
||||
class _ThreadStarter:
|
||||
"""The ONE long-lived thread that starts the other threads the engine's events ask for.
|
||||
|
||||
⛔ NO `Thread.start` ON THE CONNECTION'S READER THREAD. `Thread.start` does not return until the new thread is running
|
||||
(`self._started.wait()`), and on Windows under load that wait is milliseconds long: it was the larger part of the reader's delay, and
|
||||
every millisecond the reader is late is a millisecond a `networkidle` quiet is measured late (7 misses in 400 with four browsers at
|
||||
once, none in 400 when the start did not wait). A listener that runs on the reader and needs work done elsewhere hands it to `start`
|
||||
here: a `Thread` that is only BUILT on the reader (building waits for nothing) goes into a queue, and this thread starts it.
|
||||
|
||||
It starts threads and does not run the work itself, on purpose: an adoption waits for the engine as long as the engine takes (a popup
|
||||
whose destination never answers is waited for without a limit), and a worker that ran it would hold every later adoption behind it,
|
||||
`new_page()` included. Each piece of work keeps the thread of its own and the name it always had.
|
||||
"""
|
||||
|
||||
def __init__(self, on_error: Callable[[str], None]) -> None:
|
||||
self._queue: "queue.SimpleQueue" = queue.SimpleQueue()
|
||||
self._on_error = on_error
|
||||
self._stopped = False
|
||||
self._thread = threading.Thread(target=self._run, daemon=True, name="invpw-thread-starter")
|
||||
self._thread.start()
|
||||
|
||||
def start(self, **thread_arguments: Any) -> None:
|
||||
"""Called from any thread, the reader's included: builds the thread and queues it. Never waits."""
|
||||
if self._stopped:
|
||||
return
|
||||
self._queue.put(threading.Thread(daemon=True, **thread_arguments))
|
||||
|
||||
def stop(self) -> None:
|
||||
self._stopped = True
|
||||
self._queue.put(None)
|
||||
|
||||
def _run(self) -> None:
|
||||
while True:
|
||||
thread = self._queue.get()
|
||||
if thread is None:
|
||||
return
|
||||
try:
|
||||
thread.start()
|
||||
except Exception as failure:
|
||||
try:
|
||||
self._on_error("%s could not be started: %s" % (thread.name, failure))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
class BrowserDispatcher(Dispatcher):
|
||||
TYPE = "Browser"
|
||||
METHODS = {"newContext": "op_new_context", "close": "op_close",
|
||||
@@ -4965,6 +5012,9 @@ class BrowserDispatcher(Dispatcher):
|
||||
# subscriber seeing an event before this one records the session, and
|
||||
# recording earlier can only shorten the window in which `session_for`
|
||||
# is waiting for something that has already arrived.
|
||||
self._starter = _ThreadStarter(
|
||||
lambda why: conn.handler_errors.append(why) if len(conn.handler_errors) < 32 else None)
|
||||
conn.add_close_listener(self._starter.stop)
|
||||
conn.add_listener(self._route_browser_event)
|
||||
# The last step of starting the browser, under what is left of the
|
||||
# caller's `launch(timeout=)` (`Connection.startup_send`), not a
|
||||
@@ -4988,6 +5038,11 @@ class BrowserDispatcher(Dispatcher):
|
||||
# the target map): recorded for its session, never built into a page.
|
||||
self._adopt_enabled = True
|
||||
|
||||
@property
|
||||
def thread_starter(self) -> "_ThreadStarter":
|
||||
"""The one thread that starts threads on behalf of the engine's reader (`_ThreadStarter`)."""
|
||||
return self._starter
|
||||
|
||||
def require_interception(self, what: str) -> None:
|
||||
"""Refuse a route this browser cannot honour, instead of ignoring it.
|
||||
|
||||
@@ -5189,11 +5244,10 @@ class BrowserDispatcher(Dispatcher):
|
||||
else:
|
||||
self._strays += 1
|
||||
number = popup_number(None, self._strays)
|
||||
thread = threading.Thread(
|
||||
self._starter.start(
|
||||
target=self._adopt_target,
|
||||
args=(target_id, session_id, browser_context_id, opener, number),
|
||||
daemon=True, name="invpw-adopt-%s" % target_id[:8])
|
||||
thread.start()
|
||||
name="invpw-adopt-%s" % target_id[:8])
|
||||
|
||||
# ── the states of an adoption: the ONLY places a record changes state. Each is one method so that a test can stop the adoption thread
|
||||
# between any two of them and deliver an event of the engine there.
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
"""No thread is started on the engine connection's reader thread.
|
||||
|
||||
`Thread.start` does not return until the new thread is running. On the reader that wait is the reader's own delay: measured on Windows with
|
||||
four browsers at once, it was 75% of the reader's lag, and it made `networkidle` miss 7 times in 400 (none in 400 once the start no longer
|
||||
waited). Two listeners of this package started a thread from the reader: `Browser.attachedToTarget` (one thread per adoption) and
|
||||
`Page.fileChooserOpened` (one thread to announce the chooser). Both now hand the thread to the browser's ONE long-lived starter
|
||||
(`_ThreadStarter`, made with the browser), which starts it.
|
||||
|
||||
NO BROWSER HERE: the real dispatchers over a scripted Juggler connection, and every event of the engine delivered FROM A THREAD OF ITS OWN
|
||||
(the reader's stand-in), the way the connection delivers them. `Thread.start` is replaced by a recorder of the thread that called it.
|
||||
|
||||
`Page.eventFired(load)` is the core's case, tested where the fix is (invisible_core tests/test_no_thread_is_started_on_the_reader.py:
|
||||
the silence of `networkidle` on the connection's one thread of deadlines): this file holds the wrapper's two, the adoption and the chooser.
|
||||
|
||||
Known-bad input: the thread started in `_spawn_adoption` / `_route_juggler_event` -> two starts from the reader (the adoption and the
|
||||
chooser), named in the failure.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import queue
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_playwright._juggler import remote
|
||||
from invisible_playwright._juggler.server import LocalUtilsDispatcher
|
||||
|
||||
from test_every_order_of_the_events_of_a_popup_gives_one_page_event import FRAME, SESSION, TARGET, _wait
|
||||
from test_no_event_of_any_family_is_lost_by_the_hand_over import ChooserEngine
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
READER = "the-engine-reader"
|
||||
|
||||
|
||||
class _Reader:
|
||||
"""A thread that delivers the events it is handed, one at a time and in order, as the connection's reader does."""
|
||||
|
||||
def __init__(self):
|
||||
self._work: "queue.Queue" = queue.Queue()
|
||||
self.thread = threading.Thread(target=self._run, name=READER, daemon=True)
|
||||
self.thread.start()
|
||||
|
||||
def _run(self):
|
||||
while True:
|
||||
job = self._work.get()
|
||||
if job is None:
|
||||
return
|
||||
fn, done = job
|
||||
try:
|
||||
fn()
|
||||
finally:
|
||||
done.set()
|
||||
|
||||
def deliver(self, fn):
|
||||
done = threading.Event()
|
||||
self._work.put((fn, done))
|
||||
assert done.wait(10), "the reader is stuck inside a listener"
|
||||
|
||||
def stop(self):
|
||||
self._work.put(None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def starts(monkeypatch):
|
||||
"""Every `Thread.start` from now on, as (the name of the thread that called it, the name of the thread started)."""
|
||||
calls = []
|
||||
original = threading.Thread.start
|
||||
|
||||
def recording(self):
|
||||
calls.append((threading.current_thread().name, self.name))
|
||||
return original(self)
|
||||
monkeypatch.setattr(threading.Thread, "start", recording)
|
||||
return calls
|
||||
|
||||
|
||||
def _from_reader(starts):
|
||||
return [c for c in starts if c[0] == READER]
|
||||
|
||||
|
||||
def _a_popup_is_announced(conn, reader, browser, context_id, opener_target):
|
||||
reader.deliver(lambda: conn.attach(opener_target, context_id))
|
||||
reader.deliver(conn.frame)
|
||||
reader.deliver(conn.commit)
|
||||
reader.deliver(conn.ready)
|
||||
assert _wait(lambda: browser._page_targets.get(TARGET) is not None, 5), "the popup was never announced (%s)" % (conn.handler_errors,)
|
||||
|
||||
|
||||
def _world(starts):
|
||||
server = remote._SharedServer()
|
||||
browser_type = remote.SharedBrowserType(server)
|
||||
LocalUtilsDispatcher(server)
|
||||
conn = ChooserEngine()
|
||||
browser = remote.SharedBrowserDispatcher(server, browser_type, conn, "firefox/1")
|
||||
context = server.object(server.handle({"guid": browser.guid, "method": "newContext", "params": {}})["context"]["guid"])
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(t for t in conn.sessions if t != TARGET)
|
||||
return server, conn, browser, context, opener_target
|
||||
|
||||
|
||||
def test_an_attached_target_and_a_file_chooser_start_no_thread_on_the_reader(starts):
|
||||
server, conn, browser, context, opener_target = _world(starts)
|
||||
reader = _Reader()
|
||||
chooser = []
|
||||
try:
|
||||
del starts[:]
|
||||
_a_popup_is_announced(conn, reader, browser, context.context_id, opener_target)
|
||||
assert [c[1] for c in starts if c[1].startswith("invpw-adopt-")], "the adoption never started (%s)" % (starts,)
|
||||
page = browser._page_targets[TARGET]
|
||||
original_emit = type(page).emit
|
||||
|
||||
def spy(self, method, params=None):
|
||||
if method == "fileChooser":
|
||||
chooser.append(params)
|
||||
return original_emit(self, method, params)
|
||||
type(page).emit = spy
|
||||
try:
|
||||
reader.deliver(lambda: conn.dispatch_event(
|
||||
"Page.fileChooserOpened", {"element": {"objectId": "input-1"}, "executionContextId": "e"}, SESSION))
|
||||
assert _wait(lambda: chooser, 5), "the chooser never reached the client (%s)" % (conn.handler_errors,)
|
||||
finally:
|
||||
type(page).emit = original_emit
|
||||
assert _from_reader(starts) == [], "the reader started %s" % (_from_reader(starts),)
|
||||
assert conn.handler_errors == []
|
||||
finally:
|
||||
reader.stop()
|
||||
server.shutdown()
|
||||
|
||||
|
||||
def test_the_starter_of_a_browser_ends_with_its_connection(starts):
|
||||
server, conn, browser, context, opener_target = _world(starts)
|
||||
try:
|
||||
starter = browser.thread_starter
|
||||
starter.start(target=lambda: None, name="invpw-test-started")
|
||||
assert _wait(lambda: ("invpw-thread-starter", "invpw-test-started") in starts, 3)
|
||||
conn.announce_closed()
|
||||
starter._thread.join(5)
|
||||
assert not starter._thread.is_alive(), "the starter outlived the connection"
|
||||
starter.start(target=lambda: None, name="invpw-test-after-the-end") # after the end: nothing is started, nothing raises
|
||||
assert all(c[1] != "invpw-test-after-the-end" for c in starts)
|
||||
finally:
|
||||
server.shutdown()
|
||||
Reference in new issue
Block a user