Compare commits
2
Commits
main
...
hunt/d72-probes
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
616629ffd1 | ||
|
|
d19ec08b6f |
No files matched your search
@@ -0,0 +1,112 @@
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# d72-probes.yml - two measurements of the PUBLISHED wrapper (0.61.0, invisible-core 71.85.0, the published engine firefox-71) on
|
||||
# Linux and Windows runners. Measurement branch, never merged: it starts on a push to hunt/d72-probes and nowhere else, it decides
|
||||
# nothing (the script exits 0 unless nothing ran at all), and it is not a gate.
|
||||
#
|
||||
# The two questions.
|
||||
#
|
||||
# A. gzip - what does a page read from CompressionStream ("gzip", "deflate", "deflate-raw") over three fixed inputs, and in
|
||||
# particular which value does byte 9 of the gzip header (the OS byte) have, on Linux and on Windows, for two seeds? The raw bytes of
|
||||
# every output are kept (evidence/gzip.json).
|
||||
#
|
||||
# B. first pointer events with no input - when the script gives NO input at all (no mouse, keyboard, click, hover, focus,
|
||||
# bring_to_front or viewport call), which events does a page receive from its birth, and with which clientX/Y and screenX/Y; are the
|
||||
# first event's screen coordinates the same across seeds; does a page opened after about:blank see the same? On Linux the wrapper's
|
||||
# own private Xvfb is what is measured, so the step does NOT use xvfb-run and DISPLAY is unset; where the host allows it, the Xvfb
|
||||
# command line and the X root pointer position are recorded too (evidence/pointer.json, evidence/summary.json).
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
name: d72 probes
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- hunt/d72-probes
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Engine and GeoIP downloads go through the release API with this token (anonymous requests share a per-address limit).
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
# The Ubuntu packages of the Linux leg, from Ubuntu's archive once per runner image and list (linux-deps.yml), never by the probe.
|
||||
linux-deps-hunt:
|
||||
name: linux-deps-hunt
|
||||
uses: ./.github/workflows/linux-deps.yml
|
||||
with:
|
||||
name: hunt
|
||||
packages: xvfb
|
||||
playwright_wrapper_ref: ${{ github.sha }}
|
||||
|
||||
probe:
|
||||
name: probe (${{ matrix.os }})
|
||||
needs: linux-deps-hunt
|
||||
if: ${{ !cancelled() && needs.linux-deps-hunt.result == 'success' }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-24.04, windows-2025]
|
||||
timeout-minutes: 30
|
||||
# TEMP and TMP on D:\a\_temp (the runner's temp folder): the Firefox profiles land in TEMP and on C: they saturate the disk.
|
||||
env:
|
||||
TEMP: ${{ startsWith(matrix.os, 'windows') && 'D:\a\_temp' || '/tmp' }}
|
||||
TMP: ${{ startsWith(matrix.os, 'windows') && 'D:\a\_temp' || '/tmp' }}
|
||||
# On Windows GitHub runs `run:` blocks with PowerShell by default; every block here is bash.
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: Install the wrapper of this tag (0.61.0) and the pinned Playwright
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install .
|
||||
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
|
||||
- name: The Linux packages (the run's linux-deps-hunt job, no mirror)
|
||||
if: runner.os == 'Linux'
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
|
||||
with:
|
||||
name: ${{ needs.linux-deps-hunt.outputs.artifact }}
|
||||
path: /tmp/linux-deps
|
||||
- name: System deps (xvfb + Firefox runtime libs; the repository of the linux-deps-hunt job)
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# The run's linux-deps repository and nothing else: apt reads only its sources list and lists folder, the files are already in apt's archives,
|
||||
# and the roots are installed by name with --no-download: a package the repository does not hold is named here and red, never fetched.
|
||||
read -r OS VER < /tmp/linux-deps/image.txt
|
||||
echo "the repository was read on $OS $VER; this runner is $ImageOS $ImageVersion"
|
||||
sudo mkdir -p /tmp/linux-deps-apt/lists/partial /tmp/linux-deps-apt/parts
|
||||
echo "deb [trusted=yes] file:/tmp/linux-deps ./" | sudo tee /tmp/linux-deps-apt/sources.list >/dev/null
|
||||
APT="-o Dir::Etc::SourceList=/tmp/linux-deps-apt/sources.list -o Dir::Etc::SourceParts=/tmp/linux-deps-apt/parts -o Dir::State::Lists=/tmp/linux-deps-apt/lists -o Acquire::Languages=none"
|
||||
sudo apt-get $APT update
|
||||
sudo cp /tmp/linux-deps/*.deb /var/cache/apt/archives/
|
||||
sudo apt-get $APT install -y --no-download --no-install-recommends $(cat /tmp/linux-deps/roots.txt)
|
||||
- name: python-xlib (Linux, best effort, to read the root pointer of the wrapper's Xvfb)
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
python -m pip install python-xlib || echo "::warning::python-xlib not installed, the root pointer is not sampled"
|
||||
- name: Fetch the published firefox binary
|
||||
run: echo "FF=$(python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
- name: The probes (no xvfb-run and DISPLAY unset, so the wrapper starts its own private Xvfb)
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
run: |
|
||||
set -u
|
||||
unset DISPLAY
|
||||
echo "DISPLAY is ${DISPLAY-unset}; engine binary $FF"
|
||||
mkdir -p evidence
|
||||
python -u scripts/hunt_d72_probes.py --out evidence
|
||||
- name: Upload the evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: d72-probes-${{ matrix.os }}
|
||||
path: evidence
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
@@ -0,0 +1,59 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>d72 gzip probe</title>
|
||||
<script>
|
||||
// Compresses three inputs with CompressionStream in each format and exposes
|
||||
// window.__gzip, a promise of the whole reading. Nothing here depends on input.
|
||||
(function () {
|
||||
function hex(bytes) {
|
||||
var out = [];
|
||||
for (var i = 0; i < bytes.length; i++) out.push((bytes[i] < 16 ? "0" : "") + bytes[i].toString(16));
|
||||
return out.join("");
|
||||
}
|
||||
async function compress(fmt, text) {
|
||||
var stream = new Blob([text]).stream().pipeThrough(new CompressionStream(fmt));
|
||||
return new Uint8Array(await new Response(stream).arrayBuffer());
|
||||
}
|
||||
var inputs = {
|
||||
empty: "",
|
||||
hello: "hello",
|
||||
abcdefghijklmnop_x256: "abcdefghijklmnop".repeat(256)
|
||||
};
|
||||
var formats = ["gzip", "deflate", "deflate-raw"];
|
||||
window.__gzip = (async function () {
|
||||
var result = {
|
||||
navigator: {
|
||||
userAgent: navigator.userAgent,
|
||||
platform: navigator.platform,
|
||||
oscpu: navigator.oscpu === undefined ? null : navigator.oscpu
|
||||
},
|
||||
inputLengths: {},
|
||||
outputs: {}
|
||||
};
|
||||
for (var name in inputs) {
|
||||
result.inputLengths[name] = inputs[name].length;
|
||||
result.outputs[name] = {};
|
||||
for (var f = 0; f < formats.length; f++) {
|
||||
var fmt = formats[f];
|
||||
try {
|
||||
var bytes = await compress(fmt, inputs[name]);
|
||||
var entry = { length: bytes.length, hex: hex(bytes) };
|
||||
if (fmt === "gzip") {
|
||||
entry.header10 = hex(bytes.subarray(0, 10));
|
||||
entry.osByte = bytes.length > 9 ? bytes[9] : null;
|
||||
}
|
||||
result.outputs[name][fmt] = entry;
|
||||
} catch (e) {
|
||||
result.outputs[name][fmt] = { error: String(e) };
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
})();
|
||||
})();
|
||||
</script>
|
||||
</head>
|
||||
<body>d72 gzip probe</body>
|
||||
</html>
|
||||
@@ -0,0 +1,96 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<script>
|
||||
/*RECORDER-START*/
|
||||
// First thing in the document: records every event of the listed types from document birth.
|
||||
// The same text (between the RECORDER markers) is installed as a context init script by the
|
||||
// "blank-first" variant; the guard keeps it from recording twice when both are present.
|
||||
function d72Install(source) {
|
||||
if (window.__d72) return;
|
||||
var TYPES = ["mouseover", "mouseout", "mouseenter", "mouseleave", "mousemove",
|
||||
"pointerover", "pointerout", "pointerenter", "pointerleave", "pointermove",
|
||||
"pointerdown", "pointerup", "mousedown", "mouseup", "click", "wheel",
|
||||
"contextmenu", "focus", "blur", "visibilitychange"];
|
||||
var log = [];
|
||||
var seq = 0;
|
||||
function nz(v) { return v === undefined ? null : v; }
|
||||
function snap() {
|
||||
var de = document.documentElement;
|
||||
var hover = null;
|
||||
try { hover = de ? de.matches(":hover") : null; } catch (e) { hover = "error: " + e; }
|
||||
var hasFocus = null;
|
||||
try { hasFocus = document.hasFocus(); } catch (e) { hasFocus = "error: " + e; }
|
||||
return {
|
||||
url: String(location.href),
|
||||
readyState: document.readyState,
|
||||
screenX: nz(window.screenX), screenY: nz(window.screenY),
|
||||
mozInnerScreenX: nz(window.mozInnerScreenX), mozInnerScreenY: nz(window.mozInnerScreenY),
|
||||
outerWidth: window.outerWidth, outerHeight: window.outerHeight,
|
||||
innerWidth: window.innerWidth, innerHeight: window.innerHeight,
|
||||
screenWidth: screen.width, screenHeight: screen.height,
|
||||
availWidth: screen.availWidth, availHeight: screen.availHeight,
|
||||
devicePixelRatio: window.devicePixelRatio,
|
||||
hasFocus: hasFocus,
|
||||
visibilityState: document.visibilityState,
|
||||
rootMatchesHover: hover,
|
||||
performanceNow: performance.now()
|
||||
};
|
||||
}
|
||||
function nodeName(t) {
|
||||
if (t === window) return "#window";
|
||||
if (t && t.nodeName) return t.nodeName;
|
||||
return String(t);
|
||||
}
|
||||
function make(listener) {
|
||||
return function (e) {
|
||||
log.push({
|
||||
seq: seq++, listener: listener, type: e.type, target: nodeName(e.target),
|
||||
clientX: nz(e.clientX), clientY: nz(e.clientY),
|
||||
screenX: nz(e.screenX), screenY: nz(e.screenY),
|
||||
pageX: nz(e.pageX), pageY: nz(e.pageY),
|
||||
movementX: nz(e.movementX), movementY: nz(e.movementY),
|
||||
buttons: nz(e.buttons), button: nz(e.button),
|
||||
isTrusted: e.isTrusted, pointerType: nz(e.pointerType), pointerId: nz(e.pointerId),
|
||||
timeStamp: e.timeStamp, performanceNow: performance.now()
|
||||
});
|
||||
};
|
||||
}
|
||||
var onWindow = make("window-capture"), onDocument = make("document"), onRoot = make("root");
|
||||
var birth = snap();
|
||||
for (var i = 0; i < TYPES.length; i++) {
|
||||
window.addEventListener(TYPES[i], onWindow, true);
|
||||
document.addEventListener(TYPES[i], onDocument, false);
|
||||
}
|
||||
var rootHooked = false;
|
||||
function hookRoot() {
|
||||
var r = document.documentElement;
|
||||
if (!r || rootHooked) return;
|
||||
rootHooked = true;
|
||||
for (var j = 0; j < TYPES.length; j++) r.addEventListener(TYPES[j], onRoot, false);
|
||||
}
|
||||
hookRoot();
|
||||
if (!rootHooked) {
|
||||
var mo = new MutationObserver(function () { hookRoot(); if (rootHooked) mo.disconnect(); });
|
||||
mo.observe(document, { childList: true });
|
||||
document.addEventListener("readystatechange", hookRoot);
|
||||
}
|
||||
window.__d72 = {
|
||||
source: source,
|
||||
read: function () {
|
||||
return { source: source, birth: birth, now: snap(), events: log.slice() };
|
||||
}
|
||||
};
|
||||
}
|
||||
/*RECORDER-END*/
|
||||
d72Install("inline");
|
||||
</script>
|
||||
<meta charset="utf-8">
|
||||
<title>d72 pointer probe</title>
|
||||
<style>
|
||||
html, body { margin: 0; padding: 0; }
|
||||
body { width: 100vw; height: 100vh; overflow: hidden; background: #fff; }
|
||||
</style>
|
||||
</head>
|
||||
<body>d72 pointer probe: no input is given to this page.</body>
|
||||
</html>
|
||||
@@ -0,0 +1,403 @@
|
||||
"""Two measurements on a branch of their own (never merged, not a gate).
|
||||
|
||||
python scripts/hunt_d72_probes.py --out DIR
|
||||
|
||||
Probe A (gzip): what a page reads from CompressionStream ("gzip", "deflate", "deflate-raw") over three inputs, for seeds 1 and 2,
|
||||
one launch each (scripts/hunt_d72_pages/gzip.html). Writes DIR/gzip.json.
|
||||
|
||||
Probe B (first pointer events with no input): which events a page receives from its birth when the script gives NO input at all, and
|
||||
with which coordinates (scripts/hunt_d72_pages/pointer.html, a recorder that is the first thing in the document). Variants:
|
||||
immediate launch, new page, goto the pointer page, sleep 5 s, read.
|
||||
blank-first the same recorder as a context init script; new page, sleep 5 s on about:blank, read, then goto the pointer page,
|
||||
sleep 5 s, read.
|
||||
Seeds 1, 7, 21, 63; 2 launches per seed per variant. On Linux, best effort and never fatal: the wrapper's own Xvfb is found (a scan of
|
||||
/proc) and the root window's pointer position is sampled with python-xlib while the browser is open. Writes DIR/pointer.json (every
|
||||
launch, raw) and DIR/summary.json.
|
||||
|
||||
Every launch is launched the product's way (InvisiblePlaywright(seed=..., headless=True)); during a measurement the script gives no
|
||||
input: no mouse, keyboard, click, hover, focus, bring_to_front or viewport call. Exit 0 unless nothing at all ran.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import http.server
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import socketserver
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from importlib import metadata
|
||||
from pathlib import Path
|
||||
|
||||
PAGES = Path(__file__).resolve().parent / "hunt_d72_pages"
|
||||
GZIP_SEEDS = (1, 2)
|
||||
POINTER_SEEDS = (1, 7, 21, 63)
|
||||
LAUNCHES_PER_SEED = 2
|
||||
SLEEP_SECONDS = 5
|
||||
GOTO_TIMEOUT_MS = 30_000
|
||||
POINTER_TYPES = ("mouseover", "mouseout", "mouseenter", "mouseleave", "mousemove", "pointerover", "pointerout", "pointerenter",
|
||||
"pointerleave", "pointermove", "pointerdown", "pointerup", "mousedown", "mouseup", "click", "wheel", "contextmenu")
|
||||
|
||||
|
||||
class _Handler(http.server.SimpleHTTPRequestHandler):
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
def _serve():
|
||||
handler = lambda *a, **k: _Handler(*a, directory=str(PAGES), **k) # noqa: E731
|
||||
server = socketserver.ThreadingTCPServer(("127.0.0.1", 0), handler)
|
||||
server.daemon_threads = True
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
return server
|
||||
|
||||
|
||||
def _sha256(path: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with open(path, "rb") as f:
|
||||
for block in iter(lambda: f.read(1 << 20), b""):
|
||||
h.update(block)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def _error(exc: BaseException) -> dict:
|
||||
return {"error": repr(exc), "traceback": traceback.format_exc()}
|
||||
|
||||
|
||||
def _meta() -> dict:
|
||||
meta = {"os": platform.platform(), "system": platform.system(), "python": sys.version,
|
||||
"env_DISPLAY": os.environ.get("DISPLAY"), "env_WAYLAND_DISPLAY": os.environ.get("WAYLAND_DISPLAY")}
|
||||
try:
|
||||
import invisible_playwright
|
||||
meta["wrapper_version"] = invisible_playwright.__version__
|
||||
meta["wrapper_install_record"] = invisible_playwright.__install_record_version__
|
||||
except Exception as exc: # noqa: BLE001 - a measurement records, never stops
|
||||
meta["wrapper_version_error"] = repr(exc)
|
||||
for dist in ("invisible-core", "invisible-playwright", "playwright"):
|
||||
try:
|
||||
meta["dist_" + dist] = metadata.version(dist)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
meta["dist_" + dist] = "error: %r" % (exc,)
|
||||
try:
|
||||
import invisible_core
|
||||
meta["core_BINARY_VERSION"] = getattr(invisible_core, "BINARY_VERSION", None)
|
||||
meta["core_FIREFOX_UPSTREAM_VERSION"] = getattr(invisible_core, "FIREFOX_UPSTREAM_VERSION", None)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
meta["core_error"] = repr(exc)
|
||||
try:
|
||||
from invisible_playwright._engine import resolve_executable
|
||||
exe = Path(resolve_executable(None))
|
||||
meta["engine_binary"] = str(exe)
|
||||
meta["engine_binary_sha256"] = _sha256(exe)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
meta["engine_binary_error"] = repr(exc)
|
||||
try:
|
||||
from invisible_core.seal import active_seal
|
||||
seal = active_seal()
|
||||
meta["seal_tag"] = getattr(seal, "tag", None)
|
||||
meta["seal_upstream_version"] = getattr(seal, "upstream_version", None)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
meta["seal_error"] = repr(exc)
|
||||
return meta
|
||||
|
||||
|
||||
def _recorder_source() -> str:
|
||||
"""The pointer page's recorder, as a context init script: the same text between its RECORDER markers."""
|
||||
text = (PAGES / "pointer.html").read_text(encoding="utf-8")
|
||||
m = re.search(r"/\*RECORDER-START\*/(.*?)/\*RECORDER-END\*/", text, re.S)
|
||||
if not m:
|
||||
raise RuntimeError("recorder markers not found in pointer.html")
|
||||
return "(function () {" + m.group(1) + "\nd72Install(\"init\");\n})();"
|
||||
|
||||
|
||||
# ---- Linux: the wrapper's own Xvfb and its root pointer (best effort) -------------------------------------------------------
|
||||
|
||||
def _xvfb_processes() -> dict:
|
||||
"""pid -> argv of every Xvfb process visible in /proc."""
|
||||
found = {}
|
||||
if not Path("/proc").is_dir():
|
||||
return found
|
||||
for entry in Path("/proc").iterdir():
|
||||
if not entry.name.isdigit():
|
||||
continue
|
||||
try:
|
||||
argv = (entry / "cmdline").read_bytes().split(b"\0")
|
||||
except OSError:
|
||||
continue
|
||||
argv = [a.decode("utf-8", "replace") for a in argv if a]
|
||||
if argv and os.path.basename(argv[0]) == "Xvfb":
|
||||
found[int(entry.name)] = argv
|
||||
return found
|
||||
|
||||
|
||||
class _XvfbSampler(threading.Thread):
|
||||
"""While a browser is open: find the Xvfb that was not there before the launch, record its command line, and sample the root
|
||||
window's pointer. Never raises; everything it learns, and every error, is in `result`."""
|
||||
|
||||
def __init__(self, before: dict, interval: float = 0.5):
|
||||
super().__init__(daemon=True)
|
||||
self.before = set(before)
|
||||
self.interval = interval
|
||||
self.stop_event = threading.Event()
|
||||
self.t0 = time.monotonic()
|
||||
self.result = {"xvfb": None, "pointer_samples": [], "errors": []}
|
||||
self._display = None
|
||||
|
||||
def run(self):
|
||||
try:
|
||||
while not self.stop_event.is_set():
|
||||
self._step()
|
||||
self.stop_event.wait(self.interval)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
self.result["errors"].append(repr(exc))
|
||||
|
||||
def _step(self):
|
||||
if self.result["xvfb"] is None:
|
||||
new = {pid: argv for pid, argv in _xvfb_processes().items() if pid not in self.before}
|
||||
if not new:
|
||||
return
|
||||
pid, argv = sorted(new.items())[0]
|
||||
self.result["xvfb"] = {"pid": pid, "argv": argv, "all_new": {str(p): a for p, a in new.items()}}
|
||||
if self._display is None:
|
||||
argv = self.result["xvfb"]["argv"]
|
||||
name = next((a for a in argv[1:] if re.fullmatch(r":\d+(\.\d+)?", a)), None)
|
||||
if name is None:
|
||||
self.result["errors"].append("no display name in the Xvfb command line")
|
||||
self.stop_event.set()
|
||||
return
|
||||
try:
|
||||
from Xlib import display as xdisplay
|
||||
self._display = xdisplay.Display(name)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
if len(self.result["errors"]) < 5:
|
||||
self.result["errors"].append("xlib connect %s: %r" % (name, exc))
|
||||
return
|
||||
try:
|
||||
ptr = self._display.screen().root.query_pointer()
|
||||
self.result["pointer_samples"].append({"t": round(time.monotonic() - self.t0, 3), "root_x": ptr.root_x,
|
||||
"root_y": ptr.root_y, "same_screen": bool(ptr.same_screen)})
|
||||
except Exception as exc: # noqa: BLE001
|
||||
if len(self.result["errors"]) < 5:
|
||||
self.result["errors"].append("query_pointer: %r" % (exc,))
|
||||
|
||||
def finish(self) -> dict:
|
||||
self.stop_event.set()
|
||||
self.join(timeout=5)
|
||||
try:
|
||||
if self._display is not None:
|
||||
self._display.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return self.result
|
||||
|
||||
|
||||
def _windows_cursor():
|
||||
if platform.system() != "Windows":
|
||||
return None
|
||||
try:
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
pt = wintypes.POINT()
|
||||
ok = ctypes.windll.user32.GetCursorPos(ctypes.byref(pt))
|
||||
return {"ok": bool(ok), "x": pt.x, "y": pt.y}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"error": repr(exc)}
|
||||
|
||||
|
||||
# ---- the launches -----------------------------------------------------------------------------------------------------------
|
||||
|
||||
def _gzip_launch(seed: int, base: str) -> dict:
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
rec = {"seed": seed}
|
||||
try:
|
||||
with InvisiblePlaywright(seed=seed, headless=True) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto(base + "/gzip.html", timeout=GOTO_TIMEOUT_MS)
|
||||
rec["reading"] = page.evaluate("window.__gzip")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
rec.update(_error(exc))
|
||||
return rec
|
||||
|
||||
|
||||
def _pointer_launch(variant: str, seed: int, launch: int, base: str, recorder: str) -> dict:
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
rec = {"variant": variant, "seed": seed, "launch": launch, "pages": {}}
|
||||
sampler = None
|
||||
try:
|
||||
before = _xvfb_processes() if platform.system() == "Linux" else {}
|
||||
with InvisiblePlaywright(seed=seed, headless=True) as browser:
|
||||
if platform.system() == "Linux":
|
||||
sampler = _XvfbSampler(before)
|
||||
sampler.start()
|
||||
context = browser.new_context()
|
||||
if variant == "blank-first":
|
||||
context.add_init_script(script=recorder)
|
||||
page = context.new_page()
|
||||
rec["windows_cursor_before"] = _windows_cursor()
|
||||
if variant == "immediate":
|
||||
page.goto(base + "/pointer.html", timeout=GOTO_TIMEOUT_MS)
|
||||
time.sleep(SLEEP_SECONDS)
|
||||
rec["pages"]["pointer"] = page.evaluate("window.__d72 && window.__d72.read()")
|
||||
else:
|
||||
time.sleep(SLEEP_SECONDS)
|
||||
rec["pages"]["blank"] = page.evaluate("window.__d72 ? window.__d72.read() : null")
|
||||
page.goto(base + "/pointer.html", timeout=GOTO_TIMEOUT_MS)
|
||||
time.sleep(SLEEP_SECONDS)
|
||||
rec["pages"]["pointer"] = page.evaluate("window.__d72 && window.__d72.read()")
|
||||
rec["windows_cursor_after"] = _windows_cursor()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
rec.update(_error(exc))
|
||||
finally:
|
||||
if sampler is not None:
|
||||
rec["xvfb_sampler"] = sampler.finish()
|
||||
return rec
|
||||
|
||||
|
||||
# ---- the summary ------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def _first(ev: dict | None) -> dict | None:
|
||||
if ev is None:
|
||||
return None
|
||||
return {k: ev.get(k) for k in ("type", "listener", "target", "clientX", "clientY", "screenX", "screenY", "buttons", "isTrusted",
|
||||
"timeStamp")}
|
||||
|
||||
|
||||
def _page_summary(read: dict | None) -> dict:
|
||||
if not read:
|
||||
return {"read": False}
|
||||
events = read.get("events") or []
|
||||
counts, by_listener = {}, {}
|
||||
for ev in events:
|
||||
by_listener[ev["listener"]] = by_listener.get(ev["listener"], 0) + 1
|
||||
if ev["listener"] == "window-capture":
|
||||
counts[ev["type"]] = counts.get(ev["type"], 0) + 1
|
||||
pointer_events = [e for e in events if e["type"] in POINTER_TYPES]
|
||||
return {"read": True, "source": read.get("source"), "n_events": len(events), "count_by_type": counts,
|
||||
"count_by_listener": by_listener, "first_event": _first(events[0] if events else None),
|
||||
"first_pointer_event": _first(pointer_events[0] if pointer_events else None),
|
||||
"now": {k: (read.get("now") or {}).get(k) for k in ("screenX", "screenY", "mozInnerScreenX", "mozInnerScreenY",
|
||||
"hasFocus", "visibilityState", "rootMatchesHover")}}
|
||||
|
||||
|
||||
def _screen_xy(first: dict | None):
|
||||
return None if first is None else [first.get("screenX"), first.get("screenY")]
|
||||
|
||||
|
||||
def _summarize(launches: list) -> dict:
|
||||
out = {"os": platform.system(), "variants": {}}
|
||||
for variant in ("immediate", "blank-first"):
|
||||
mine = [r for r in launches if r["variant"] == variant]
|
||||
entry = {"launches": [], "errors": []}
|
||||
by_seed = {} # page -> seed -> list of first-event screen coordinates
|
||||
by_seed_pointer = {}
|
||||
for r in mine:
|
||||
item = {"seed": r["seed"], "launch": r["launch"], "pages": {}}
|
||||
if "error" in r:
|
||||
entry["errors"].append({"seed": r["seed"], "launch": r["launch"], "error": r["error"]})
|
||||
item["error"] = r["error"]
|
||||
for name, read in r["pages"].items():
|
||||
s = _page_summary(read)
|
||||
item["pages"][name] = s
|
||||
if s.get("read"):
|
||||
by_seed.setdefault(name, {}).setdefault(r["seed"], []).append(_screen_xy(s["first_event"]))
|
||||
by_seed_pointer.setdefault(name, {}).setdefault(r["seed"], []).append(
|
||||
_screen_xy(s["first_pointer_event"]))
|
||||
sampler = r.get("xvfb_sampler")
|
||||
if sampler:
|
||||
item["xvfb_argv"] = (sampler.get("xvfb") or {}).get("argv")
|
||||
item["root_pointer_samples"] = sampler.get("pointer_samples")
|
||||
item["xvfb_sampler_errors"] = sampler.get("errors")
|
||||
entry["launches"].append(item)
|
||||
|
||||
def same(table):
|
||||
res = {}
|
||||
for name, seeds in table.items():
|
||||
flat = {json.dumps(v) for runs in seeds.values() for v in runs}
|
||||
res[name] = {"first_screenXY_by_seed": {str(s): v for s, v in sorted(seeds.items())},
|
||||
"same_across_seeds": len(flat) == 1}
|
||||
return res
|
||||
entry["first_event_screenXY"] = same(by_seed)
|
||||
entry["first_pointer_event_screenXY"] = same(by_seed_pointer)
|
||||
out["variants"][variant] = entry
|
||||
return out
|
||||
|
||||
|
||||
def _write(path: Path, obj) -> None:
|
||||
path.write_text(json.dumps(obj, indent=1, sort_keys=True) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--out", type=Path, required=True)
|
||||
args = ap.parse_args()
|
||||
args.out.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
meta = _meta()
|
||||
print("meta:", json.dumps(meta, indent=1, sort_keys=True), flush=True)
|
||||
server = _serve()
|
||||
base = "http://127.0.0.1:%d" % server.server_address[1]
|
||||
ran = 0
|
||||
summary_errors = []
|
||||
|
||||
# Probe A
|
||||
gzip_launches = []
|
||||
for seed in GZIP_SEEDS:
|
||||
print("gzip seed %d" % seed, flush=True)
|
||||
r = _gzip_launch(seed, base)
|
||||
gzip_launches.append(r)
|
||||
if "error" in r:
|
||||
summary_errors.append({"probe": "gzip", "seed": seed, "error": r["error"]})
|
||||
else:
|
||||
ran += 1
|
||||
_write(args.out / "gzip.json", {"meta": meta, "launches": gzip_launches})
|
||||
|
||||
# Probe B
|
||||
pointer_launches = []
|
||||
recorder = None
|
||||
variants = ["immediate"]
|
||||
try:
|
||||
recorder = _recorder_source()
|
||||
from invisible_playwright._pw.sync_api import BrowserContext
|
||||
if hasattr(BrowserContext, "add_init_script"):
|
||||
variants.append("blank-first")
|
||||
meta["add_init_script_exists"] = True
|
||||
else:
|
||||
meta["add_init_script_exists"] = False
|
||||
meta["blank_first_skipped"] = "BrowserContext has no add_init_script in this version"
|
||||
except Exception as exc: # noqa: BLE001
|
||||
meta["blank_first_skipped"] = "could not check BrowserContext.add_init_script: %r" % (exc,)
|
||||
for variant in variants:
|
||||
for seed in POINTER_SEEDS:
|
||||
for launch in range(1, LAUNCHES_PER_SEED + 1):
|
||||
print("pointer %s seed %d launch %d" % (variant, seed, launch), flush=True)
|
||||
r = _pointer_launch(variant, seed, launch, base, recorder)
|
||||
pointer_launches.append(r)
|
||||
if "error" in r:
|
||||
summary_errors.append({"probe": "pointer", "variant": variant, "seed": seed, "launch": launch,
|
||||
"error": r["error"]})
|
||||
else:
|
||||
ran += 1
|
||||
_write(args.out / "pointer.json", {"meta": meta, "launches": pointer_launches})
|
||||
server.shutdown()
|
||||
|
||||
summary = _summarize(pointer_launches)
|
||||
summary["meta"] = meta
|
||||
summary["variants_run"] = variants
|
||||
summary["gzip"] = {str(r["seed"]): ({"error": r["error"]} if "error" in r else {
|
||||
"gzip_os_byte_by_input": {k: v.get("gzip", {}).get("osByte") for k, v in r["reading"]["outputs"].items()},
|
||||
"platform": r["reading"]["navigator"]["platform"]}) for r in gzip_launches}
|
||||
summary["successful_launches"] = ran
|
||||
summary["errors"] = summary_errors
|
||||
_write(args.out / "summary.json", summary)
|
||||
_write(args.out / "pointer.json", {"meta": meta, "launches": pointer_launches})
|
||||
print("done: %d successful launches, %d errors" % (ran, len(summary_errors)), flush=True)
|
||||
return 0 if ran else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user