diff --git a/docreader/parser/web_parser.py b/docreader/parser/web_parser.py index 40a25279..8ef94340 100644 --- a/docreader/parser/web_parser.py +++ b/docreader/parser/web_parser.py @@ -18,6 +18,15 @@ from docreader.utils.ssrf import is_ssrf_safe_url logger = logging.getLogger(__name__) + +class WebParseError(RuntimeError): + """Raised when a URL cannot be scraped or has no extractable content. + + This must propagate as a parse failure. Returning the error string as + document body would index it as knowledge. + """ + + _GOTO_TIMEOUT_MS = 30_000 _NETWORK_IDLE_TIMEOUT_MS = 10_000 _SPA_WAIT_TIMEOUT_MS = 15_000 @@ -56,6 +65,7 @@ class _ScrapeResult: html: str visible_text: str page_title: str + error: str = "" def extract_markdown_from_html(html: str) -> Optional[str]: @@ -167,14 +177,17 @@ class StdWebParser(BaseParser): url: The URL of the web page to scrape Returns: - HTML, visible text, and document title; empty fields on hard failure + HTML, visible text, and document title. On hard failure the + content fields are empty and ``error`` explains why. """ logger.info(f"Starting web page scraping for URL: {url}") - empty = _ScrapeResult(html="", visible_text="", page_title="") safe, reason = is_ssrf_safe_url(url) if not safe: logger.error("URL blocked by SSRF guard before navigation: %s", reason) - return empty + return _ScrapeResult( + html="", visible_text="", page_title="", + error=f"URL blocked by SSRF guard: {reason}", + ) try: async with async_playwright() as p: kwargs = {} @@ -197,7 +210,10 @@ class StdWebParser(BaseParser): except Exception as e: logger.error(f"Error navigating to URL: {str(e)}") await browser.close() - return empty + return _ScrapeResult( + html="", visible_text="", page_title="", + error=f"navigation failed: {e}", + ) await wait_for_rendered_content(page) @@ -223,7 +239,10 @@ class StdWebParser(BaseParser): except Exception as e: logger.error(f"Failed to scrape web page: {str(e)}") - return empty + return _ScrapeResult( + html="", visible_text="", page_title="", + error=f"scrape failed: {e}", + ) def parse_into_text(self, content: bytes) -> Document: """Parse web page content into a Document object. @@ -233,14 +252,22 @@ class StdWebParser(BaseParser): Returns: Document object containing the parsed markdown content + + Raises: + WebParseError: If scraping fails or the page has no extractable + content. Callers must surface this as a parse failure rather + than indexing the error string as document body. """ url = endecode.decode_bytes(content) logger.info(f"Scraping web page: {url}") scrape_result = asyncio.run(self.scrape(url)) - if not scrape_result.html and not scrape_result.visible_text: - logger.error("Failed to scrape web page (no HTML or visible text)") - return Document(content=f"Error parsing web page: {url}") + if scrape_result.error or ( + not scrape_result.html and not scrape_result.visible_text + ): + detail = scrape_result.error or "no HTML or visible text" + logger.error("Failed to scrape web page %s: %s", url, detail) + raise WebParseError(f"Failed to scrape web page: {url} ({detail})") md_text = extract_markdown_from_html(scrape_result.html) if not md_text: @@ -255,8 +282,8 @@ class StdWebParser(BaseParser): ) if not md_text: - logger.error("Failed to parse web page") - return Document(content=f"Error parsing web page: {url}") + logger.error("Failed to parse web page: %s", url) + raise WebParseError(f"Failed to parse web page: {url}") metadata = {} title_match = re.search(r"^title:\s*(.+)", md_text, re.MULTILINE) diff --git a/docreader/tests/test_web_parser.py b/docreader/tests/test_web_parser.py index 0d24c87f..677a259b 100644 --- a/docreader/tests/test_web_parser.py +++ b/docreader/tests/test_web_parser.py @@ -1,8 +1,12 @@ import os import unittest -from unittest.mock import patch +from unittest.mock import AsyncMock, patch from docreader.parser.web_parser import ( + StdWebParser, + WebParseError, + WebParser, + _ScrapeResult, build_visible_text_fallback, extract_markdown_from_html, install_ssrf_route_guard, @@ -63,5 +67,87 @@ class TestWebParserHelpers(unittest.TestCase): self.assertTrue(reason) +class TestStdWebParserFailures(unittest.TestCase): + """Scrape/parse failures must raise, not become indexable document body.""" + + def _parser(self) -> StdWebParser: + return StdWebParser(title="page") + + def test_empty_scrape_raises_instead_of_error_body(self): + empty = _ScrapeResult( + html="", + visible_text="", + page_title="", + error="navigation failed: Timeout", + ) + parser = self._parser() + with patch.object(parser, "scrape", new=AsyncMock(return_value=empty)): + with self.assertRaises(WebParseError) as ctx: + parser.parse_into_text(b"https://example.com/blocked") + message = str(ctx.exception) + self.assertIn("https://example.com/blocked", message) + self.assertIn("navigation failed", message) + self.assertNotIn("Error parsing web page:", message) + + def test_empty_scrape_without_error_field_still_raises(self): + empty = _ScrapeResult(html="", visible_text="", page_title="") + parser = self._parser() + with patch.object(parser, "scrape", new=AsyncMock(return_value=empty)): + with self.assertRaises(WebParseError) as ctx: + parser.parse_into_text(b"https://example.com/blank") + self.assertIn("no HTML or visible text", str(ctx.exception)) + + def test_unextractable_page_raises_instead_of_error_body(self): + scrape = _ScrapeResult( + html="
", + visible_text="short", + page_title="", + ) + parser = self._parser() + with patch.object(parser, "scrape", new=AsyncMock(return_value=scrape)): + with patch( + "docreader.parser.web_parser.extract_markdown_from_html", + return_value=None, + ): + with patch( + "docreader.parser.web_parser.build_visible_text_fallback", + return_value=None, + ): + with self.assertRaises(WebParseError) as ctx: + parser.parse_into_text(b"https://example.com/empty") + self.assertIn("Failed to parse web page", str(ctx.exception)) + self.assertIn("https://example.com/empty", str(ctx.exception)) + + def test_successful_scrape_returns_markdown_document(self): + html = """ + Demo +

Hello

World paragraph with enough text for extraction.

+ + """ + scrape = _ScrapeResult( + html=html, + visible_text="Hello World paragraph with enough text for extraction.", + page_title="Demo", + ) + parser = self._parser() + with patch.object(parser, "scrape", new=AsyncMock(return_value=scrape)): + doc = parser.parse_into_text(b"https://example.com/ok") + self.assertTrue(doc.is_valid()) + self.assertNotIn("Error parsing web page:", doc.content) + self.assertIn("Hello", doc.content) + + def test_pipeline_web_parser_does_not_index_scrape_error(self): + empty = _ScrapeResult( + html="", + visible_text="", + page_title="", + error="URL blocked by SSRF guard: loopback", + ) + pipeline = WebParser(title="page") + with patch.object(StdWebParser, "scrape", new=AsyncMock(return_value=empty)): + with self.assertRaises(WebParseError): + pipeline.parse_into_text(b"https://example.com/ssrf") + + if __name__ == "__main__": unittest.main()