Files
chemenu/tools/chemenu/fetch_routes.py
T
torbenandClaude Opus 5.5 5994b2a88c
CI / verify (push) Successful in 8m8s
CI / pwsh (push) Successful in 2m40s
Release / release (push) Successful in 35s
Release / wiki-mirror (push) Skipped
raw: fetch behind a login - raw login stores the user's session as a secret outside the tree, fetch.routes sends a host through it or to an external fetcher, a handler's render goes through the optional browser component (preflight --with browser) (#169); 10.0.0-beta.8
Files changed:
- CHANGES.md
- INSTALL.md
- VERSION
- docs/how-to/README.md
- docs/how-to/fetch-pages-behind-a-login.md
- docs/how-to/ingest-a-source.md
- docs/reference/commands/README.md
- docs/reference/commands/instance-health.md
- docs/reference/commands/raw-material-and-uploads.md
- docs/reference/configuration.md
- docs/reference/exit-codes.md
- instructions/preflight.md
- instructions/wiki-ingest/SKILL.md
- raw/CONTRACT.md
- sites/CONTRACT.md
- tools/CONTRACT.md
- tools/README.md
- tools/chemenu/browser.py
- tools/chemenu/cli_contract.py
- tools/chemenu/commands/doctor.py
- tools/chemenu/commands/raw/__init__.py
- tools/chemenu/commands/raw/fetch.py
- tools/chemenu/commands/raw/login.py
- tools/chemenu/config_shapes.py
- tools/chemenu/fetch_routes.py
- tools/chemenu/reference_doc.py
- tools/chemenu/settings.py
- tools/chemenu/sites/__init__.py
- tools/chemenu/sites/data.py
- tools/chemenu/sites/site.schema.json
- tools/chemenu/tests/test_cli.py
- tools/chemenu/tests/test_config_shapes.py
- tools/chemenu/tests/test_doctor.py
- tools/chemenu/tests/test_preflight.py
- tools/chemenu/tests/test_preflight_pwsh.py
- tools/chemenu/tests/test_raw_fetch_routes.py
- tools/chemenu/tests/test_raw_login.py
- tools/chemenu/tests/test_site_files.py
- tools/chemenu/web_capture.py
- tools/chemenu/web_session.py
- tools/preflight.ps1
- tools/preflight.sh
- tools/requirements-browser.txt

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SnAJ7Z3CpVD3PRbN73QtU2
2026-10-11 20:50:23 +02:00

180 lines
8.2 KiB
Python

"""Which way a page is fetched: the built-in anonymous fetch, the user's own
session, or an external fetcher - and the fetch itself.
The instance decides per host (`fetch.routes`, tier `instance`):
- not listed: the built-in fetch, exactly as before - no cookie, no browser;
- `session`: the built-in fetch with the cookies of the session the user signed
in with through `raw login` (`chemenu.web_session`). The host's site handler
names the login page and how a page shows that it arrived signed in; a page
that did not, or no stored session at all, is `SessionNeeded` - exit 42,
because only the user can sign in again. A teaser is never kept in silence;
- any other value: an external fetcher of this checkout (`fetch.fetchers`, tier
`checkout`, never `instance` - it names a program to run). It is run without
a shell with the URL appended; exit 0 and HTML on stdout is the page,
anything else is an error, and the built-in fetch is never tried instead.
A site handler that declares `render` sends a fetch through a headless browser
instead of the built-in fetch, with the session when the route has one
(`chemenu.browser`); an external fetcher is its own fetch and is never rendered.
No `typer`, no `rich`: errors are `ChemenuError`s, and the CLI decides what each
one means for the exit code.
"""
from __future__ import annotations
import subprocess
import urllib.parse
from dataclasses import dataclass
from typing import Optional
from chemenu import browser, config, sites, web_capture, web_session
from chemenu.config_shapes import SESSION_ROUTE
from chemenu.errors import BackendError, ChemenuError, ValidationError
PLAIN = "plain"
SESSION = "session"
FETCHER = "fetcher"
FETCHER_TIMEOUT_SECONDS = 120
_STDERR_TAIL_CHARS = 2000
class SessionNeeded(ChemenuError):
"""No usable session for the host: none stored, or the page arrived
without the sign of being signed in. Only the user can sign in, so the CLI
renders this as exit 42."""
@dataclass(frozen=True)
class Route:
"""How one page is fetched. `session` is the handler's description of
the login, for a `SESSION` route; `command` the program and arguments of a
`FETCHER` route; `render` whether the page goes through a browser."""
host: str
kind: str = PLAIN
fetcher: str = ""
command: tuple[str, ...] = ()
session: Optional[sites.Session] = None
render: bool = False
instance_id: Optional[str] = None
@property
def fetched_by(self) -> str:
if self.kind == FETCHER:
return f"wikitool raw fetch (fetcher: {self.fetcher})"
return "wikitool raw fetch"
@property
def session_label(self) -> str:
return self.host if self.kind == SESSION else ""
def host_of(url: str) -> str:
return (urllib.parse.urlsplit(url).hostname or "").lower()
def route_for(plan: sites.Plan, preferences: sites.Preferences, section) -> Route:
"""The route for the page `plan` describes, from the `fetch` settings
`section` (`chemenu.settings.Section`). Raises `ValidationError` for a route
that cannot work: `session` for a host no handler names a login page for,
or a fetcher this checkout does not define."""
host = host_of(plan.url)
render = bool(plan.site and plan.site.render)
via = section["routes"].get(host)
if via is None:
return Route(host, render=render)
if via == SESSION_ROUTE:
login = sites.login_site(host, preferences.disabled, preferences.instance)
if login is None:
raise ValidationError(
f"fetch.routes sends {host} through the user's session, and no enabled site handler of "
f"that host names a login page - add a `session` block to a handler of {host} "
"(sites/CONTRACT.md), or remove the route."
)
own = plan.site.session if plan.site and plan.site.session else login.session
return Route(host, SESSION, session=own, render=render, instance_id=section.instance_id)
command = section["fetchers"].get(via)
if command is None:
raise ValidationError(
f"fetch.routes sends {host} to the fetcher {via!r}, which this checkout does not define - "
f"the user adds `fetch.fetchers.{via}` to {config.LOCAL_SETTINGS_FILENAME} by hand "
"(it names a program to run, so `config set` does not write it)."
)
return Route(host, FETCHER, fetcher=via, command=tuple(command))
def _login_hint(host: str) -> str:
return (f"Ask the user to run `tools/wikitool raw login {host}` - it opens a browser window for "
"them to sign in; never run it yourself. Nothing was written.")
def get(route: Route, url: str, user_agent: str) -> web_capture.Response:
"""Fetch `url` the way `route` says. Raises `SessionNeeded` when no
session is stored, `browser.BrowserMissing` when a rendered fetch has no
browser, and `BackendError`/`ValidationError` for everything else."""
if route.kind == FETCHER:
return run_fetcher(route, url)
state = None
if route.kind == SESSION:
state = web_session.load(route.host, route.instance_id)
if state is None:
raise SessionNeeded(f"{route.host} is fetched with the user's session, and none is stored. "
+ _login_hint(route.host))
if route.render:
return browser.render(url, user_agent, state)
# The built-in fetch exactly as before when there is no session to send.
extra = {"cookies": web_session.cookie_jar(state)} if state is not None else {}
return web_capture.fetch(
url, user_agent, timeout=web_capture.TIMEOUT_SECONDS, max_bytes=web_capture.MAX_BYTES, **extra
)
def check_signed_in(route: Route, response: web_capture.Response) -> None:
"""Raise `SessionNeeded` when a page fetched with the session did not
arrive signed in - the session expired, or the website ended it."""
if route.kind != SESSION or route.session is None or response.media_type not in web_capture.HTML_TYPES:
return
text = web_capture.decode(response.body, response.content_type).text
if not route.session.is_signed_in(text):
raise SessionNeeded(
f"{response.final_url} arrived without a valid session - the page does not show the sign of "
f"being signed in that the site handler names, so the session for {route.host} has expired "
"or was ended. " + _login_hint(route.host)
)
def _tail(stderr: bytes) -> str:
text = stderr.decode("utf-8", errors="replace").strip()
if len(text) > _STDERR_TAIL_CHARS:
text = "..." + text[-_STDERR_TAIL_CHARS:]
return text or "(nothing on stderr)"
def run_fetcher(route: Route, url: str, timeout: float = FETCHER_TIMEOUT_SECONDS,
max_bytes: int = web_capture.MAX_BYTES) -> web_capture.Response:
"""Run the external fetcher of `route` for `url`: no shell, the URL as the
last argument, stdin closed. Its stdout is the page, byte for byte."""
web_capture.check_url(url)
where = f"the fetcher {route.fetcher!r}"
try:
result = subprocess.run(
[*route.command, url], capture_output=True, stdin=subprocess.DEVNULL, timeout=timeout, check=False,
)
except FileNotFoundError:
raise BackendError(f"{where} could not be started: {route.command[0]} does not exist. Nothing was written.") from None
except subprocess.TimeoutExpired:
raise BackendError(f"{where} did not finish within {timeout:g} s for {url}. Nothing was written.") from None
except OSError as exc:
raise BackendError(f"{where} could not be started ({exc}). Nothing was written.") from None
if result.returncode != 0:
raise BackendError(
f"{where} ended with exit {result.returncode} for {url} - nothing was written, and the built-in "
f"fetch was not tried instead. Its stderr:\n{_tail(result.stderr)}"
)
if not result.stdout:
raise BackendError(f"{where} ended with exit 0 for {url} but printed nothing. Nothing was written.")
if len(result.stdout) > max_bytes:
raise BackendError(f"{where} printed more than {max_bytes // (1024 * 1024)} MiB for {url}. Nothing was written.")
return web_capture.Response(url, url, 0, "text/html", result.stdout)