A page's number in the session follows the call, not the engine (#291)
This commit is contained in:
1 parent
b35a837c50
commit
b29531d643
13 files changed
+824
-92
No files matched your search
@@ -28,6 +28,19 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
with a page script whose source names Playwright, which any page can read,
|
||||
so it is refused with a sentence saying why. Routes work with service
|
||||
workers allowed.
|
||||
- **A seed replays which tab has which rhythm, with the async API too.**
|
||||
Every page draws its pauses, keys, clicks, drags and cursor paths under its
|
||||
number in the session. The server counted those numbers in the order the
|
||||
engine answered, so `asyncio.gather(browser.new_page(), browser.new_page())`
|
||||
gave the first call number 1 in 4 runs out of 10, and a popup took the next
|
||||
number too, so a `new_page()` gathered with the click that opens one could
|
||||
take the popup's. The cursor counted a third time, at each page's first
|
||||
movement. The client now reserves the number at the call and the server
|
||||
takes it from the request; a popup is numbered from its opener and its rank
|
||||
among that opener's popups, in a space of its own; the cursor reads the
|
||||
page's number from the page. Pages created one after the other keep the
|
||||
numbers they had (0, 1, 2); a `new_page()` after a popup no longer counts
|
||||
the popup, and popups draw new rhythms.
|
||||
|
||||
## [0.25.12] - 2026-10-04
|
||||
|
||||
|
||||
@@ -83,7 +83,6 @@ from __future__ import annotations
|
||||
|
||||
import math
|
||||
import random
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
from typing import (Any, Callable, Dict, Iterable, List, Optional, Sequence,
|
||||
Tuple)
|
||||
@@ -96,8 +95,8 @@ __all__ = [
|
||||
"plan_hesitation",
|
||||
"plan_click",
|
||||
"act_nonce",
|
||||
"popup_number",
|
||||
"PageActs",
|
||||
"SessionActs",
|
||||
"PlanStats",
|
||||
"initial_pointer",
|
||||
"landing_point",
|
||||
@@ -161,6 +160,27 @@ def act_nonce(page: int, n: int) -> int:
|
||||
return (int(page) << 32) | (int(n) & 0xFFFFFFFF)
|
||||
|
||||
|
||||
def popup_number(opener: Optional[int], k: int) -> int:
|
||||
"""The number of the `k`-th page (1, 2, ...) the SITE opened from the page
|
||||
numbered `opener`, or, with `opener` None, the `k`-th one of the session
|
||||
whose opener is not a page we know.
|
||||
|
||||
⛔ A SEPARATE SPACE FROM THE PAGES THE SCRIPT ASKS FOR, and that is the
|
||||
point. Those are numbered 0, 1, 2 by the client in the order of the calls;
|
||||
a popup arrives when the engine says so, which no script controls, so a
|
||||
popup drawing from the same count would push every later `new_page()` one
|
||||
number further whenever it happened to land first (measured: an
|
||||
`asyncio.gather` of a click that opens a popup and a `new_page()`). Keyed
|
||||
by its opener and its rank among that opener's popups, a popup has a
|
||||
number its own script decides: the second popup the first page opened.
|
||||
|
||||
Bit 62 set and a 62-bit hash below it: never one of the client's small
|
||||
numbers, and two popups collide with odds of 2**-62.
|
||||
"""
|
||||
tag = "popup:%s:%d" % ("-" if opener is None else int(opener), int(k))
|
||||
return (1 << 62) | (_sub_seed(0, tag) & ((1 << 62) - 1))
|
||||
|
||||
|
||||
class PageActs:
|
||||
"""Numbers the acts of one page, so no two acts of a session share a stream.
|
||||
|
||||
@@ -170,9 +190,19 @@ class PageActs:
|
||||
of every tab waited the same pause and was typed with the same intervals,
|
||||
and the first click of every tab was held for the same time. A site that
|
||||
sees two tabs of one session saw the same numbers twice. The page's
|
||||
number, handed out once by the session (`SessionActs`), is now part of
|
||||
every nonce, which is what the client's cursor already did with its page
|
||||
ordinal (`_cursor.page_motion_seed`).
|
||||
number is now part of every nonce, which is what the client's cursor
|
||||
already did with its page ordinal (`_cursor.page_motion_seed`).
|
||||
|
||||
⛔ AND THE NUMBER IS GIVEN, NEVER COUNTED HERE. A page the script asks for
|
||||
carries the number the client reserved at the CALL (`Browser.
|
||||
_reserve_page_number` in the vendored client), a popup the one
|
||||
`popup_number` derives; the server's `PageDispatcher` holds it and hands
|
||||
it to the client in the page's initializer, where the cursor reads it.
|
||||
The server used to count pages itself as their dispatchers were built,
|
||||
and the cursor counted again at each page's first movement: two counters
|
||||
for one fact, and the server's followed the order in which the engine
|
||||
answered, so with `asyncio.gather` the first page of the call was page 1
|
||||
in 4 runs out of 10 ([B237]).
|
||||
|
||||
Reproducible: the same seed and the same acts in the same pages give the
|
||||
same sequence. Per page rather than one count for the whole session for
|
||||
@@ -193,36 +223,6 @@ class PageActs:
|
||||
return act_nonce(self.page, n)
|
||||
|
||||
|
||||
class SessionActs:
|
||||
"""Hands each page of a session its number, 0, 1, 2, in the order asked.
|
||||
|
||||
Owned by whatever object IS the session, never by a module: a process can
|
||||
hold two sessions. Two layers number their pages with it, each holding
|
||||
its own: the server's `BrowserDispatcher`, for the acts it draws, and the
|
||||
client cursor's `_cursor._Session`, for the paths it draws. They cannot
|
||||
hold one object between them: the client's is keyed by the vendored
|
||||
client's objects, which the server never sees, and the seed reaches the
|
||||
server through the launch prefs for that same reason.
|
||||
"""
|
||||
|
||||
__slots__ = ("_pages", "_lock")
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._pages = 0
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def next_page(self) -> int:
|
||||
"""The next page's number."""
|
||||
with self._lock:
|
||||
n = self._pages
|
||||
self._pages += 1
|
||||
return n
|
||||
|
||||
def page(self) -> PageActs:
|
||||
"""The next page, ready to number its acts."""
|
||||
return PageActs(self.next_page())
|
||||
|
||||
|
||||
def _clamp(v: float, lo: float, hi: float) -> float:
|
||||
return lo if v < lo else (hi if v > hi else v)
|
||||
|
||||
|
||||
@@ -369,9 +369,21 @@ def page_motion_seed(session_seed: int, ordinal: int) -> int:
|
||||
in which tabs happened to move. Same session seed plus same tab ordinal
|
||||
gives the same path, which is what makes a replayed seed replay the
|
||||
cursor. Kept inside int31 for consistency with the rest of the seeding.
|
||||
|
||||
⛔ EVERY BIT OF THE ORDINAL COUNTS, not only the low 16. A page the site
|
||||
opened is numbered in a space of its own above bit 62 (`_behaviour.
|
||||
popup_number`), and with the old mask two popups shared a path whenever
|
||||
their numbers agreed on 16 bits. The higher bits are folded in only when
|
||||
there are any, so the pages the script asks for (0, 1, 2 ...) keep the
|
||||
seeds they always had.
|
||||
"""
|
||||
ordinal = int(ordinal)
|
||||
h = (int(session_seed) & 0xFFFFFFFF) * 0x9E3779B1
|
||||
h = (h ^ ((int(ordinal) & 0xFFFF) * 0x85EBCA6B)) & 0xFFFFFFFF
|
||||
h = (h ^ ((ordinal & 0xFFFF) * 0x85EBCA6B)) & 0xFFFFFFFF
|
||||
high = ordinal >> 16
|
||||
while high > 0:
|
||||
h = ((h ^ (high & 0xFFFF)) * 0xC2B2AE35) & 0xFFFFFFFF
|
||||
high >>= 16
|
||||
h ^= h >> 16
|
||||
return h & 0x7FFFFFFF
|
||||
|
||||
@@ -379,17 +391,25 @@ def page_motion_seed(session_seed: int, ordinal: int) -> int:
|
||||
class _Session:
|
||||
"""Everything a session hands to the pages underneath it."""
|
||||
|
||||
__slots__ = ("seed", "max_seconds", "pages")
|
||||
__slots__ = ("seed", "max_seconds")
|
||||
|
||||
def __init__(self, seed: int, max_seconds: float) -> None:
|
||||
self.seed = int(seed)
|
||||
self.max_seconds = float(max_seconds)
|
||||
#: The pages' numbers, by the one counter the server numbers its pages
|
||||
#: with too (`_behaviour.SessionActs`).
|
||||
self.pages = _behaviour.SessionActs()
|
||||
|
||||
def next_ordinal(self) -> int:
|
||||
return self.pages.next_page()
|
||||
|
||||
def page_number(page: Any) -> int:
|
||||
"""The page's number in the session, as the server gave it.
|
||||
|
||||
⛔ READ FROM THE PAGE, NEVER COUNTED HERE. The server sends it in the
|
||||
page's initializer (`PageDispatcher.number`: the number the client
|
||||
reserved at the `new_page()` call, or a popup's derived one), and the
|
||||
server draws the page's acts under it. This cursor used to count its own,
|
||||
at each page's FIRST MOVEMENT: a script that created two pages and moved
|
||||
on the second first gave the second page 0 here and 1 there - two
|
||||
counters for one fact, with two different orders ([B237]).
|
||||
"""
|
||||
return int(page._initializer["pageNumber"])
|
||||
|
||||
|
||||
class _PageCursor:
|
||||
@@ -680,9 +700,10 @@ def _cursor_for_page(page: Any) -> Optional[_PageCursor]:
|
||||
factory = _motion_factory()
|
||||
if factory is None:
|
||||
return None
|
||||
seed = page_motion_seed(session.seed, page_number(page))
|
||||
try:
|
||||
cursor = _PageCursor(
|
||||
page_motion_seed(session.seed, session.next_ordinal()),
|
||||
seed,
|
||||
session.max_seconds,
|
||||
factory,
|
||||
)
|
||||
|
||||
@@ -147,7 +147,7 @@ class Actions:
|
||||
self.motion = CursorMotion(_sub_seed(session_seed, "server:drag"))
|
||||
#: ⛔ THE NONCE OF EVERY ACT OF THIS PAGE, and it is REQUIRED, not
|
||||
#: defaulted. It carries the page's number in the session
|
||||
#: (`_behaviour.SessionActs.page`), so two clicks, two fields or two
|
||||
#: (`PageDispatcher.number`), so two clicks, two fields or two
|
||||
#: typed strings never draw the same durations, not even the first act
|
||||
#: of two different tabs. Bare counters here restarted at 1 on every
|
||||
#: page, and a default would bring that back for whoever forgot to
|
||||
|
||||
@@ -27,6 +27,7 @@ hard failure. Everything here creates first and returns the channel second.
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import contextlib
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
@@ -36,7 +37,7 @@ import time
|
||||
import warnings
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from .._behaviour import SessionActs
|
||||
from .._behaviour import PageActs, popup_number
|
||||
from . import connection as juggler
|
||||
from .actions import Actions
|
||||
from .dispatcher import Dispatcher, ProtocolException, Server
|
||||
@@ -1694,7 +1695,7 @@ class PageDispatcher(Dispatcher):
|
||||
}
|
||||
|
||||
def __init__(self, server, context: "BrowserContextDispatcher",
|
||||
session: str, target_id: str,
|
||||
session: str, target_id: str, number: int,
|
||||
opener: Optional["PageDispatcher"] = None) -> None:
|
||||
self.context = context
|
||||
#: True while `page.route()` holds this page's requests. The context
|
||||
@@ -1703,6 +1704,17 @@ class PageDispatcher(Dispatcher):
|
||||
self.intercepting = False
|
||||
self.session = session
|
||||
self.target_id = target_id
|
||||
#: ⛔ THIS PAGE'S NUMBER IN THE SESSION, GIVEN, NOT COUNTED: the one
|
||||
#: the client reserved at the `new_page()` call, or for a page the
|
||||
#: site opened the one `_behaviour.popup_number` derives from its
|
||||
#: opener (see `BrowserDispatcher._spawn_adoption`). Every act of the
|
||||
#: page draws under it, and it travels to the client in the
|
||||
#: initializer so the cursor draws under the same one.
|
||||
self.number = number
|
||||
#: How many pages the site has opened from this one, which is the
|
||||
#: rank of the next one among them. Moved only under the browser's
|
||||
#: `_targets_lock`, on the reader thread, in the engine's order.
|
||||
self.popups_opened = 0
|
||||
# ⛔ The once-guard for `announce_closed` lives under this lock, not
|
||||
# in a bare attribute: the close arrives on up to four threads
|
||||
# (`op_close`, the reader's detach, an adoption finishing early, a
|
||||
@@ -1755,7 +1767,7 @@ class PageDispatcher(Dispatcher):
|
||||
"""The rest of the construction, under `__init__`'s cleanup."""
|
||||
self.injected.install()
|
||||
self.actions = context.browser.actions_for_page(
|
||||
session, self.lifecycle, self.injected)
|
||||
session, self.lifecycle, self.injected, self.number)
|
||||
# ⛔ THE EVENTS THIS PAGE ALREADY MISSED, handed over now that the two
|
||||
# things that need them exist. `Page.frameAttached` and the
|
||||
# `Runtime.executionContextCreated` pair are sent by the browser BEFORE
|
||||
@@ -1797,8 +1809,12 @@ class PageDispatcher(Dispatcher):
|
||||
self.frame = FrameDispatcher(server, self, self.main_frame_id)
|
||||
viewport = context.options.get("viewport") or {"width": 1280,
|
||||
"height": 720}
|
||||
# `pageNumber` is ours, not Playwright's: the cursor reads it
|
||||
# (`_cursor._cursor_for_page`), so client and server draw one page's
|
||||
# rhythms under one number.
|
||||
initializer = {"mainFrame": self.frame.channel,
|
||||
"viewportSize": viewport, "isClosed": False}
|
||||
"viewportSize": viewport, "isClosed": False,
|
||||
"pageNumber": self.number}
|
||||
if opener is not None:
|
||||
# ⛔ THE OPENER TRAVELS IN THE INITIALIZER, and nowhere else. The
|
||||
# client resolves `page.opener()` from it and emits `popup` on the
|
||||
@@ -3124,11 +3140,25 @@ class BrowserContextDispatcher(Dispatcher):
|
||||
the `PageDispatcher` for all of them, so a target can never be built
|
||||
twice (once by this call, once by the event) and a `window.open`
|
||||
target is a page like any other, with its opener recorded.
|
||||
|
||||
⛔ AND IT DOES NOT NUMBER THE PAGE EITHER: the number arrives with the
|
||||
request (`pageNumber`, reserved by the client at the call) and is
|
||||
handed to the adoption through `BrowserDispatcher._asking`. Required,
|
||||
not defaulted: a server-side default is the second counter [B237]
|
||||
removed.
|
||||
"""
|
||||
conn = self.conn
|
||||
result = conn.send("Browser.newPage",
|
||||
_address(self.context_id, {}), timeout=30)
|
||||
page = self.browser._wait_for_page(result["targetId"], timeout=60.0)
|
||||
number = params.get("pageNumber")
|
||||
if type(number) is not int or number < 0:
|
||||
raise ProtocolException(
|
||||
"newPage needs the page's number in the session "
|
||||
"(pageNumber), reserved by the client at the call; got %r"
|
||||
% (number,))
|
||||
browser = self.browser
|
||||
with browser._asking(self.context_id) as answered:
|
||||
result = self.conn.send("Browser.newPage",
|
||||
_address(self.context_id, {}), timeout=30)
|
||||
answered(result["targetId"], number)
|
||||
page = browser._wait_for_page(result["targetId"], timeout=60.0)
|
||||
return {"page": page.channel}
|
||||
|
||||
# ── cookies, permissions, geolocation ───────────────────────────────────
|
||||
@@ -3274,12 +3304,6 @@ class BrowserDispatcher(Dispatcher):
|
||||
#: downstream reads that as "no rhythm" rather than as a default one.
|
||||
self.session_seed = session_seed
|
||||
self.motion_budget_s = motion_budget_s
|
||||
#: ⛔ THE NUMBER OF EACH PAGE, handed out here for the same reason the
|
||||
#: seed lives here: it belongs to the session, and every context of
|
||||
#: this browser is the same person. Each page's acts draw their nonces
|
||||
#: under its number (`_behaviour.PageActs`), so the first field, key
|
||||
#: and click of a second tab are not the first tab's again.
|
||||
self.acts = SessionActs()
|
||||
self._sessions: Dict[str, str] = {}
|
||||
self._sessions_ready = threading.Condition()
|
||||
# ⛔ THE EVENTS OF A SESSION START BEFORE ANYBODY IS LISTENING, and
|
||||
@@ -3343,6 +3367,19 @@ class BrowserDispatcher(Dispatcher):
|
||||
#: Ending the page - registries, session, listeners - is
|
||||
#: `announce_closed`'s job alone: see `_page_over`.
|
||||
self._detached_early: set = set()
|
||||
#: ⛔ HOW A NEW TARGET LEARNS ITS PAGE NUMBER (see `_spawn_adoption`).
|
||||
#: `Browser.newPage` requests sent and not yet answered, by context;
|
||||
#: and the number each answered request named for its target, until
|
||||
#: that target's adoption takes it. Juggler emits `attachedToTarget`
|
||||
#: BEFORE it answers `newPage` (`TargetRegistry.newPage` waits for the
|
||||
#: target to exist), so an adoption cannot know its number at attach
|
||||
#: and waits for the answer - but only while an answer is pending.
|
||||
self._unanswered: Dict[Optional[str], int] = {}
|
||||
self._answered_numbers: Dict[str, int] = {}
|
||||
#: Pages the site opened whose opener is not a page we know (a
|
||||
#: `noopener` window has no opener in the engine either): the rank of
|
||||
#: the last one, in a space of their own (`_behaviour.popup_number`).
|
||||
self._strays = 0
|
||||
self._pages_ready = threading.Condition(self._targets_lock)
|
||||
self._adopt_enabled = False
|
||||
# ⛔ THIS ONE RUNS FIRST NOW, WHERE THE CHAIN RAN IT LAST, and the
|
||||
@@ -3382,15 +3419,63 @@ class BrowserDispatcher(Dispatcher):
|
||||
"so every request would go out unseen. Drop the pref: routes "
|
||||
"work with service workers enabled" % what)
|
||||
|
||||
def actions_for_page(self, session: str, lifecycle, injected) -> Actions:
|
||||
def actions_for_page(self, session: str, lifecycle, injected,
|
||||
number: int) -> Actions:
|
||||
"""The hands of a new page: the session's seed and motion budget, and
|
||||
the page's number in the session, which goes into the nonce of every
|
||||
act it performs. Built here because all three are the session's."""
|
||||
act it performs. The number is the page's own (`PageDispatcher.
|
||||
number`); nothing here counts pages."""
|
||||
return Actions(self.conn, session, lifecycle, injected,
|
||||
acts=self.acts.page(),
|
||||
acts=PageActs(number),
|
||||
session_seed=self.session_seed,
|
||||
motion_budget_s=self.motion_budget_s)
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _asking(self, context_id: Optional[str]):
|
||||
"""One `Browser.newPage` request in flight for `context_id`, for the
|
||||
span of the block. The block calls the yielded function with the
|
||||
target the engine answered and the number the client gave; leaving
|
||||
the block without it (the request failed) still ends the request, so
|
||||
an adoption waiting on it learns it was not this one."""
|
||||
with self._targets_lock:
|
||||
self._unanswered[context_id] = self._unanswered.get(context_id, 0) + 1
|
||||
answer: List = []
|
||||
try:
|
||||
yield lambda target_id, number: answer.append((target_id, number))
|
||||
finally:
|
||||
with self._targets_lock:
|
||||
left = self._unanswered.get(context_id, 1) - 1
|
||||
if left:
|
||||
self._unanswered[context_id] = left
|
||||
else:
|
||||
self._unanswered.pop(context_id, None)
|
||||
for target_id, number in answer:
|
||||
self._answered_numbers[target_id] = number
|
||||
self._pages_ready.notify_all()
|
||||
|
||||
def _number_of_requested(self, target_id: str,
|
||||
browser_context_id: Optional[str],
|
||||
timeout: float) -> int:
|
||||
"""The number of a target that attached while a `newPage` of its
|
||||
context was unanswered: the number that request named for it, or -
|
||||
once every request of the context is answered and none named it - a
|
||||
page the site opened, numbered as a stray."""
|
||||
deadline = time.monotonic() + timeout
|
||||
with self._pages_ready:
|
||||
while True:
|
||||
number = self._answered_numbers.pop(target_id, None)
|
||||
if number is not None:
|
||||
return number
|
||||
if not self._unanswered.get(browser_context_id):
|
||||
self._strays += 1
|
||||
return popup_number(None, self._strays)
|
||||
left = deadline - time.monotonic()
|
||||
if left <= 0:
|
||||
raise ProtocolException(
|
||||
"target %s attached while a newPage was in flight, "
|
||||
"and no answer named it in %.0fs" % (target_id, timeout))
|
||||
self._pages_ready.wait(left)
|
||||
|
||||
def _route_browser_event(self, method: str, params: Dict, session) -> None:
|
||||
if method == "Browser.attachedToTarget":
|
||||
info = params.get("targetInfo") or {}
|
||||
@@ -3461,22 +3546,46 @@ class BrowserDispatcher(Dispatcher):
|
||||
def _spawn_adoption(self, target_id: str, session_id: Optional[str],
|
||||
browser_context_id: Optional[str],
|
||||
opener_id: Optional[str]) -> None:
|
||||
"""Claim a fresh engine target and build its page off the reader thread."""
|
||||
"""Claim a fresh engine target and build its page off the reader thread.
|
||||
|
||||
⛔ AND DECIDE HOW IT IS NUMBERED HERE, ON THE READER THREAD, because
|
||||
this is the only place that sees the targets in the engine's order;
|
||||
each adoption then builds on a thread of its own, in no order at all.
|
||||
A target with a known opener is that opener's next popup; one that
|
||||
some `newPage` answer named, or may still name, takes the number that
|
||||
request carried (`_number_of_requested`); anything else is a page the
|
||||
site opened with no opener we know, the session's next stray. The
|
||||
popups' numbers live in a space of their own (`_behaviour.
|
||||
popup_number`), so a popup landing between two `new_page()` calls
|
||||
does not shift the second one's number.
|
||||
"""
|
||||
with self._targets_lock:
|
||||
if not self._adopt_enabled:
|
||||
return
|
||||
if target_id in self._page_targets or target_id in self._adopting:
|
||||
return
|
||||
self._adopting.add(target_id)
|
||||
opener = self._page_targets.get(opener_id) if opener_id else None
|
||||
if opener is not None:
|
||||
opener.popups_opened += 1
|
||||
number: Optional[int] = popup_number(opener.number,
|
||||
opener.popups_opened)
|
||||
elif (target_id in self._answered_numbers
|
||||
or self._unanswered.get(browser_context_id)):
|
||||
number = None
|
||||
else:
|
||||
self._strays += 1
|
||||
number = popup_number(None, self._strays)
|
||||
thread = threading.Thread(
|
||||
target=self._adopt_target,
|
||||
args=(target_id, session_id, browser_context_id, opener_id),
|
||||
args=(target_id, session_id, browser_context_id, opener, number),
|
||||
daemon=True, name="invpw-adopt-%s" % target_id[:8])
|
||||
thread.start()
|
||||
|
||||
def _adopt_target(self, target_id: str, session_id: Optional[str],
|
||||
browser_context_id: Optional[str],
|
||||
opener_id: Optional[str]) -> None:
|
||||
opener: Optional[PageDispatcher],
|
||||
number: Optional[int]) -> None:
|
||||
"""Build the `PageDispatcher` for one engine target, then announce it.
|
||||
|
||||
A popup goes through EXACTLY the same construction as a `newPage`
|
||||
@@ -3485,12 +3594,13 @@ class BrowserDispatcher(Dispatcher):
|
||||
how it was opened. Stealth is preserved by doing nothing special.
|
||||
"""
|
||||
try:
|
||||
if number is None:
|
||||
number = self._number_of_requested(
|
||||
target_id, browser_context_id, timeout=60.0)
|
||||
session = session_id or self.session_for(target_id, timeout=20.0)
|
||||
context = self._context_for_popup(browser_context_id)
|
||||
with self._targets_lock:
|
||||
opener = self._page_targets.get(opener_id) if opener_id else None
|
||||
page = PageDispatcher(self.server, context, session, target_id,
|
||||
opener=opener)
|
||||
number, opener=opener)
|
||||
# ⛔ `page` BEFORE the registration, on purpose. A detach racing
|
||||
# this build is recorded as early (see `_handle_detach`) and the
|
||||
# close is announced right after, so the client always sees the
|
||||
@@ -3837,9 +3947,11 @@ class BrowserDispatcher(Dispatcher):
|
||||
return {"context": context.channel}
|
||||
|
||||
def op_new_page(self, params: Dict) -> Any:
|
||||
params = dict(params)
|
||||
number = params.pop("pageNumber", None)
|
||||
context = self.op_new_context(params)
|
||||
guid = context["context"]["guid"]
|
||||
return self.server.object(guid).op_new_page({})
|
||||
return self.server.object(guid).op_new_page({"pageNumber": number})
|
||||
|
||||
def op_close(self, params: Dict) -> Any:
|
||||
try:
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import itertools
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import (
|
||||
@@ -36,7 +37,10 @@ from invisible_playwright._pw._impl._api_structures import (
|
||||
ViewportSize,
|
||||
)
|
||||
from invisible_playwright._pw._impl._artifact import Artifact
|
||||
from invisible_playwright._pw._impl._browser_context import BrowserContext
|
||||
from invisible_playwright._pw._impl._browser_context import (
|
||||
BrowserContext,
|
||||
page_number_for_call,
|
||||
)
|
||||
from invisible_playwright._pw._impl._cdp_session import CDPSession
|
||||
from invisible_playwright._pw._impl._connection import ChannelOwner, from_channel
|
||||
from invisible_playwright._pw._impl._errors import is_target_closed_error
|
||||
@@ -73,6 +77,13 @@ class Browser(ChannelOwner):
|
||||
self._cr_tracing_path: Optional[str] = None
|
||||
|
||||
self._contexts: Set[BrowserContext] = set()
|
||||
# MODIFIED by invisible_playwright: the numbers of the pages the
|
||||
# script asks for, 0, 1, 2, in the order of the calls. The ONLY counter
|
||||
# of them: the server takes each from its `newPage` request, and the
|
||||
# cursor reads it back from the page (`page_number_for_call` in
|
||||
# `_browser_context.py`). Pages the site opens are numbered by the
|
||||
# server, in a space of their own (`_behaviour.popup_number`).
|
||||
self._page_numbers = itertools.count()
|
||||
self._traces_dir: Optional[str] = None
|
||||
self._channel.on(
|
||||
"context",
|
||||
@@ -112,6 +123,10 @@ class Browser(ChannelOwner):
|
||||
assert self._browser_type is not None
|
||||
self._browser_type._playwright.selectors._contexts_for_selectors.add(context)
|
||||
|
||||
def _reserve_page_number(self) -> int:
|
||||
# MODIFIED by invisible_playwright: see `_page_numbers`.
|
||||
return next(self._page_numbers)
|
||||
|
||||
def _on_close(self) -> None:
|
||||
self._is_connected = False
|
||||
self.emit(Browser.Events.Disconnected, self)
|
||||
@@ -222,10 +237,14 @@ class Browser(ChannelOwner):
|
||||
clientCertificates: List[ClientCertificate] = None,
|
||||
) -> Page:
|
||||
params = locals_to_params(locals())
|
||||
# MODIFIED by invisible_playwright: reserved before the first await,
|
||||
# so the page's number follows this call and not the order in which
|
||||
# the engine answers its `newContext`.
|
||||
number = page_number_for_call(self)
|
||||
|
||||
async def inner() -> Page:
|
||||
context = await self.new_context(**params)
|
||||
page = await context.new_page()
|
||||
page = await context._new_page(number)
|
||||
page._owned_context = context
|
||||
context._owner_page = page
|
||||
return page
|
||||
|
||||
@@ -14,6 +14,8 @@
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import (
|
||||
@@ -21,6 +23,7 @@ from typing import (
|
||||
Any,
|
||||
Callable,
|
||||
Dict,
|
||||
Iterator,
|
||||
List,
|
||||
Literal,
|
||||
Optional,
|
||||
@@ -88,6 +91,48 @@ if TYPE_CHECKING: # pragma: no cover
|
||||
from invisible_playwright._pw._impl._browser import Browser
|
||||
|
||||
|
||||
# MODIFIED by invisible_playwright: each page the script asks for carries a
|
||||
# number in the session, and every rhythm the page draws (the pause before a
|
||||
# field, the keys, the clicks, the cursor's paths) is drawn under it. The
|
||||
# number is reserved HERE, on the client, at the moment of the call, because
|
||||
# that is the only place the order of the calls exists: by the time a request
|
||||
# reaches the server, `browser.new_page()` has already waited for its
|
||||
# `newContext` answer, so two of them in an `asyncio.gather` arrive in the
|
||||
# order the engine answered - the first call was page 1 in 4 runs out of 10,
|
||||
# measured on firefox-35 ([B237]). The server takes the number it is given;
|
||||
# it no longer counts.
|
||||
#
|
||||
# A caller above this layer that can WAIT before reaching it (the wrapper
|
||||
# checks the proxy's egress first, and only the first call of a burst
|
||||
# actually waits for that check) reserves at its own entry instead, with
|
||||
# `page_number_reserved`; the number then reaches this layer through the
|
||||
# context variable, so whoever is outermost owns the moment of the call.
|
||||
_reserved_page_number: "ContextVar[Optional[int]]" = ContextVar(
|
||||
"invisible_playwright_page_number", default=None)
|
||||
|
||||
|
||||
def page_number_for_call(browser: "Browser") -> int:
|
||||
"""The number of the page this call creates: the one a caller above
|
||||
reserved for it, or the browser's next one."""
|
||||
number = _reserved_page_number.get()
|
||||
if number is not None:
|
||||
_reserved_page_number.set(None)
|
||||
return number
|
||||
return browser._reserve_page_number()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def page_number_reserved(browser: "Browser") -> Iterator[int]:
|
||||
"""Reserve the next page number now, for the page the call inside this
|
||||
block creates."""
|
||||
number = browser._reserve_page_number()
|
||||
token = _reserved_page_number.set(number)
|
||||
try:
|
||||
yield number
|
||||
finally:
|
||||
_reserved_page_number.reset(token)
|
||||
|
||||
|
||||
class BrowserContext(ChannelOwner):
|
||||
Events = SimpleNamespace(
|
||||
# Deprecated in v1.56, never emitted anymore.
|
||||
@@ -349,7 +394,13 @@ class BrowserContext(ChannelOwner):
|
||||
async def new_page(self) -> Page:
|
||||
if self._owner_page:
|
||||
raise Error("Please use browser.new_context()")
|
||||
return from_channel(await self._channel.send("newPage", None))
|
||||
return await self._new_page(page_number_for_call(self._browser))
|
||||
|
||||
async def _new_page(self, number: int) -> Page:
|
||||
# MODIFIED by invisible_playwright: the page's number in the session
|
||||
# travels with the request (see `page_number_for_call`).
|
||||
return from_channel(
|
||||
await self._channel.send("newPage", None, {"pageNumber": number}))
|
||||
|
||||
async def cookies(self, urls: Union[str, Sequence[str]] = None) -> List[Cookie]:
|
||||
if urls is None:
|
||||
|
||||
@@ -8,6 +8,7 @@ from pathlib import Path
|
||||
from typing import Any, Dict, Optional, Union
|
||||
|
||||
from invisible_playwright._pw.async_api import Browser, BrowserContext, Playwright, async_playwright
|
||||
from invisible_playwright._pw._impl._browser_context import page_number_reserved
|
||||
|
||||
from . import _session
|
||||
from ._cursor import resolve_cursor_engine
|
||||
@@ -267,8 +268,14 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
_new_page_ctx = ctx.new_page
|
||||
|
||||
async def _new_page_guarded(**kw2):
|
||||
await self._assert_uscita_invariata()
|
||||
return await _new_page_ctx(**kw2)
|
||||
# ⛔ THE PAGE'S NUMBER IS RESERVED BEFORE THE CHECK, because
|
||||
# the check is the one await in front of the page: only the
|
||||
# first call of a burst waits for it, so in a gather the
|
||||
# second call would reach the client first and take the
|
||||
# first call's number ([B237]).
|
||||
with page_number_reserved(ctx._impl_obj._browser):
|
||||
await self._assert_uscita_invariata()
|
||||
return await _new_page_ctx(**kw2)
|
||||
|
||||
ctx.new_page = _new_page_guarded # type: ignore[assignment]
|
||||
return ctx
|
||||
@@ -278,10 +285,12 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
original_page = browser.new_page
|
||||
|
||||
async def patched_page(**kw):
|
||||
await self._assert_uscita_invariata()
|
||||
merged = dict(defaults)
|
||||
merged.update(kw) # user-supplied wins, same rule as new_context
|
||||
page = await original_page(**merged)
|
||||
# Reserved before the check, for `_new_page_guarded`'s reason.
|
||||
with page_number_reserved(browser._impl_obj):
|
||||
await self._assert_uscita_invariata()
|
||||
merged = dict(defaults)
|
||||
merged.update(kw) # user-supplied wins, same rule as new_context
|
||||
page = await original_page(**merged)
|
||||
ctx = page.context
|
||||
if prep:
|
||||
from ._recaptcha_seed import seed_recaptcha_cookies_async
|
||||
|
||||
@@ -86,8 +86,11 @@ class _FakeBrowser:
|
||||
|
||||
|
||||
class _FakePage:
|
||||
def __init__(self, context, width=1280, height=720):
|
||||
def __init__(self, context, width=1280, height=720, number=0):
|
||||
self._browser_context = context
|
||||
# The page's number in the session, as the server's initializer
|
||||
# carries it (`_cursor.page_number`).
|
||||
self._initializer = {"pageNumber": number}
|
||||
self._viewport_size = {"width": width, "height": height}
|
||||
self.moves = []
|
||||
self.wheels = []
|
||||
|
||||
@@ -125,8 +125,11 @@ class _FakeContext:
|
||||
|
||||
|
||||
class _FakePage:
|
||||
def __init__(self, context, width=1280, height=720):
|
||||
def __init__(self, context, width=1280, height=720, number=0):
|
||||
self._browser_context = context
|
||||
# The page's number in the session, as the server's initializer
|
||||
# carries it (`_cursor.page_number`).
|
||||
self._initializer = {"pageNumber": number}
|
||||
self._viewport_size = {"width": width, "height": height}
|
||||
self.moves = []
|
||||
self.wheels = []
|
||||
@@ -371,13 +374,57 @@ def test_each_page_gets_its_own_stream(stub_motion):
|
||||
browser = _FakeBrowser()
|
||||
_cursor.enable_for(browser, seed=999, max_seconds=1.0)
|
||||
ctx = _FakeContext(browser)
|
||||
a = _cursor._cursor_for_page(_FakePage(ctx))
|
||||
b = _cursor._cursor_for_page(_FakePage(ctx))
|
||||
a = _cursor._cursor_for_page(_FakePage(ctx, number=0))
|
||||
b = _cursor._cursor_for_page(_FakePage(ctx, number=1))
|
||||
assert a.seed != b.seed, "two tabs sharing one stream would couple their paths"
|
||||
assert a.seed == _cursor.page_motion_seed(999, 0)
|
||||
assert b.seed == _cursor.page_motion_seed(999, 1)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_page_moved_first_keeps_the_number_the_server_gave_it(stub_motion):
|
||||
"""[B237], second half. Known-bad, before: the cursor counted pages at
|
||||
their FIRST MOVEMENT, so a script that opened p0 and p1 and moved on p1
|
||||
first gave p1 ordinal 0 here while the server, numbering at creation,
|
||||
gave it 1 - one page, two numbers, two layers drawing apart. Now the
|
||||
cursor reads the number the server put in the page's initializer."""
|
||||
browser = _FakeBrowser()
|
||||
_cursor.enable_for(browser, seed=999, max_seconds=1.0)
|
||||
ctx = _FakeContext(browser)
|
||||
p0, p1 = _FakePage(ctx, number=0), _FakePage(ctx, number=1)
|
||||
second = _cursor._cursor_for_page(p1)
|
||||
first = _cursor._cursor_for_page(p0)
|
||||
assert second.seed == _cursor.page_motion_seed(999, 1)
|
||||
assert first.seed == _cursor.page_motion_seed(999, 0)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_motion_seed_reads_every_bit_of_the_page_number():
|
||||
"""A page the site opened is numbered above bit 62
|
||||
(`_behaviour.popup_number`); with the old 16-bit mask two such numbers
|
||||
that agreed on their low 16 bits drew the same paths. The pages the
|
||||
script asks for keep the seeds they had: the values below are the old
|
||||
formula's."""
|
||||
from invisible_playwright._behaviour import popup_number
|
||||
|
||||
def old(seed, ordinal):
|
||||
h = (seed & 0xFFFFFFFF) * 0x9E3779B1
|
||||
h = (h ^ ((ordinal & 0xFFFF) * 0x85EBCA6B)) & 0xFFFFFFFF
|
||||
h ^= h >> 16
|
||||
return h & 0x7FFFFFFF
|
||||
|
||||
for seed in (0, 1, 106, 999, 2**31 - 1):
|
||||
for ordinal in (0, 1, 2, 7, 65535):
|
||||
assert _cursor.page_motion_seed(seed, ordinal) == old(seed, ordinal)
|
||||
a = (1 << 62) | 0x1234
|
||||
b = (1 << 62) | (1 << 40) | 0x1234
|
||||
assert _cursor.page_motion_seed(106, a) != _cursor.page_motion_seed(106, b)
|
||||
popups = {_cursor.page_motion_seed(106, popup_number(o, k))
|
||||
for o in (None, 0, 1) for k in range(1, 6)}
|
||||
assert len(popups) == 15
|
||||
assert all(0 <= s < 2**31 for s in popups)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_page_motion_seed_is_stable_and_in_range():
|
||||
assert _cursor.page_motion_seed(42, 0) == _cursor.page_motion_seed(42, 0)
|
||||
|
||||
@@ -10,8 +10,9 @@ Measured on 0.25.8 with seed 106 and three tabs: a pause of 2.14-2.16 s on all
|
||||
three, and keydown intervals within a few milliseconds of each other. A site
|
||||
that sees two tabs of one session saw the same numbers twice.
|
||||
|
||||
The page's number now comes from the session (`BrowserDispatcher.acts`) and is
|
||||
part of every nonce. The same seed still gives the same sequence: replaying a
|
||||
The page's number now comes with the page (`PageDispatcher.number`: the number
|
||||
the client reserved at the `new_page()` call, [B237]) and is part of every
|
||||
nonce. The same seed still gives the same sequence: replaying a
|
||||
session replays its acts.
|
||||
|
||||
The unit half builds pages the way the server does, through
|
||||
@@ -65,8 +66,8 @@ def _browser(seed=SEED):
|
||||
session_seed=seed)
|
||||
|
||||
|
||||
def _page(browser):
|
||||
return browser.actions_for_page("session", None, _Field())
|
||||
def _page(browser, number):
|
||||
return browser.actions_for_page("session", None, _Field(), number)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
@@ -92,8 +93,8 @@ def test_the_first_acts_of_two_pages_are_two_different_draws(clock):
|
||||
"""Known-bad, before: the second page's first field, string and click
|
||||
drew exactly what the first page's did."""
|
||||
browser = _browser()
|
||||
one = _first_acts(_page(browser), clock)
|
||||
two = _first_acts(_page(browser), clock)
|
||||
one = _first_acts(_page(browser, 0), clock)
|
||||
two = _first_acts(_page(browser, 1), clock)
|
||||
assert one["pause"] != two["pause"]
|
||||
assert one["typing"] != two["typing"]
|
||||
assert one["click"] != two["click"]
|
||||
@@ -105,16 +106,16 @@ def test_the_same_seed_replays_the_same_sequence_across_pages(clock):
|
||||
runs = []
|
||||
for _ in range(2):
|
||||
browser = _browser()
|
||||
runs.append([_first_acts(_page(browser), clock) for _ in range(3)])
|
||||
runs.append([_first_acts(_page(browser, n), clock) for n in range(3)])
|
||||
assert runs[0] == runs[1]
|
||||
assert runs[0] != [_first_acts(_page(_browser(SEED + 1)), clock)
|
||||
for _ in range(3)]
|
||||
other = _browser(SEED + 1)
|
||||
assert runs[0] != [_first_acts(_page(other, n), clock) for n in range(3)]
|
||||
|
||||
|
||||
def test_the_first_page_keeps_the_plain_count(clock):
|
||||
"""The first field of a session is nonce 1 on the first page: the page
|
||||
number goes in the high bits, so page 0 keeps the plain count."""
|
||||
a = _page(_browser())
|
||||
a = _page(_browser(), 0)
|
||||
assert _first_acts(a, clock)["pause"] == pytest.approx(
|
||||
plan_hesitation(TypingPersona.from_seed(SEED), "field", 1) / 1000.0)
|
||||
|
||||
@@ -123,7 +124,7 @@ def test_the_keyboard_and_the_drag_number_their_acts_on_the_page():
|
||||
"""One numbering per page: the keyboard holds the page's, not one of its
|
||||
own, and the pages of one session are numbered apart."""
|
||||
browser = _browser()
|
||||
a, b = _page(browser), _page(browser)
|
||||
a, b = _page(browser, 0), _page(browser, 1)
|
||||
assert a.keyboard.acts is a.acts
|
||||
assert (a.acts.page, b.acts.page) == (0, 1)
|
||||
assert a.acts.next("drag") != b.acts.next("drag")
|
||||
|
||||
@@ -62,6 +62,17 @@ class _StubBrowser:
|
||||
|
||||
|
||||
class _AsyncStubBrowser(_StubBrowser):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
# The wrapper reserves each page's number at its own entry, on the
|
||||
# implementation object ([B237]); a stub is its own implementation.
|
||||
self._impl_obj = self
|
||||
self.numbers = []
|
||||
|
||||
def _reserve_page_number(self):
|
||||
self.numbers.append(len(self.numbers))
|
||||
return self.numbers[-1]
|
||||
|
||||
async def new_context(self, **kw): # type: ignore[override]
|
||||
self.context_kwargs.append(kw)
|
||||
return _AsyncStubContext()
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
"""A page's number in the session follows the script, not the engine's timing.
|
||||
|
||||
⛔ WHAT IT REPLACES ([B237]). Every rhythm a page draws - the pause before a
|
||||
field, the keys, the clicks, the drag, the cursor's paths - is drawn under the
|
||||
page's number in the session, so that two tabs never replay each other. The
|
||||
server counted those numbers as it built each page, after the engine had
|
||||
answered; the cursor counted again, at each page's first movement. Two
|
||||
counters for one fact, and the server's followed the engine:
|
||||
|
||||
* `asyncio.gather(browser.new_page(), browser.new_page())`: the client sends
|
||||
each `newPage` only after its own `newContext` is answered, so the first
|
||||
call became page 1 in 4 runs out of 10 (firefox-35, measured on Windows);
|
||||
* a popup took the next number too, so a `new_page()` gathered with the click
|
||||
that opens one became page 2 in 2 runs out of 10;
|
||||
* a script that moved on its second page first gave it 0 in the cursor and 1
|
||||
in the server.
|
||||
|
||||
The pages kept differing from each other, but the seed no longer reproduced
|
||||
WHICH tab had which rhythm.
|
||||
|
||||
Now the client reserves the number at the call (`Browser._reserve_page_number`
|
||||
in the vendored client, the only counter), the server takes it from the
|
||||
request, a popup is numbered from its opener in a space of its own
|
||||
(`_behaviour.popup_number`), and the cursor reads the number from the page.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import http.server
|
||||
import itertools
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_playwright._behaviour import popup_number
|
||||
from invisible_playwright._juggler import server as srv
|
||||
from invisible_playwright._juggler.connection import EventListeners
|
||||
from invisible_playwright._juggler.server import (
|
||||
BrowserContextDispatcher, BrowserDispatcher, Server,
|
||||
)
|
||||
from invisible_playwright._pw._impl._browser import Browser
|
||||
from invisible_playwright._pw._impl._browser_context import (
|
||||
BrowserContext, page_number_for_call,
|
||||
)
|
||||
|
||||
|
||||
# -- the client: the number is reserved at the call --------------------------
|
||||
|
||||
def _impl_browser():
|
||||
browser = object.__new__(Browser)
|
||||
browser._page_numbers = itertools.count()
|
||||
browser._connection = SimpleNamespace(
|
||||
wrap_api_call=lambda cb, title=None: cb())
|
||||
return browser
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_browser_new_page_numbers_by_call_when_the_engine_answers_backwards():
|
||||
"""Known-bad, before: the number was given where `newPage` arrived, and
|
||||
`browser.new_page()` sends `newPage` only once its `newContext` is
|
||||
answered. Here the second call's context is answered first."""
|
||||
browser = _impl_browser()
|
||||
gates = [asyncio.Event(), asyncio.Event()]
|
||||
reached = []
|
||||
|
||||
class _Context:
|
||||
def __init__(self, call):
|
||||
self.call = call
|
||||
|
||||
async def _new_page(self, number):
|
||||
reached.append(self.call)
|
||||
return SimpleNamespace(call=self.call, number=number)
|
||||
|
||||
calls = itertools.count()
|
||||
|
||||
async def new_context(**_kw):
|
||||
call = next(calls)
|
||||
await gates[call].wait()
|
||||
return _Context(call)
|
||||
|
||||
browser.new_context = new_context
|
||||
|
||||
async def drive():
|
||||
both = asyncio.gather(browser.new_page(), browser.new_page())
|
||||
await asyncio.sleep(0)
|
||||
gates[1].set()
|
||||
await asyncio.sleep(0.01)
|
||||
gates[0].set()
|
||||
return await both
|
||||
|
||||
pages = asyncio.run(drive())
|
||||
assert reached == [1, 0], "the engine did not answer backwards"
|
||||
assert [(p.call, p.number) for p in pages] == [(0, 0), (1, 1)]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_context_new_page_sends_the_number_with_the_request():
|
||||
browser = _impl_browser()
|
||||
context = object.__new__(BrowserContext)
|
||||
context._owner_page = None
|
||||
context._browser = browser
|
||||
sent = []
|
||||
|
||||
async def send(method, timeout, params=None):
|
||||
sent.append((method, params))
|
||||
return SimpleNamespace(_object="page %d" % len(sent))
|
||||
|
||||
context._channel = SimpleNamespace(send=send)
|
||||
|
||||
async def drive():
|
||||
return [await context.new_page(), await context.new_page()]
|
||||
|
||||
assert asyncio.run(drive()) == ["page 1", "page 2"]
|
||||
assert sent == [("newPage", {"pageNumber": 0}),
|
||||
("newPage", {"pageNumber": 1})]
|
||||
|
||||
|
||||
class _Impl:
|
||||
"""A browser's implementation object, as far as numbering goes: its
|
||||
`new_page` takes the number on its first step, like the vendored one."""
|
||||
|
||||
def __init__(self):
|
||||
self._page_numbers = itertools.count()
|
||||
self._impl_obj = self
|
||||
self.taken = []
|
||||
|
||||
def _reserve_page_number(self):
|
||||
return next(self._page_numbers)
|
||||
|
||||
async def new_context(self, **_kw):
|
||||
browser = self
|
||||
|
||||
class _Ctx:
|
||||
_impl_obj = SimpleNamespace(_browser=browser)
|
||||
|
||||
async def new_page(self, **_kw2):
|
||||
browser.taken.append(page_number_for_call(browser))
|
||||
return SimpleNamespace(context=self)
|
||||
|
||||
async def add_cookies(self, cookies):
|
||||
pass
|
||||
|
||||
return _Ctx()
|
||||
|
||||
async def new_page(self, **_kw):
|
||||
number = page_number_for_call(self)
|
||||
self.taken.append(number)
|
||||
return SimpleNamespace(context=None, number=number)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("route", ["browser.new_page", "context.new_page"])
|
||||
def test_the_wrapper_reserves_before_the_egress_check_it_waits_for(route):
|
||||
"""With a proxy, the wrapper checks the egress before a page, and only
|
||||
the first call of a burst actually waits for that check: the second one
|
||||
reached the client first and took the first call's number."""
|
||||
from invisible_playwright.async_api import InvisiblePlaywright
|
||||
|
||||
ip = InvisiblePlaywright(seed=42)
|
||||
burst = {"armed": False, "checks": 0}
|
||||
|
||||
async def check():
|
||||
# Due once per interval: the first check of the burst probes the
|
||||
# proxy, the next one finds it fresh and returns at once.
|
||||
if burst["armed"]:
|
||||
burst["checks"] += 1
|
||||
if burst["checks"] == 1:
|
||||
await asyncio.sleep(0.05)
|
||||
|
||||
ip._assert_uscita_invariata = check
|
||||
browser = _Impl()
|
||||
ip._patch_new_context_defaults(browser)
|
||||
|
||||
async def drive():
|
||||
if route == "browser.new_page":
|
||||
burst["armed"] = True
|
||||
await asyncio.gather(browser.new_page(), browser.new_page())
|
||||
else:
|
||||
ctx = await browser.new_context()
|
||||
burst["armed"] = True
|
||||
await asyncio.gather(ctx.new_page(), ctx.new_page())
|
||||
|
||||
asyncio.run(drive())
|
||||
# The second call reached the implementation first; it still holds the
|
||||
# second number, because the number was taken when it was called.
|
||||
assert browser.taken == [1, 0]
|
||||
|
||||
|
||||
# -- the server: it takes the number, and numbers popups apart ---------------
|
||||
|
||||
class _Engine(EventListeners):
|
||||
"""Juggler as far as `Browser.newPage` goes: the target attaches BEFORE
|
||||
the answer (`TargetRegistry.newPage` waits for the target to exist), and
|
||||
each answer waits until the test releases it."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.browser = None
|
||||
self.arrived = threading.Semaphore(0)
|
||||
self.release = [threading.Event() for _ in range(8)]
|
||||
self._calls = itertools.count()
|
||||
|
||||
def send(self, method, params=None, session=None, timeout=30):
|
||||
if method == "Browser.createBrowserContext":
|
||||
return {"browserContextId": "C1"}
|
||||
if method != "Browser.newPage":
|
||||
return {}
|
||||
call = next(self._calls)
|
||||
target = "T%d" % call
|
||||
self.attach(target, (params or {}).get("browserContextId"))
|
||||
self.arrived.release()
|
||||
assert self.release[call].wait(10)
|
||||
return {"targetId": target}
|
||||
|
||||
def attach(self, target, context_id, opener=None):
|
||||
info = {"targetId": target, "type": "page",
|
||||
"browserContextId": context_id}
|
||||
if opener:
|
||||
info["openerId"] = opener
|
||||
self.browser._route_browser_event(
|
||||
"Browser.attachedToTarget",
|
||||
{"sessionId": "S-" + target, "targetInfo": info}, None)
|
||||
|
||||
|
||||
class _Page:
|
||||
"""The `PageDispatcher` seen from the numbering: what it was given."""
|
||||
|
||||
def __init__(self, server, context, session, target_id, number,
|
||||
opener=None):
|
||||
self.target_id = target_id
|
||||
self.number = number
|
||||
self.opener = opener
|
||||
self.popups_opened = 0
|
||||
self.channel = {"guid": "page-" + target_id}
|
||||
|
||||
def announce_closed(self):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def engine(monkeypatch):
|
||||
monkeypatch.setattr(srv, "PageDispatcher", _Page)
|
||||
e = _Engine()
|
||||
browser = BrowserDispatcher(Server(), None, e, "151.0", session_seed=1)
|
||||
e.browser = browser
|
||||
context = BrowserContextDispatcher(browser.server, browser, {}, "C1")
|
||||
browser.contexts.append(context)
|
||||
e.context = context
|
||||
return e
|
||||
|
||||
|
||||
def _new_page_in_thread(engine, number, out):
|
||||
def run():
|
||||
out[number] = engine.context.op_new_page({"pageNumber": number})
|
||||
t = threading.Thread(target=run, daemon=True)
|
||||
t.start()
|
||||
assert engine.arrived.acquire(timeout=10)
|
||||
return t
|
||||
|
||||
|
||||
def _page_of(engine, answer):
|
||||
guid = answer["page"]["guid"]
|
||||
return next(p for p in engine.browser._page_targets.values()
|
||||
if p.channel["guid"] == guid)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_server_takes_the_number_the_request_carries(engine):
|
||||
"""Known-bad, before: the server numbered pages in the order it built
|
||||
them, after the engine answered. Two requests in flight, answered
|
||||
backwards: each page keeps the number its request carried."""
|
||||
out = {}
|
||||
first = _new_page_in_thread(engine, 0, out)
|
||||
second = _new_page_in_thread(engine, 1, out)
|
||||
engine.release[1].set()
|
||||
second.join(10)
|
||||
engine.release[0].set()
|
||||
first.join(10)
|
||||
assert _page_of(engine, out[0]).number == 0
|
||||
assert _page_of(engine, out[1]).number == 1
|
||||
assert engine.browser._answered_numbers == {}
|
||||
assert engine.browser._unanswered == {}
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_request_without_a_number_is_refused(engine):
|
||||
with pytest.raises(srv.ProtocolException, match="pageNumber"):
|
||||
engine.context.op_new_page({})
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_popup_is_numbered_from_its_opener_and_shifts_no_new_page(engine):
|
||||
"""Known-bad, before: a popup took the session's next number, so one
|
||||
landing while a `new_page()` was in flight pushed that page one further.
|
||||
Now the k-th popup of page N is `popup_number(N, k)` whenever it lands,
|
||||
and a page the site opened with no opener we know is a stray."""
|
||||
out = {}
|
||||
engine.release[0].set()
|
||||
_new_page_in_thread(engine, 0, out).join(10)
|
||||
opener = _page_of(engine, out[0])
|
||||
|
||||
pending = _new_page_in_thread(engine, 1, out)
|
||||
engine.attach("P1", "C1", opener="T0") # lands mid-request
|
||||
engine.attach("P2", "C1", opener="T0")
|
||||
engine.release[1].set()
|
||||
pending.join(10)
|
||||
engine.attach("X1", "C1") # no opener: a stray
|
||||
|
||||
def number(target):
|
||||
for _ in range(200):
|
||||
page = engine.browser._page_targets.get(target)
|
||||
if page is not None:
|
||||
return page.number
|
||||
threading.Event().wait(0.01)
|
||||
raise AssertionError("target %s was never adopted" % target)
|
||||
|
||||
assert _page_of(engine, out[1]).number == 1
|
||||
assert number("P1") == popup_number(0, 1)
|
||||
assert number("P2") == popup_number(0, 2)
|
||||
assert number("X1") == popup_number(None, 1)
|
||||
assert engine.browser._page_targets["P1"].opener is opener
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_popup_numbers_never_meet_the_numbers_of_asked_pages():
|
||||
numbers = {popup_number(o, k) for o in (None, 0, 1, 2) for k in range(1, 50)}
|
||||
assert len(numbers) == 4 * 49
|
||||
assert min(numbers) >= 1 << 62
|
||||
|
||||
|
||||
# -- against a real engine ---------------------------------------------------
|
||||
|
||||
def _server_number(page):
|
||||
impl = page._impl_obj
|
||||
server = impl._connection._transport._server
|
||||
return server.object(impl._guid).actions.acts.page
|
||||
|
||||
|
||||
def _client_number(page):
|
||||
return page._impl_obj._initializer.get("pageNumber")
|
||||
|
||||
|
||||
OPENER = (b"<!doctype html><html><body><button id=o "
|
||||
b"onclick=\"window.open('/popup', '_blank')\">open</button>"
|
||||
b"</body></html>")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def opener_url():
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.end_headers()
|
||||
self.wfile.write(b"<!doctype html><p>popup" if
|
||||
self.path.startswith("/popup") else OPENER)
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
yield "http://127.0.0.1:%d/" % server.server_port
|
||||
server.shutdown()
|
||||
|
||||
|
||||
#: ⛔ TWELVE ROUNDS, because the defect is a race: on main the first call of a
|
||||
#: gather took number 1 in 4 runs out of 10, and a `new_page()` gathered with
|
||||
#: a popup took the popup's number in 2 out of 10. Twelve rounds miss the
|
||||
#: first with odds of 0.6**12 (0.2%).
|
||||
ROUNDS = 12
|
||||
|
||||
|
||||
def _gathered_new_pages(firefox_binary):
|
||||
from invisible_playwright.async_api import InvisiblePlaywright
|
||||
|
||||
async def drive():
|
||||
seen = []
|
||||
async with InvisiblePlaywright(seed=106, binary_path=firefox_binary,
|
||||
headless=True) as browser:
|
||||
for _ in range(ROUNDS):
|
||||
pages = await asyncio.gather(browser.new_page(),
|
||||
browser.new_page())
|
||||
seen.extend((_server_number(p), _client_number(p))
|
||||
for p in pages)
|
||||
for p in pages:
|
||||
await p.close()
|
||||
return seen
|
||||
|
||||
return asyncio.run(drive())
|
||||
|
||||
|
||||
def _popups_beside_new_pages(firefox_binary, opener_url):
|
||||
from invisible_playwright.async_api import InvisiblePlaywright
|
||||
|
||||
async def drive():
|
||||
fresh_pages, popups = [], []
|
||||
async with InvisiblePlaywright(seed=106, binary_path=firefox_binary,
|
||||
headless=True) as browser:
|
||||
ctx = await browser.new_context()
|
||||
opener = await ctx.new_page()
|
||||
await opener.goto(opener_url)
|
||||
for _ in range(ROUNDS):
|
||||
popped = asyncio.get_running_loop().create_future()
|
||||
opener.once("popup", lambda p: popped.set_result(p))
|
||||
_, fresh = await asyncio.gather(opener.click("#o"),
|
||||
ctx.new_page())
|
||||
popup = await asyncio.wait_for(popped, 15)
|
||||
fresh_pages.append((_server_number(fresh), _client_number(fresh)))
|
||||
popups.append((_server_number(popup), _client_number(popup)))
|
||||
await fresh.close()
|
||||
await popup.close()
|
||||
return _server_number(opener), fresh_pages, popups
|
||||
|
||||
return asyncio.run(drive())
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_gathered_pages_take_the_numbers_of_their_calls(firefox_binary):
|
||||
"""Two `browser.new_page()` gathered, twelve times in one session: every
|
||||
page has the number of its call, in the server and in the client's
|
||||
initializer alike."""
|
||||
seen = _gathered_new_pages(firefox_binary)
|
||||
assert seen == [(n, n) for n in range(2 * ROUNDS)], (
|
||||
"pages asked for, (server, client), in call order: %s" % seen)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_a_popup_takes_no_number_of_a_page_asked_for(firefox_binary, opener_url):
|
||||
"""A click that opens a popup gathered with a `new_page()`, twelve times
|
||||
in one session: each new page has the number of its call, and each popup
|
||||
the one its opener and its rank give it.
|
||||
|
||||
⛔ A SESSION OF ITS OWN, not the tail of the gathered one. After the 24
|
||||
pages of the test above, this loop stalled the engine at its seventh to
|
||||
tenth round (`Browser.newPage` or `Runtime.callFunction` unanswered for
|
||||
30 s) in 6 runs out of 12 with four browsers at once, on main as on this
|
||||
branch alike; in a fresh session, 0 out of 12."""
|
||||
opener_number, fresh_pages, popups = _popups_beside_new_pages(
|
||||
firefox_binary, opener_url)
|
||||
assert opener_number == 0
|
||||
assert fresh_pages == [(n, n) for n in range(1, ROUNDS + 1)], fresh_pages
|
||||
assert popups == [(popup_number(0, k),) * 2
|
||||
for k in range(1, ROUNDS + 1)], popups
|
||||
Reference in new issue
Block a user