juggler: a download that finished before it was announced is finished
BrowserDispatcher._on_download_finished keeps the error of a download whose artifact does not exist yet; a successful download has no error (None), and _on_download_created popped it with a None default and tested `is not None`, so the artifact was never marked finished and save_as, path and failure waited forever. A module-level sentinel tells "nothing recorded" from "finished with no error". The entry is also popped before the unknown-context early return, so it no longer stays in the dict. Tests: unit file (red on the old code for the success and the gone-context cases) and a served-browser e2e with ten 300-byte and ten 1-byte downloads. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ff02f112fe
commit
6a50ad1333
3 files changed
+218
-2
No files matched your search
@@ -180,6 +180,13 @@ class APIRequestContextDispatcher(RefusingDispatcher):
|
||||
#: what the alternative reads like.
|
||||
_HANDLE = "<element handle>"
|
||||
|
||||
#: ⛔ ABSENT, NOT "FINISHED WITH NO ERROR". `BrowserDispatcher._finished_early` keeps the error of a download the
|
||||
#: engine finished before it announced it, and a download that SUCCEEDED has `None` for an error: popping with a
|
||||
#: `None` default and testing `is not None` read a success as "nothing was recorded", so the artifact was never
|
||||
#: marked finished and `save_as`, `path` and `failure` waited forever on a download that was complete. This
|
||||
#: marker is what a pop returns when nothing was recorded, so the two are told apart.
|
||||
_NOT_FINISHED_EARLY = object()
|
||||
|
||||
|
||||
def _key_delay(params: Dict) -> Optional[float]:
|
||||
"""The caller's `delay` for a key operation, in milliseconds, or None.
|
||||
@@ -5456,13 +5463,15 @@ class BrowserDispatcher(Dispatcher):
|
||||
# "if it's a new window download, report it on the pop-up's opener"); looking only among the announced pages, as this did,
|
||||
# lost the download altogether.
|
||||
origin = announced or (adoption.opener if adoption is not None else self._gone_openers.get(target))
|
||||
# Popped BEFORE the context check: a download of a context that is gone leaves no artifact to finish, and its
|
||||
# early entry would stay in the dict for the life of the browser.
|
||||
early = self._finished_early.pop(params["uuid"], _NOT_FINISHED_EARLY)
|
||||
if context is None:
|
||||
return
|
||||
directory = self._downloads_dir(params.get("browserContextId"))
|
||||
artifact = ArtifactDispatcher(self.server, context, params["uuid"],
|
||||
os.path.join(directory, params["uuid"]))
|
||||
self._artifacts[params["uuid"]] = artifact
|
||||
early = self._finished_early.pop(params["uuid"], None)
|
||||
if page is not None or origin is not None:
|
||||
# ⛔ THE ENGINE ENDS A NAVIGATION THAT BECAME A DOWNLOAD WITH NO
|
||||
# EVENT AT ALL (no navigationCommitted, no navigationAborted), so
|
||||
@@ -5496,7 +5505,7 @@ class BrowserDispatcher(Dispatcher):
|
||||
deferred = True
|
||||
if not deferred:
|
||||
origin.emit("download", payload)
|
||||
if early is not None:
|
||||
if early is not _NOT_FINISHED_EARLY:
|
||||
artifact.report_finished(early)
|
||||
|
||||
def _on_download_finished(self, params: Dict) -> None:
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
"""A download the engine finished BEFORE it announced it is finished once it is announced.
|
||||
|
||||
`BrowserDispatcher._on_download_finished` keeps the error of a download whose artifact does not exist yet, and
|
||||
`_on_download_created` hands it to the artifact later. A download that succeeded has no error (`None`), and the old
|
||||
code read that as "nothing was kept": the artifact was never marked finished, so `save_as`, `path` and `failure`
|
||||
waited forever on a complete file (seen on tiny downloads, where the transfer ends before the announcement is handled).
|
||||
|
||||
No browser and no socket: the two real methods run on a stand-in that carries the attributes they read, and the
|
||||
artifact is a fake that records what it was told.
|
||||
|
||||
Known-bad input: the old code -> (a) and (d) are red.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import types
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_playwright._juggler import server as juggler_server
|
||||
from invisible_playwright._juggler.server import BrowserDispatcher
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
CONTEXT = "ctx-1"
|
||||
|
||||
|
||||
class FakeArtifact:
|
||||
"""What `ArtifactDispatcher` is to the two methods: built with (server, context, uuid, path), told once."""
|
||||
|
||||
def __init__(self, server, context, uuid, path):
|
||||
self.uuid = uuid
|
||||
self.path = path
|
||||
self.channel = {"guid": "artifact@" + uuid}
|
||||
self.finished = threading.Event()
|
||||
self.reports = []
|
||||
|
||||
def report_finished(self, error):
|
||||
self.reports.append(error)
|
||||
self.finished.set()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def browser(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(juggler_server, "ArtifactDispatcher", FakeArtifact)
|
||||
return types.SimpleNamespace(
|
||||
contexts=[types.SimpleNamespace(context_id=CONTEXT)],
|
||||
_targets_lock=threading.Lock(),
|
||||
_page_targets={},
|
||||
_adoptions={},
|
||||
_gone_openers={},
|
||||
_artifacts={},
|
||||
_finished_early={},
|
||||
server=object(),
|
||||
_downloads_dir=lambda context_id: str(tmp_path),
|
||||
)
|
||||
|
||||
|
||||
def _created(browser, uuid, context=CONTEXT):
|
||||
BrowserDispatcher._on_download_created(
|
||||
browser, {"uuid": uuid, "browserContextId": context, "pageTargetId": "t1",
|
||||
"url": "http://x/f", "suggestedFileName": "f.bin"})
|
||||
|
||||
|
||||
def _finished(browser, uuid, **extra):
|
||||
BrowserDispatcher._on_download_finished(browser, dict({"uuid": uuid}, **extra))
|
||||
|
||||
|
||||
def test_a_download_that_succeeded_before_it_was_announced_is_finished(browser):
|
||||
_finished(browser, "u1")
|
||||
_created(browser, "u1")
|
||||
artifact = browser._artifacts["u1"]
|
||||
assert artifact.finished.wait(2), "the artifact was never marked finished: save_as would wait forever"
|
||||
assert artifact.reports == [None]
|
||||
assert browser._finished_early == {}
|
||||
|
||||
|
||||
def test_a_download_canceled_before_it_was_announced_is_finished_with_the_reason(browser):
|
||||
_finished(browser, "u2", canceled=True)
|
||||
_created(browser, "u2")
|
||||
artifact = browser._artifacts["u2"]
|
||||
assert artifact.finished.wait(2)
|
||||
assert artifact.reports == ["canceled"]
|
||||
assert browser._finished_early == {}
|
||||
|
||||
|
||||
def test_a_download_that_failed_before_it_was_announced_keeps_its_error(browser):
|
||||
_finished(browser, "u3", error="NS_ERROR_NET_RESET")
|
||||
_created(browser, "u3")
|
||||
assert browser._artifacts["u3"].reports == ["NS_ERROR_NET_RESET"]
|
||||
|
||||
|
||||
def test_a_download_announced_and_then_finished_is_finished(browser):
|
||||
_created(browser, "u4")
|
||||
artifact = browser._artifacts["u4"]
|
||||
assert not artifact.finished.is_set()
|
||||
_finished(browser, "u4")
|
||||
assert artifact.finished.wait(2)
|
||||
assert artifact.reports == [None]
|
||||
assert browser._finished_early == {}
|
||||
|
||||
|
||||
def test_a_download_announced_and_not_finished_stays_open(browser):
|
||||
_created(browser, "u5")
|
||||
assert not browser._artifacts["u5"].finished.is_set()
|
||||
assert browser._finished_early == {}
|
||||
|
||||
|
||||
def test_an_early_finish_of_a_context_that_does_not_exist_is_not_kept(browser):
|
||||
_finished(browser, "u6")
|
||||
assert "u6" in browser._finished_early
|
||||
_created(browser, "u6", context="gone")
|
||||
assert "u6" not in browser._artifacts
|
||||
assert browser._finished_early == {}
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Tiny downloads through a served browser are saved by a stock client, every one.
|
||||
|
||||
A download of a few bytes ends in the engine before the server has handled its announcement, so the server meets
|
||||
`Browser.downloadFinished` first. A download that succeeded has no error, and the old code read "finished with no
|
||||
error" as "nothing recorded": the artifact was never marked finished and `save_as` waited forever.
|
||||
|
||||
One served browser, a stock Playwright client, a page that links to a 300-byte attachment and to a 1-byte one:
|
||||
ten downloads of each, each saved and compared byte for byte.
|
||||
|
||||
Known-bad input: the server before the fix -> a `save_as` of an early-finished download never returns.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import http.server
|
||||
import importlib
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
BODIES = {"big": bytes(range(256)) + b"\x01" * 44, "one": b"Z"}
|
||||
COUNT = 10
|
||||
|
||||
|
||||
def _serve():
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
kind = self.path.strip("/").split("/")[0].split("?")[0]
|
||||
if kind in BODIES:
|
||||
body = BODIES[kind]
|
||||
self.send_response(200)
|
||||
self.send_header("content-type", "application/octet-stream")
|
||||
self.send_header("content-disposition", 'attachment; filename="%s.bin"' % kind)
|
||||
self.send_header("content-length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return
|
||||
links = "".join('<a id="%s%d" href="/%s?n=%d">%s</a> ' % (k, i, k, i, k)
|
||||
for k in BODIES for i in range(COUNT))
|
||||
page = ("<!doctype html><title>d</title>" + links).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("content-type", "text/html")
|
||||
self.send_header("content-length", str(len(page)))
|
||||
self.end_headers()
|
||||
self.wfile.write(page)
|
||||
|
||||
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
|
||||
srv.daemon_threads = True
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
return srv, "http://127.0.0.1:%d/" % srv.server_address[1]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def served():
|
||||
srv, url = _serve()
|
||||
try:
|
||||
yield url
|
||||
finally:
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
|
||||
|
||||
def test_ten_tiny_downloads_of_each_size_are_saved_through_a_served_browser(firefox_binary, served, tmp_path):
|
||||
try: # the stock client (a pinned dev dependency), imported by name: the fork's guard forbids a static import
|
||||
sync_playwright = importlib.import_module("playwright.sync_api").sync_playwright
|
||||
except ImportError as exc:
|
||||
pytest.fail("the stock Playwright client is missing (%s): install the wrapper with its dev extra" % exc,
|
||||
pytrace=False)
|
||||
from invisible_playwright._juggler.remote import launch_server
|
||||
|
||||
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.firefox.connect(server.ws_endpoint)
|
||||
try:
|
||||
page = browser.new_context(accept_downloads=True).new_page()
|
||||
page.goto(served, timeout=30_000)
|
||||
for kind, body in BODIES.items():
|
||||
for i in range(COUNT):
|
||||
with page.expect_download(timeout=20_000) as info:
|
||||
page.click("#%s%d" % (kind, i))
|
||||
target = tmp_path / ("%s%d.bin" % (kind, i))
|
||||
info.value.save_as(target)
|
||||
assert target.read_bytes() == body, (kind, i)
|
||||
assert info.value.failure() is None
|
||||
finally:
|
||||
browser.close()
|
||||
finally:
|
||||
server.close()
|
||||
Reference in new issue
Block a user