statement-fetch 0.5.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- statement_fetch/__init__.py +126 -0
- statement_fetch/_contracts.py +532 -0
- statement_fetch/_playwright.py +518 -0
- statement_fetch/_registry.py +132 -0
- statement_fetch/_runner.py +538 -0
- statement_fetch/_staging.py +409 -0
- statement_fetch/_validators.py +242 -0
- statement_fetch/api.py +133 -0
- statement_fetch/cli.py +686 -0
- statement_fetch/demo.py +111 -0
- statement_fetch/providers/__init__.py +1 -0
- statement_fetch/providers/example_bank.py +152 -0
- statement_fetch/py.typed +0 -0
- statement_fetch/sinks/__init__.py +1 -0
- statement_fetch/sinks/directory.py +260 -0
- statement_fetch-0.5.0.dist-info/METADATA +95 -0
- statement_fetch-0.5.0.dist-info/RECORD +20 -0
- statement_fetch-0.5.0.dist-info/WHEEL +4 -0
- statement_fetch-0.5.0.dist-info/entry_points.txt +8 -0
- statement_fetch-0.5.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
"""Local Playwright/Chromium host (`PlaywrightHost`), `NativePage`, and CDP `Fetch` host confinement."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import contextlib
|
|
6
|
+
import inspect
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
import shutil
|
|
10
|
+
import tempfile
|
|
11
|
+
import weakref
|
|
12
|
+
from collections.abc import Callable
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
from urllib.parse import urljoin
|
|
16
|
+
|
|
17
|
+
from ._contracts import (
|
|
18
|
+
Click,
|
|
19
|
+
DownloadMismatchError,
|
|
20
|
+
DownloadTimeoutError,
|
|
21
|
+
DownloadTrigger,
|
|
22
|
+
Evaluate,
|
|
23
|
+
FrameLocator,
|
|
24
|
+
Keyboard,
|
|
25
|
+
Locator,
|
|
26
|
+
Page,
|
|
27
|
+
WindowClosedError,
|
|
28
|
+
)
|
|
29
|
+
from ._runner import allowed_document, fetch_same_origin_bytes
|
|
30
|
+
from ._staging import sanitize_filename
|
|
31
|
+
|
|
32
|
+
log = logging.getLogger("statement-fetch.playwright")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class _NativeLocator:
|
|
36
|
+
def __init__(self, loc: Any, check_state: Callable[[], None] | None = None) -> None:
|
|
37
|
+
self._loc = loc
|
|
38
|
+
self._check_state = check_state
|
|
39
|
+
|
|
40
|
+
def _check(self) -> None:
|
|
41
|
+
if self._check_state is not None:
|
|
42
|
+
self._check_state()
|
|
43
|
+
|
|
44
|
+
def first(self) -> _NativeLocator:
|
|
45
|
+
return _NativeLocator(self._loc.first, self._check_state)
|
|
46
|
+
|
|
47
|
+
def nth(self, index: int) -> _NativeLocator:
|
|
48
|
+
return _NativeLocator(self._loc.nth(int(index)), self._check_state)
|
|
49
|
+
|
|
50
|
+
async def count(self) -> int:
|
|
51
|
+
self._check()
|
|
52
|
+
return int(await self._loc.count())
|
|
53
|
+
|
|
54
|
+
async def click(self, *, timeout_ms: int = 10_000, force: bool = False) -> None:
|
|
55
|
+
self._check()
|
|
56
|
+
kwargs: dict[str, Any] = {"timeout": timeout_ms}
|
|
57
|
+
if force:
|
|
58
|
+
kwargs["force"] = True
|
|
59
|
+
await self._loc.click(**kwargs)
|
|
60
|
+
|
|
61
|
+
async def fill(self, value: str, *, timeout_ms: int = 10_000) -> None:
|
|
62
|
+
self._check()
|
|
63
|
+
await self._loc.fill(value, timeout=timeout_ms)
|
|
64
|
+
|
|
65
|
+
async def select_option(self, value: str, *, timeout_ms: int = 10_000) -> None:
|
|
66
|
+
self._check()
|
|
67
|
+
await self._loc.select_option(value, timeout=timeout_ms)
|
|
68
|
+
|
|
69
|
+
async def press(self, key: str, *, timeout_ms: int = 5_000) -> None:
|
|
70
|
+
self._check()
|
|
71
|
+
await self._loc.press(key, timeout=timeout_ms)
|
|
72
|
+
|
|
73
|
+
async def inner_text(self, *, timeout_ms: int = 5_000) -> str:
|
|
74
|
+
self._check()
|
|
75
|
+
return str(await self._loc.inner_text(timeout=timeout_ms) or "")
|
|
76
|
+
|
|
77
|
+
async def get_attribute(self, name: str, *, timeout_ms: int = 5_000) -> str | None:
|
|
78
|
+
self._check()
|
|
79
|
+
val = await self._loc.get_attribute(name, timeout=timeout_ms)
|
|
80
|
+
return None if val is None else str(val)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class _NativeFrameLocator:
|
|
84
|
+
def __init__(self, fl: Any, check_state: Callable[[], None] | None = None) -> None:
|
|
85
|
+
self._fl = fl
|
|
86
|
+
self._check_state = check_state
|
|
87
|
+
|
|
88
|
+
def locator(self, selector: str) -> _NativeLocator:
|
|
89
|
+
return _NativeLocator(self._fl.locator(selector), self._check_state)
|
|
90
|
+
|
|
91
|
+
def frame_locator(self, selector: str) -> _NativeFrameLocator:
|
|
92
|
+
return _NativeFrameLocator(self._fl.frame_locator(selector), self._check_state)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class _NativeKeyboard:
|
|
96
|
+
def __init__(self, kb: Any) -> None:
|
|
97
|
+
self._kb = kb
|
|
98
|
+
|
|
99
|
+
async def press(self, key: str) -> None:
|
|
100
|
+
await self._kb.press(key)
|
|
101
|
+
|
|
102
|
+
async def type(self, text: str) -> None:
|
|
103
|
+
await self._kb.type(text)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _supports_isolated_context(page: Any) -> bool:
|
|
107
|
+
eval_fn = getattr(page, "evaluate", None)
|
|
108
|
+
if eval_fn is None:
|
|
109
|
+
return False
|
|
110
|
+
try:
|
|
111
|
+
return "isolated_context" in inspect.signature(eval_fn).parameters
|
|
112
|
+
except (TypeError, ValueError):
|
|
113
|
+
return False
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class NativePage:
|
|
117
|
+
"""Async `Page` directly wrapping a Playwright or Patchright async Page."""
|
|
118
|
+
|
|
119
|
+
def __init__(self, page: Any, download_dir: Path, *, allowed_hosts: tuple[str, ...] = ()) -> None:
|
|
120
|
+
self._page = page
|
|
121
|
+
self._download_dir = Path(download_dir)
|
|
122
|
+
self._download_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
123
|
+
self._allowed_hosts = tuple(allowed_hosts)
|
|
124
|
+
self._has_isolated_ctx = _supports_isolated_context(page)
|
|
125
|
+
self._dl_seq = 0
|
|
126
|
+
|
|
127
|
+
def bind_page(self, page: Any) -> None:
|
|
128
|
+
self._page = page
|
|
129
|
+
self._has_isolated_ctx = _supports_isolated_context(page)
|
|
130
|
+
|
|
131
|
+
def _check_state(self) -> None:
|
|
132
|
+
if self._page.is_closed():
|
|
133
|
+
raise WindowClosedError("Browser window was closed")
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def keyboard(self) -> Keyboard:
|
|
137
|
+
self._check_state()
|
|
138
|
+
return _NativeKeyboard(self._page.keyboard)
|
|
139
|
+
|
|
140
|
+
async def url(self) -> str:
|
|
141
|
+
self._check_state()
|
|
142
|
+
return str(self._page.url or "")
|
|
143
|
+
|
|
144
|
+
async def goto(self, url: str, *, wait_until: str = "domcontentloaded", timeout_ms: int = 25_000) -> None:
|
|
145
|
+
self._check_state()
|
|
146
|
+
await self._page.goto(url, wait_until=wait_until, timeout=timeout_ms)
|
|
147
|
+
|
|
148
|
+
async def evaluate(self, expression: str, arg: Any = None, *, timeout_s: float = 60.0) -> Any:
|
|
149
|
+
self._check_state()
|
|
150
|
+
kwargs: dict[str, Any] = {"isolated_context": False} if self._has_isolated_ctx else {}
|
|
151
|
+
coro = (
|
|
152
|
+
self._page.evaluate(expression, **kwargs)
|
|
153
|
+
if arg is None
|
|
154
|
+
else self._page.evaluate(expression, arg, **kwargs)
|
|
155
|
+
)
|
|
156
|
+
return await asyncio.wait_for(coro, timeout=timeout_s)
|
|
157
|
+
|
|
158
|
+
def locator(self, selector: str) -> Locator:
|
|
159
|
+
return _NativeLocator(self._page.locator(selector), self._check_state)
|
|
160
|
+
|
|
161
|
+
def frame_locator(self, selector: str) -> FrameLocator:
|
|
162
|
+
return _NativeFrameLocator(self._page.frame_locator(selector), self._check_state)
|
|
163
|
+
|
|
164
|
+
async def wait_for_selector(self, selector: str, *, timeout_ms: int = 15_000) -> None:
|
|
165
|
+
self._check_state()
|
|
166
|
+
await self._page.wait_for_selector(selector, timeout=timeout_ms)
|
|
167
|
+
|
|
168
|
+
async def sleep(self, seconds: float) -> None:
|
|
169
|
+
await asyncio.sleep(max(0.0, float(seconds)))
|
|
170
|
+
|
|
171
|
+
async def download(
|
|
172
|
+
self,
|
|
173
|
+
trigger: DownloadTrigger,
|
|
174
|
+
*,
|
|
175
|
+
suffixes: tuple[str, ...] = (),
|
|
176
|
+
timeout_s: float = 30.0,
|
|
177
|
+
) -> Path:
|
|
178
|
+
self._check_state()
|
|
179
|
+
self._dl_seq += 1
|
|
180
|
+
seq = self._dl_seq
|
|
181
|
+
trigger_done = False
|
|
182
|
+
try:
|
|
183
|
+
async with self._page.expect_download(timeout=int(max(1.0, timeout_s) * 1000)) as dl_info:
|
|
184
|
+
if isinstance(trigger, Click):
|
|
185
|
+
target: Any = self._page
|
|
186
|
+
for frame_sel in trigger.frames:
|
|
187
|
+
target = target.frame_locator(frame_sel)
|
|
188
|
+
click_kwargs: dict[str, Any] = {"timeout": trigger.timeout_ms}
|
|
189
|
+
if trigger.force:
|
|
190
|
+
click_kwargs["force"] = True
|
|
191
|
+
loc = target.locator(trigger.selector)
|
|
192
|
+
chosen = loc.first if trigger.nth == 0 else loc.nth(trigger.nth)
|
|
193
|
+
await chosen.click(**click_kwargs)
|
|
194
|
+
elif isinstance(trigger, Evaluate):
|
|
195
|
+
await self.evaluate(trigger.expression, trigger.arg, timeout_s=timeout_s)
|
|
196
|
+
else:
|
|
197
|
+
raise TypeError(f"Unsupported download trigger: {trigger!r}")
|
|
198
|
+
trigger_done = True
|
|
199
|
+
dl = await asyncio.wait_for(dl_info.value, timeout=timeout_s)
|
|
200
|
+
except Exception as exc:
|
|
201
|
+
if trigger_done and (isinstance(exc, (asyncio.TimeoutError, TimeoutError)) or type(exc).__name__ == "TimeoutError"):
|
|
202
|
+
raise DownloadTimeoutError(f"Timed out waiting for download ({suffixes or 'any'}) after {timeout_s}s") from exc
|
|
203
|
+
raise
|
|
204
|
+
raw_suggested = str(getattr(dl, "suggested_filename", "") or f"download-{seq}.bin")
|
|
205
|
+
try:
|
|
206
|
+
suggested = sanitize_filename(raw_suggested)
|
|
207
|
+
except ValueError:
|
|
208
|
+
suggested = f"download-{seq}.bin"
|
|
209
|
+
if suffixes and not any(suggested.lower().endswith(s.lower()) for s in suffixes):
|
|
210
|
+
if hasattr(dl, "delete"):
|
|
211
|
+
with contextlib.suppress(Exception):
|
|
212
|
+
await dl.delete()
|
|
213
|
+
raise DownloadMismatchError(f"Downloaded file {suggested!r} did not match expected suffixes {suffixes!r}")
|
|
214
|
+
dest = self._download_dir / f"{seq:03d}-{suggested}"
|
|
215
|
+
await asyncio.wait_for(dl.save_as(str(dest)), timeout=timeout_s)
|
|
216
|
+
return dest
|
|
217
|
+
|
|
218
|
+
async def fetch_bytes(
|
|
219
|
+
self,
|
|
220
|
+
url: str,
|
|
221
|
+
*,
|
|
222
|
+
same_origin_only: bool = True,
|
|
223
|
+
timeout_s: float = 45.0,
|
|
224
|
+
max_bytes: int = 32 * 1024 * 1024,
|
|
225
|
+
) -> tuple[bytes, str]:
|
|
226
|
+
return await fetch_same_origin_bytes(
|
|
227
|
+
self,
|
|
228
|
+
url,
|
|
229
|
+
allowed_hosts=self._allowed_hosts,
|
|
230
|
+
same_origin_only=same_origin_only,
|
|
231
|
+
timeout_s=timeout_s,
|
|
232
|
+
max_bytes=max_bytes,
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _spawn_task(tasks: set[asyncio.Task[Any]], coro: Any) -> None:
|
|
237
|
+
task = asyncio.create_task(coro)
|
|
238
|
+
tasks.add(task)
|
|
239
|
+
task.add_done_callback(tasks.discard)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
async def _attach_cdp_host_guard(
|
|
243
|
+
ctx: Any,
|
|
244
|
+
page: Any,
|
|
245
|
+
allowed_hosts: tuple[str, ...],
|
|
246
|
+
*,
|
|
247
|
+
tasks: set[asyncio.Task[Any]] | None = None,
|
|
248
|
+
) -> bool:
|
|
249
|
+
"""Enforce top-level Document host confinement via native Chromium CDP `Fetch.enable`.
|
|
250
|
+
|
|
251
|
+
Intercepts every top-level navigation AND every HTTP 3xx redirect hop (GET/HEAD/POST/multi-hop)
|
|
252
|
+
before Chromium contacts a disallowed host, while preserving Chromium's native TLS stack,
|
|
253
|
+
`page.goto()` redirect semantics, and streaming 302-to-attachment downloads. Subframes are left
|
|
254
|
+
unblocked so 3rd-party CAPTCHA/2FA iframes continue to work.
|
|
255
|
+
"""
|
|
256
|
+
if not hasattr(ctx, "new_cdp_session"):
|
|
257
|
+
return False
|
|
258
|
+
task_bag = tasks if tasks is not None else set()
|
|
259
|
+
try:
|
|
260
|
+
cdp = await ctx.new_cdp_session(page)
|
|
261
|
+
if not hasattr(cdp, "on"):
|
|
262
|
+
return False
|
|
263
|
+
tree = await cdp.send("Page.getFrameTree")
|
|
264
|
+
main_frame_id = str(((tree or {}).get("frameTree") or {}).get("frame", {}).get("id") or "")
|
|
265
|
+
await cdp.send("Fetch.enable", {"patterns": [{"resourceType": "Document", "requestStage": "Request"}]})
|
|
266
|
+
except Exception as exc:
|
|
267
|
+
log.debug("CDP Fetch guard unavailable, falling back to route guard: %s", exc)
|
|
268
|
+
return False
|
|
269
|
+
|
|
270
|
+
async def _on_paused(params: dict[str, Any]) -> None:
|
|
271
|
+
req_id = params.get("requestId")
|
|
272
|
+
if not req_id:
|
|
273
|
+
return
|
|
274
|
+
url = str((params.get("request") or {}).get("url") or "")
|
|
275
|
+
frame_id = str(params.get("frameId") or "")
|
|
276
|
+
is_top = (not main_frame_id) or (not frame_id) or (frame_id == main_frame_id)
|
|
277
|
+
try:
|
|
278
|
+
if is_top and not allowed_document(url, hosts=allowed_hosts):
|
|
279
|
+
await cdp.send("Fetch.failRequest", {"requestId": req_id, "errorReason": "BlockedByClient"})
|
|
280
|
+
else:
|
|
281
|
+
await cdp.send("Fetch.continueRequest", {"requestId": req_id})
|
|
282
|
+
except Exception:
|
|
283
|
+
pass
|
|
284
|
+
|
|
285
|
+
cdp.on("Fetch.requestPaused", lambda p: _spawn_task(task_bag, _on_paused(p)))
|
|
286
|
+
return True
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
async def _safe_goto(page: Any, url: str) -> None:
|
|
290
|
+
with contextlib.suppress(Exception):
|
|
291
|
+
await page.goto(url, wait_until="domcontentloaded", timeout=30_000)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
async def _install_host_guard(
|
|
295
|
+
ctx: Any,
|
|
296
|
+
page: Any,
|
|
297
|
+
allowed_hosts: tuple[str, ...],
|
|
298
|
+
*,
|
|
299
|
+
tasks: set[asyncio.Task[Any]] | None = None,
|
|
300
|
+
) -> None:
|
|
301
|
+
"""Install combined context-level route guard + race-free per-page CDP `Fetch.enable` guard.
|
|
302
|
+
|
|
303
|
+
Context-level `ctx.route` blocks disallowed direct navigations even on newly opened popups
|
|
304
|
+
(`target="_blank"` / `window.open`) before any network egress. For any popup whose first
|
|
305
|
+
navigation starts before CDP `Fetch.enable` is active, it attaches CDP and resolves any
|
|
306
|
+
redirect chain hop-by-hop (up to 10 hops) so multi-hop popup redirects cannot escape confinement.
|
|
307
|
+
"""
|
|
308
|
+
task_bag = tasks if tasks is not None else set()
|
|
309
|
+
cdp_supported = await _attach_cdp_host_guard(ctx, page, allowed_hosts, tasks=task_bag)
|
|
310
|
+
guarded_pages: weakref.WeakSet[Any] = weakref.WeakSet()
|
|
311
|
+
if cdp_supported:
|
|
312
|
+
guarded_pages.add(page)
|
|
313
|
+
page_locks: weakref.WeakKeyDictionary[Any, asyncio.Lock] = weakref.WeakKeyDictionary()
|
|
314
|
+
|
|
315
|
+
async def _guard(route: Any) -> None:
|
|
316
|
+
req = route.request
|
|
317
|
+
is_top = False
|
|
318
|
+
req_page: Any = None
|
|
319
|
+
if req.is_navigation_request():
|
|
320
|
+
try:
|
|
321
|
+
frame = req.frame
|
|
322
|
+
is_top = frame is None or getattr(frame, "parent_frame", None) is None
|
|
323
|
+
if is_top and frame is not None:
|
|
324
|
+
req_page = getattr(frame, "page", None)
|
|
325
|
+
except Exception:
|
|
326
|
+
is_top = True
|
|
327
|
+
if is_top and not allowed_document(req.url, hosts=allowed_hosts):
|
|
328
|
+
await route.abort()
|
|
329
|
+
return
|
|
330
|
+
if is_top and (not cdp_supported or req_page is None or req_page not in guarded_pages):
|
|
331
|
+
if cdp_supported and req_page is not None and req_page not in guarded_pages:
|
|
332
|
+
lock = page_locks.get(req_page)
|
|
333
|
+
if lock is None:
|
|
334
|
+
lock = asyncio.Lock()
|
|
335
|
+
page_locks[req_page] = lock
|
|
336
|
+
async with lock:
|
|
337
|
+
if req_page not in guarded_pages:
|
|
338
|
+
if await _attach_cdp_host_guard(ctx, req_page, allowed_hosts, tasks=task_bag):
|
|
339
|
+
guarded_pages.add(req_page)
|
|
340
|
+
# Popup's first navigation (or non-CDP fallback) is not covered by CDP Fetch.enable yet;
|
|
341
|
+
# resolve any 3xx redirect chain hop-by-hop before continuing.
|
|
342
|
+
if hasattr(route, "fetch"):
|
|
343
|
+
cur_url = req.url
|
|
344
|
+
cur_method = str(getattr(req, "method", "GET") or "GET").upper()
|
|
345
|
+
try:
|
|
346
|
+
resp = await route.fetch(max_redirects=0)
|
|
347
|
+
except Exception:
|
|
348
|
+
await route.abort()
|
|
349
|
+
return
|
|
350
|
+
for _hop in range(10):
|
|
351
|
+
if not (300 <= resp.status < 400):
|
|
352
|
+
break
|
|
353
|
+
loc = resp.headers.get("location") or resp.headers.get("Location") or ""
|
|
354
|
+
if not loc:
|
|
355
|
+
break
|
|
356
|
+
dest = urljoin(cur_url, loc.strip())
|
|
357
|
+
if not allowed_document(dest, hosts=allowed_hosts):
|
|
358
|
+
await route.abort()
|
|
359
|
+
return
|
|
360
|
+
if req_page is not None and req_page in guarded_pages:
|
|
361
|
+
await route.abort()
|
|
362
|
+
_spawn_task(task_bag, _safe_goto(req_page, dest))
|
|
363
|
+
return
|
|
364
|
+
cur_url = dest
|
|
365
|
+
if resp.status in (307, 308):
|
|
366
|
+
next_method = cur_method
|
|
367
|
+
if next_method not in ("GET", "HEAD"):
|
|
368
|
+
await route.abort()
|
|
369
|
+
return
|
|
370
|
+
else:
|
|
371
|
+
next_method = "GET"
|
|
372
|
+
cur_method = next_method
|
|
373
|
+
try:
|
|
374
|
+
resp = await route.fetch(url=dest, method=next_method, max_redirects=0)
|
|
375
|
+
except Exception:
|
|
376
|
+
await route.abort()
|
|
377
|
+
return
|
|
378
|
+
else:
|
|
379
|
+
# Exceeded redirect hop limit -> fail closed.
|
|
380
|
+
await route.abort()
|
|
381
|
+
return
|
|
382
|
+
await route.fulfill(response=resp)
|
|
383
|
+
return
|
|
384
|
+
await route.continue_()
|
|
385
|
+
|
|
386
|
+
await ctx.route("**/*", _guard)
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def check_playwright_available() -> dict[str, Any]:
|
|
390
|
+
"""Check whether Playwright (or Patchright) and a Chromium executable are available."""
|
|
391
|
+
pkg = ""
|
|
392
|
+
factory: Any = None
|
|
393
|
+
for mod_name in ("playwright.async_api", "patchright.async_api"):
|
|
394
|
+
try:
|
|
395
|
+
mod = __import__(mod_name, fromlist=["async_playwright"])
|
|
396
|
+
factory = getattr(mod, "async_playwright", None)
|
|
397
|
+
if factory is not None:
|
|
398
|
+
pkg = mod_name.split(".", 1)[0]
|
|
399
|
+
break
|
|
400
|
+
except ImportError:
|
|
401
|
+
continue
|
|
402
|
+
if factory is None:
|
|
403
|
+
return {
|
|
404
|
+
"ok": False,
|
|
405
|
+
"error": "playwright not installed (install with: pip install playwright && playwright install chromium)",
|
|
406
|
+
}
|
|
407
|
+
try:
|
|
408
|
+
sync_mod = __import__(f"{pkg}.sync_api", fromlist=["sync_playwright"])
|
|
409
|
+
sync_playwright = sync_mod.sync_playwright
|
|
410
|
+
|
|
411
|
+
with sync_playwright() as pw:
|
|
412
|
+
exe = Path(pw.chromium.executable_path)
|
|
413
|
+
if exe.is_file():
|
|
414
|
+
return {"ok": True, "package": pkg, "executable": str(exe)}
|
|
415
|
+
return {
|
|
416
|
+
"ok": False,
|
|
417
|
+
"package": pkg,
|
|
418
|
+
"error": f"Chromium executable missing at {exe} (run: playwright install chromium)",
|
|
419
|
+
}
|
|
420
|
+
except Exception:
|
|
421
|
+
# Sync check unavailable inside running loop or headless driver; report package present.
|
|
422
|
+
return {"ok": True, "package": pkg}
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
class PlaywrightHost:
|
|
426
|
+
"""Default local browser host using Playwright/Chromium with a `0700` download dir and CDP host confinement."""
|
|
427
|
+
|
|
428
|
+
name = "playwright"
|
|
429
|
+
|
|
430
|
+
def __init__(
|
|
431
|
+
self,
|
|
432
|
+
*,
|
|
433
|
+
headless: bool = False,
|
|
434
|
+
channel: str | None = None,
|
|
435
|
+
playwright_factory: Callable[[], Any] | None = None,
|
|
436
|
+
) -> None:
|
|
437
|
+
self._headless = headless
|
|
438
|
+
self._channel = channel
|
|
439
|
+
self._factory = playwright_factory
|
|
440
|
+
self._pw_cm: Any = None
|
|
441
|
+
self._browser: Any = None
|
|
442
|
+
self._ctx: Any = None
|
|
443
|
+
self._dl_dir: Path | None = None
|
|
444
|
+
self._guard_tasks: set[asyncio.Task[Any]] = set()
|
|
445
|
+
|
|
446
|
+
async def __aenter__(self) -> PlaywrightHost:
|
|
447
|
+
return self
|
|
448
|
+
|
|
449
|
+
async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
|
|
450
|
+
await self.close()
|
|
451
|
+
|
|
452
|
+
def _resolve_factory(self) -> Callable[[], Any]:
|
|
453
|
+
if self._factory is not None:
|
|
454
|
+
return self._factory
|
|
455
|
+
for mod_name in ("playwright.async_api", "patchright.async_api"):
|
|
456
|
+
try:
|
|
457
|
+
mod = __import__(mod_name, fromlist=["async_playwright"])
|
|
458
|
+
factory = getattr(mod, "async_playwright", None)
|
|
459
|
+
if factory is not None:
|
|
460
|
+
return factory
|
|
461
|
+
except ImportError:
|
|
462
|
+
continue
|
|
463
|
+
raise RuntimeError(
|
|
464
|
+
"PlaywrightHost requires playwright. "
|
|
465
|
+
"Install with: pip install playwright && playwright install chromium"
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
async def open(self, url: str, *, allowed_hosts: tuple[str, ...]) -> Page:
|
|
469
|
+
if self._browser is not None or self._ctx is not None or self._pw_cm is not None:
|
|
470
|
+
raise RuntimeError("PlaywrightHost is already open; call close() before reopening.")
|
|
471
|
+
factory = self._resolve_factory()
|
|
472
|
+
self._dl_dir = Path(tempfile.mkdtemp(prefix="sf-pw-dl-"))
|
|
473
|
+
os.chmod(self._dl_dir, 0o700)
|
|
474
|
+
try:
|
|
475
|
+
self._pw_cm = factory()
|
|
476
|
+
pw = await self._pw_cm.__aenter__()
|
|
477
|
+
launch_kwargs: dict[str, Any] = {"headless": self._headless}
|
|
478
|
+
if self._channel:
|
|
479
|
+
launch_kwargs["channel"] = self._channel
|
|
480
|
+
self._browser = await pw.chromium.launch(**launch_kwargs)
|
|
481
|
+
self._ctx = await self._browser.new_context(accept_downloads=True)
|
|
482
|
+
page = await self._ctx.new_page()
|
|
483
|
+
await _install_host_guard(self._ctx, page, allowed_hosts, tasks=self._guard_tasks)
|
|
484
|
+
await page.goto(url, wait_until="domcontentloaded", timeout=60_000)
|
|
485
|
+
return NativePage(page, self._dl_dir, allowed_hosts=allowed_hosts)
|
|
486
|
+
except BaseException:
|
|
487
|
+
await self.close()
|
|
488
|
+
raise
|
|
489
|
+
|
|
490
|
+
async def close(self) -> None:
|
|
491
|
+
pending = list(self._guard_tasks)
|
|
492
|
+
self._guard_tasks.clear()
|
|
493
|
+
for task in pending:
|
|
494
|
+
if not task.done():
|
|
495
|
+
task.cancel()
|
|
496
|
+
try:
|
|
497
|
+
if pending:
|
|
498
|
+
with contextlib.suppress(Exception):
|
|
499
|
+
await asyncio.gather(*pending, return_exceptions=True)
|
|
500
|
+
if self._ctx is not None:
|
|
501
|
+
ctx, self._ctx = self._ctx, None
|
|
502
|
+
with contextlib.suppress(Exception):
|
|
503
|
+
await ctx.close()
|
|
504
|
+
if self._browser is not None:
|
|
505
|
+
browser, self._browser = self._browser, None
|
|
506
|
+
with contextlib.suppress(Exception):
|
|
507
|
+
await browser.close()
|
|
508
|
+
if self._pw_cm is not None:
|
|
509
|
+
pw_cm, self._pw_cm = self._pw_cm, None
|
|
510
|
+
with contextlib.suppress(Exception):
|
|
511
|
+
await pw_cm.__aexit__(None, None, None)
|
|
512
|
+
finally:
|
|
513
|
+
self._ctx = None
|
|
514
|
+
self._browser = None
|
|
515
|
+
self._pw_cm = None
|
|
516
|
+
if self._dl_dir is not None:
|
|
517
|
+
dl_dir, self._dl_dir = self._dl_dir, None
|
|
518
|
+
shutil.rmtree(dl_dir, ignore_errors=True)
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Lazy, duplicate-rejecting plugin registry backed by `importlib.metadata.entry_points`."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import importlib.metadata
|
|
5
|
+
import inspect
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from ._contracts import (
|
|
9
|
+
PROVIDER_ENTRY_POINT_GROUP,
|
|
10
|
+
SINK_ENTRY_POINT_GROUP,
|
|
11
|
+
DuplicatePluginError,
|
|
12
|
+
Provider,
|
|
13
|
+
Sink,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _instantiate_plugin(loaded: Any) -> Any:
|
|
18
|
+
"""Instantiate a loaded entry point when it is a class or zero-arg factory."""
|
|
19
|
+
if inspect.isclass(loaded):
|
|
20
|
+
return loaded()
|
|
21
|
+
if callable(loaded) and not (hasattr(loaded, "spec") or hasattr(loaded, "deliver")):
|
|
22
|
+
return loaded()
|
|
23
|
+
return loaded
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _target_qualname(obj: Any) -> str:
|
|
27
|
+
if inspect.isfunction(obj) or inspect.isclass(obj):
|
|
28
|
+
return f"{obj.__module__}:{obj.__qualname__}"
|
|
29
|
+
cls = type(obj)
|
|
30
|
+
return f"{cls.__module__}:{cls.__qualname__}"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class PluginRegistry:
|
|
34
|
+
"""Lazy, duplicate-rejecting registry for providers and sinks."""
|
|
35
|
+
|
|
36
|
+
def __init__(self) -> None:
|
|
37
|
+
self._providers: dict[str, Provider] = {}
|
|
38
|
+
self._sinks: dict[str, Sink] = {}
|
|
39
|
+
self._provider_eps: dict[str, Any] = {}
|
|
40
|
+
self._sink_eps: dict[str, Any] = {}
|
|
41
|
+
self._discovered = False
|
|
42
|
+
|
|
43
|
+
def register_provider(self, provider: Provider) -> None:
|
|
44
|
+
if not isinstance(provider, Provider):
|
|
45
|
+
raise TypeError(f"Object does not implement Provider protocol: {provider!r}")
|
|
46
|
+
pid = provider.spec.id.strip().lower()
|
|
47
|
+
if pid in self._providers or pid in self._provider_eps:
|
|
48
|
+
raise DuplicatePluginError(f"Duplicate provider id registered: {pid!r}")
|
|
49
|
+
self._providers[pid] = provider
|
|
50
|
+
|
|
51
|
+
def register_sink(self, sink: Sink) -> None:
|
|
52
|
+
if not isinstance(sink, Sink):
|
|
53
|
+
raise TypeError(f"Object does not implement Sink protocol: {sink!r}")
|
|
54
|
+
sid = sink.id.strip().lower()
|
|
55
|
+
if sid in self._sinks or sid in self._sink_eps:
|
|
56
|
+
raise DuplicatePluginError(f"Duplicate sink id registered: {sid!r}")
|
|
57
|
+
self._sinks[sid] = sink
|
|
58
|
+
|
|
59
|
+
def discover_entry_points(self) -> None:
|
|
60
|
+
"""Index installed entry points lazily; raise `DuplicatePluginError` on conflicts."""
|
|
61
|
+
if self._discovered:
|
|
62
|
+
return
|
|
63
|
+
new_provider_eps: dict[str, Any] = dict(self._provider_eps)
|
|
64
|
+
new_sink_eps: dict[str, Any] = dict(self._sink_eps)
|
|
65
|
+
|
|
66
|
+
for ep in importlib.metadata.entry_points(group=PROVIDER_ENTRY_POINT_GROUP):
|
|
67
|
+
name = (ep.name or "").strip().lower()
|
|
68
|
+
if name in new_provider_eps:
|
|
69
|
+
if getattr(new_provider_eps[name], "value", None) == getattr(ep, "value", None):
|
|
70
|
+
continue
|
|
71
|
+
raise DuplicatePluginError(f"Duplicate provider entry point: {name!r}")
|
|
72
|
+
if name in self._providers:
|
|
73
|
+
if _target_qualname(self._providers[name]) == getattr(ep, "value", None):
|
|
74
|
+
continue
|
|
75
|
+
raise DuplicatePluginError(f"Provider entry point {name!r} conflicts with registered built-in")
|
|
76
|
+
new_provider_eps[name] = ep
|
|
77
|
+
|
|
78
|
+
for ep in importlib.metadata.entry_points(group=SINK_ENTRY_POINT_GROUP):
|
|
79
|
+
name = (ep.name or "").strip().lower()
|
|
80
|
+
if name in new_sink_eps:
|
|
81
|
+
if getattr(new_sink_eps[name], "value", None) == getattr(ep, "value", None):
|
|
82
|
+
continue
|
|
83
|
+
raise DuplicatePluginError(f"Duplicate sink entry point: {name!r}")
|
|
84
|
+
if name in self._sinks:
|
|
85
|
+
if _target_qualname(self._sinks[name]) == getattr(ep, "value", None):
|
|
86
|
+
continue
|
|
87
|
+
raise DuplicatePluginError(f"Sink entry point {name!r} conflicts with registered built-in")
|
|
88
|
+
new_sink_eps[name] = ep
|
|
89
|
+
|
|
90
|
+
self._provider_eps = new_provider_eps
|
|
91
|
+
self._sink_eps = new_sink_eps
|
|
92
|
+
self._discovered = True
|
|
93
|
+
|
|
94
|
+
def get_provider(self, provider_id: str) -> Provider:
|
|
95
|
+
self.discover_entry_points()
|
|
96
|
+
key = (provider_id or "").strip().lower()
|
|
97
|
+
if key in self._providers:
|
|
98
|
+
return self._providers[key]
|
|
99
|
+
if key in self._provider_eps:
|
|
100
|
+
inst = _instantiate_plugin(self._provider_eps[key].load())
|
|
101
|
+
if not isinstance(inst, Provider):
|
|
102
|
+
raise TypeError(f"Entry point {key!r} did not load a Provider instance: {inst!r}")
|
|
103
|
+
if inst.spec.id.strip().lower() != key:
|
|
104
|
+
raise ValueError(f"Entry point {key!r} loaded provider with mismatched id {inst.spec.id!r}")
|
|
105
|
+
self._providers[key] = inst
|
|
106
|
+
return inst
|
|
107
|
+
available = ", ".join(sorted(set(self._providers) | set(self._provider_eps)))
|
|
108
|
+
raise ValueError(f"Unknown provider {provider_id!r}. Available: {available or '(none)'}")
|
|
109
|
+
|
|
110
|
+
def get_sink(self, sink_id: str) -> Sink:
|
|
111
|
+
self.discover_entry_points()
|
|
112
|
+
key = (sink_id or "").strip().lower()
|
|
113
|
+
if key in self._sinks:
|
|
114
|
+
return self._sinks[key]
|
|
115
|
+
if key in self._sink_eps:
|
|
116
|
+
inst = _instantiate_plugin(self._sink_eps[key].load())
|
|
117
|
+
if not isinstance(inst, Sink):
|
|
118
|
+
raise TypeError(f"Entry point {key!r} did not load a Sink instance: {inst!r}")
|
|
119
|
+
if inst.id.strip().lower() != key:
|
|
120
|
+
raise ValueError(f"Entry point {key!r} loaded sink with mismatched id {inst.id!r}")
|
|
121
|
+
self._sinks[key] = inst
|
|
122
|
+
return inst
|
|
123
|
+
available = ", ".join(sorted(set(self._sinks) | set(self._sink_eps)))
|
|
124
|
+
raise ValueError(f"Unknown sink {sink_id!r}. Available: {available or '(none)'}")
|
|
125
|
+
|
|
126
|
+
def list_provider_ids(self) -> list[str]:
|
|
127
|
+
self.discover_entry_points()
|
|
128
|
+
return sorted(set(self._providers) | set(self._provider_eps))
|
|
129
|
+
|
|
130
|
+
def list_sink_ids(self) -> list[str]:
|
|
131
|
+
self.discover_entry_points()
|
|
132
|
+
return sorted(set(self._sinks) | set(self._sink_eps))
|