Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.
fix(fetch): deadline read returns an already-buffered body; report content_bytes
Agrici Danielf67d1edf4bb2
diff --git a/scripts/fetch_page.py b/scripts/fetch_page.pyindex 25b71d2..a8f2ec1 100755--- a/scripts/fetch_page.py+++ b/scripts/fetch_page.py@@ -87,6 +87,8 @@ MAX_PAGE_BYTES = _MAX_PAGE_BYTES# Timing keys of a raw fetch, in the order they are documented._TIMING_KEYS = ("ttfb_ms", "response_time_ms", "fetch_duration_ms")+# Keys only a raw fetch fills in; a rendered result carries them as null.+_RAW_ONLY_KEYS = (*_TIMING_KEYS, "content_bytes")def _default_max_time(timeout: float) -> float:@@ -140,8 +142,12 @@ def fetch_page(Returns:Dictionary with url, status_code, content, headers, redirect_chain,- redirect_details, too_large, error, and three timings in- milliseconds, each None when it was not reached:+ redirect_details, too_large, error, content_bytes (the size of+ the body read, in bytes after decompression and before character+ decoding, so a windows-1251 page is not counted at its UTF-8 size;+ the part read when the body was cut short; None when no body was+ read), and three timings in milliseconds, each None when it was not+ reached:- ``ttfb_ms``: time to first byte of the final response, fromsending that request (a new connection and its TLS handshake@@ -172,6 +178,7 @@ def fetch_page("redirect_details": [],"too_large": False,"error": None,+ "content_bytes": None,"ttfb_ms": None,"response_time_ms": None,"fetch_duration_ms": None,@@ -228,6 +235,7 @@ def fetch_page(result["url"] = response.urlresult["status_code"] = response.status_coderesult["content"] = decode_body(raw, response.headers.get("Content-Type", ""))+ result["content_bytes"] = len(raw)result["headers"] = dict(response.headers)if response.history:@@ -307,7 +315,7 @@ def _as_render_result(result: dict, *, mode_used: str) -> dict:"mode_used": mode_used,"too_large": bool(result.get("too_large")),"error": result.get("error"),- **{key: result.get(key) for key in _TIMING_KEYS},+ **{key: result.get(key) for key in _RAW_ONLY_KEYS},}@@ -320,9 +328,9 @@ def _emit_json(result: dict, output: Optional[str], *, max_text: int = 0) -> Non"""from render_page import _json_summary- # A rendered result reports render_ms, not the raw-fetch timings; they- # are null there so both paths keep one key set.- for key in _TIMING_KEYS:+ # A rendered result reports render_ms, not the raw-fetch timings or+ # body size; those are null there so both paths keep one key set.+ for key in _RAW_ONLY_KEYS:result.setdefault(key, None)output_written = Falsediff --git a/scripts/url_safety.py b/scripts/url_safety.pyindex 45404aa..cdcd23a 100644--- a/scripts/url_safety.py+++ b/scripts/url_safety.py@@ -1095,9 +1095,16 @@ def _iter_as_received(response, chunk_size: int = 65536) -> Iterator[bytes]:urllib3's ``read1`` returns what a single read brings, still decompressedand at most ``chunk_size`` bytes. Errors are mapped to the requestsexceptions ``iter_content`` raises.++ A body that is already in memory has nothing left on the socket:+ requests read it itself (``stream=False``), or the redirect hook filled+ in a 3xx body and closed the connection. ``iter_content`` replays that+ body, and cannot block doing so."""raw = getattr(response, "raw", None)- if not isinstance(raw, _Urllib3Response): # A test double, not a socket.+ if getattr(response, "_content_consumed", False) or not isinstance(+ raw, _Urllib3Response # Anything else is a test double, not a socket.+ ):yield from response.iter_content(chunk_size=chunk_size)returntry:diff --git a/tests/test_fetch_page_cli.py b/tests/test_fetch_page_cli.pyindex b12a14a..276e112 100644--- a/tests/test_fetch_page_cli.py+++ b/tests/test_fetch_page_cli.py@@ -79,8 +79,8 @@ def _expected_json(raw_source: dict, *, mode: str, output_written: bool, max_texraw_source if mode != "never" else fetch_page._as_render_result(raw_source, mode_used="raw"))summary = render_page._json_summary(normalized, max_text=max_text)- # Raw-fetch timings: null on a rendered result, so both paths share keys.- for key in fetch_page._TIMING_KEYS:+ # Raw-only keys: null on a rendered result, so both paths share keys.+ for key in fetch_page._RAW_ONLY_KEYS:summary.setdefault(key, None)summary["output_written"] = output_writtenreturn json.loads(json.dumps(summary, default=str))diff --git a/tests/test_fetch_page_timing.py b/tests/test_fetch_page_timing.pyindex 8a7ac69..d1eac93 100644--- a/tests/test_fetch_page_timing.py+++ b/tests/test_fetch_page_timing.py@@ -33,6 +33,8 @@ import url_safety # noqa: E402DRIP_BYTES = 400DRIP_INTERVAL = 0.02 # the whole drip takes about 8 seconds if nothing stops itTIMING_KEYS = ("ttfb_ms", "response_time_ms", "fetch_duration_ms")+CYRILLIC_TEXT = "<html><title>" + "Привет, мир. " * 40 + "</title></html>"+CYRILLIC_BYTES = CYRILLIC_TEXT.encode("windows-1251")class _Handler(http.server.BaseHTTPRequestHandler):@@ -48,6 +50,19 @@ class _Handler(http.server.BaseHTTPRequestHandler):elif self.path == "/slow-redirect":time.sleep(0.2)self._headers(302, {"Location": "/slow-final", "Content-Length": "0"})+ elif self.path == "/moved":+ self._headers(302, {"Location": "/plain", "Content-Length": "15"})+ self.wfile.write(b"moved-body-here")+ elif self.path == "/not-modified":+ self._headers(304, {})+ elif self.path == "/cyrillic":+ self.send_response(200)+ self.send_header("Content-Type", "text/html; charset=windows-1251")+ self.send_header("Content-Length", str(len(CYRILLIC_BYTES)))+ self.send_header("Connection", "close")+ self.end_headers()+ self.close_connection = True+ self.wfile.write(CYRILLIC_BYTES)elif self.path == "/slow-final":time.sleep(0.1)self._headers(200, {"Content-Length": "5"})@@ -57,6 +72,9 @@ class _Handler(http.server.BaseHTTPRequestHandler):self._headers(200, {"Content-Length": "5"})self.wfile.write(b"plain")+ def do_HEAD(self): # noqa: N802 (http.server API)+ self._headers(200, {"Content-Length": "5"})+def _headers(self, status: int, headers: dict) -> None:self.send_response(status)self.send_header("Content-Type", "text/html; charset=utf-8")@@ -150,6 +168,100 @@ def test_timing_fields_separate_the_final_request_from_the_redirect_hops(server)assert result["fetch_duration_ms"] >= result["response_time_ms"] + 190+# ---------------------------------------------------------------------------+# A body that was already read before the deadline reader sees the response+# ---------------------------------------------------------------------------+++def test_unfollowed_redirect_keeps_its_body(server):+ """The redirect hook reads a 3xx body into the response and closes the+ socket. --no-redirects must still return that body, as it did before the+ deadline reader replaced read_bounded here."""+ result = fetch_page.fetch_page(f"{server}/moved", timeout=5, follow_redirects=False)+ assert result["error"] is None+ assert result["status_code"] == 302+ assert result["headers"]["Location"] == "/plain"+ assert result["content"] == "moved-body-here"+ assert result["content_bytes"] == 15+++ "method,path,kwargs,expected",+ [+ # 3xx: the redirect hook has consumed and closed the stream.+ ("get", "/moved", {"allow_redirects": False, "stream": True}, b"moved-body-here"),+ ("get", "/moved", {"allow_redirects": False, "stream": False}, b"moved-body-here"),+ # stream=False: requests has read the body itself.+ ("get", "/plain", {"stream": False}, b"plain"),+ ("get", "/plain", {"stream": True}, b"plain"),+ # No body at all: 304 and HEAD, streamed or not.+ ("get", "/not-modified", {"stream": True}, b""),+ ("get", "/not-modified", {"stream": False}, b""),+ ("head", "/plain", {"stream": True}, b""),+ ("head", "/plain", {"stream": False}, b""),+ ],+)+def test_deadline_reader_returns_what_read_bounded_returns(server, method, path, kwargs, expected):+ def fetch(reader):+ with url_safety.safe_requests_session(f"{server}{path}") as session:+ response = getattr(session, method)(f"{server}{path}", timeout=5, **kwargs)+ try:+ return reader(response)+ finally:+ response.close()++ far = time.monotonic() + 30+ assert fetch(lambda r: url_safety.read_bounded(r, 1000)) == (expected, False)+ assert fetch(lambda r: url_safety.read_bounded_until(r, 1000, far)) == (expected, False, False)+++def test_already_read_body_still_honours_the_cap_and_the_deadline(server):+ with url_safety.safe_requests_session(f"{server}/moved") as session:+ response = session.get(f"{server}/moved", timeout=5, allow_redirects=False, stream=True)+ assert url_safety.read_bounded_until(response, 5, time.monotonic() + 30) == (b"", True, False)+ assert url_safety.read_bounded_until(response, 1000, time.monotonic() - 1) == (b"", False, True)+++# ---------------------------------------------------------------------------+# content_bytes: the size of the body as bytes, not of the decoded text+# ---------------------------------------------------------------------------+++def test_content_bytes_counts_the_body_not_its_utf8_re_encoding(server):+ """A windows-1251 page is one byte per Cyrillic letter. Measuring the+ decoded text as UTF-8 nearly doubles it."""+ result = fetch_page.fetch_page(f"{server}/cyrillic", timeout=5)+ assert result["error"] is None+ assert result["content"] == CYRILLIC_TEXT+ assert result["content_bytes"] == len(CYRILLIC_BYTES)+ assert len(result["content"].encode("utf-8")) > 1.5 * result["content_bytes"]+++def test_content_bytes_is_counted_after_decompression(monkeypatch):+ body = CYRILLIC_BYTES * 20+ page = _streamed_response(body, gzipped=True, headers={"Content-Type": "text/html; charset=windows-1251"})+ result = _patched_fetch(monkeypatch, page)+ assert result["content"] == CYRILLIC_TEXT * 20+ assert result["content_bytes"] == len(body)+++def test_content_bytes_counts_the_part_read_when_the_body_is_cut(monkeypatch):+ capped = _patched_fetch(monkeypatch, _streamed_response(b"A" * 300_000), max_bytes=100_000)+ assert capped["too_large"] is True+ assert capped["content_bytes"] == len(capped["content"]) <= 100_000++ unread = _patched_fetch(monkeypatch, _streamed_response(b"<html></html>"), max_time=1e-9)+ assert "wall-clock deadline" in unread["error"]+ assert unread["content_bytes"] == 0+++def test_content_bytes_is_none_when_no_body_was_read(monkeypatch):+ monkeypatch.delenv("CLAUDE_SEO_LOCAL_TARGETS", raising=False)+ assert fetch_page.fetch_page("http://127.0.0.1:1/")["content_bytes"] is None+ stalled = _streamed_response(b"", fp=_TimingOutBody())+ assert _patched_fetch(monkeypatch, stalled)["content_bytes"] is None++# ---------------------------------------------------------------------------# read_bounded_until, with a clock the test controls# ---------------------------------------------------------------------------@@ -364,6 +476,7 @@ _RAW = {"ttfb_ms": 120,"response_time_ms": 340,"fetch_duration_ms": 910,+ "content_bytes": 10,}@@ -410,6 +523,12 @@ def test_cli_json_reports_the_timings_of_a_raw_fetch(monkeypatch, capsys):}+def test_cli_json_reports_content_bytes_of_a_raw_fetch(monkeypatch, capsys):+ code, _seen, captured = _run_cli(monkeypatch, capsys, ["--json"], _RAW)+ assert code == 0+ assert json.loads(captured.out)["content_bytes"] == 10++def test_cli_json_keeps_one_key_set_for_a_rendered_fetch(monkeypatch, capsys):"""A rendered result has render_ms instead; the raw timings are null."""rendered = {@@ -425,6 +544,7 @@ def test_cli_json_keeps_one_key_set_for_a_rendered_fetch(monkeypatch, capsys):payload = json.loads(capsys.readouterr().out)assert exc.value.code == 0assert {key: payload[key] for key in TIMING_KEYS} == dict.fromkeys(TIMING_KEYS)+ assert payload["content_bytes"] is Noneassert payload["render_ms"] == 12.5