Skip to content

Official Crawl4AI Cloud: a hosted web scraping, extraction, and search API for AI agents. Free API key, 1,000 credits a month, no card. Fully open source: this repo is the Apache-2.0 crawler that powers it, and you can self-host it.

fix(docker): route PDFContentScrapingStrategy requests to PDFCrawlerStrategy (#2127)

Soham Kukreti4ccd143026e0
diff --git a/deploy/docker/api.py b/deploy/docker/api.py
index f11494b1..72928ea1 100644
--- a/deploy/docker/api.py
+++ b/deploy/docker/api.py
@@ -85,6 +85,7 @@ from utils import (
get_llm_base_url,
get_redis_task_ttl,
validate_url_destination,
+ datetime_handler,
)
from webhook import WebhookDeliveryService
@@ -607,6 +608,7 @@ async def stream_results(crawler: AsyncWebCrawler, results_gen: AsyncGenerator)
import json
from utils import datetime_handler
from crawler_pool import release_crawler
+ from crawl4ai.processors.pdf import PDFCrawlerStrategy
try:
async for result in results_gen:
@@ -634,7 +636,10 @@ async def stream_results(crawler: AsyncWebCrawler, results_gen: AsyncGenerator)
logger.warning("Client disconnected during streaming")
finally:
if crawler:
- await release_crawler(crawler)
+ if isinstance(crawler.crawler_strategy, PDFCrawlerStrategy):
+ await crawler.close() # not pooled; release_crawler would be a no-op
+ else:
+ await release_crawler(crawler)
def _normalize_and_validate_seeds(urls: List[str]) -> List[str]:
@@ -659,6 +664,7 @@ async def handle_crawl_request(
# Track request start
request_id = f"req_{uuid4().hex[:8]}"
crawler = None
+ is_pdf_crawl = False
try:
from monitor import get_monitor
await get_monitor().track_request_start(
@@ -689,7 +695,17 @@ async def handle_crawl_request(
)
from crawler_pool import get_crawler, release_crawler
- crawler = await get_crawler(browser_config)
+ from crawl4ai.processors.pdf import PDFContentScrapingStrategy, PDFCrawlerStrategy
+ is_pdf_crawl = isinstance(crawler_config.scraping_strategy, PDFContentScrapingStrategy)
+ if is_pdf_crawl:
+ if hooks_config:
+ # PDFCrawlerStrategy has no browser page, so hooks can't attach to it
+ raise HTTPException(status_code=400, detail="Hooks are not supported with PDFContentScrapingStrategy")
+ # Use PDFCrawlerStrategy when scraping PDFs, as headless Chromium can't render PDFs inline
+ crawler = AsyncWebCrawler(crawler_strategy=PDFCrawlerStrategy())
+ await crawler.start()
+ else:
+ crawler = await get_crawler(browser_config)
# Attach declarative hooks if provided
hooks_status = {}
@@ -771,6 +787,10 @@ async def handle_crawl_request(
if result_dict.get('pdf') is not None and isinstance(result_dict.get('pdf'), bytes):
result_dict['pdf'] = b64encode(result_dict['pdf']).decode('utf-8')
+ if is_pdf_crawl:
+ # PDF metadata contains datetimes that JSONResponse can't serialize
+ result_dict = json.loads(json.dumps(result_dict, default=datetime_handler))
+
processed_results.append(result_dict)
except Exception as e:
logger.error(f"Error processing result: {e}")
@@ -851,7 +871,10 @@ async def handle_crawl_request(
)
finally:
if crawler:
- await release_crawler(crawler)
+ if is_pdf_crawl:
+ await crawler.close() # not pooled; release_crawler would be a no-op
+ else:
+ await release_crawler(crawler)
async def handle_stream_crawl_request(
urls: List[str],
@@ -895,7 +918,16 @@ async def handle_stream_crawl_request(
)
from crawler_pool import get_crawler, release_crawler
- crawler = await get_crawler(browser_config)
+ from crawl4ai.processors.pdf import PDFContentScrapingStrategy, PDFCrawlerStrategy
+ if isinstance(crawler_config.scraping_strategy, PDFContentScrapingStrategy):
+ if hooks_config:
+ # PDFCrawlerStrategy has no browser page, so hooks can't attach to it
+ raise HTTPException(status_code=400, detail="Hooks are not supported with PDFContentScrapingStrategy")
+ # Use PDFCrawlerStrategy when scraping PDFs, as headless Chromium can't render PDFs inline
+ crawler = AsyncWebCrawler(crawler_strategy=PDFCrawlerStrategy())
+ await crawler.start()
+ else:
+ crawler = await get_crawler(browser_config)
# Attach declarative hooks if provided
if hooks_config:
diff --git a/tests/test_docker_pdf_crawler_pairing.py b/tests/test_docker_pdf_crawler_pairing.py
new file mode 100644
index 00000000..cdce7f53
--- /dev/null
+++ b/tests/test_docker_pdf_crawler_pairing.py
@@ -0,0 +1,123 @@
+"""Tests for the Docker API's PDF crawler pairing.
+
+When a client requests PDFContentScrapingStrategy, the crawl handlers must
+pair it with PDFCrawlerStrategy (which downloads the PDF itself) instead of a
+pooled Playwright crawler — headless Chromium cannot render PDFs inline, so
+browser navigation fails with "Page.goto: Download is starting" before the
+scraping strategy ever runs.
+"""
+
+import importlib
+from pathlib import Path
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from crawl4ai.processors.pdf import PDFCrawlerStrategy
+
+ROOT = Path(__file__).resolve().parent.parent
+
+CONFIG = {
+ "crawler": {
+ "memory_threshold_percent": 90,
+ "rate_limiter": {"enabled": False, "base_delay": [0.1, 0.3]},
+ "base_config": {},
+ }
+}
+
+
+def _crawler_config_payload(with_pdf_strategy):
+ params = {"cache_mode": "bypass"}
+ if with_pdf_strategy:
+ params["scraping_strategy"] = {
+ "type": "PDFContentScrapingStrategy",
+ "params": {},
+ }
+ return {"type": "CrawlerRunConfig", "params": params}
+
+
+def api(monkeypatch):
+ monkeypatch.syspath_prepend(str(ROOT / "deploy" / "docker"))
+ return importlib.import_module("api")
+
+
+def pool_mock(api, monkeypatch):
+ crawler_pool = importlib.import_module("crawler_pool")
+ egress_broker = importlib.import_module("egress_broker")
+ governor = importlib.import_module("governor")
+
+ pooled = MagicMock()
+ pooled.arun = AsyncMock(return_value=[])
+ pooled.active_requests = 1 # release_crawler decrements this int
+ mock = AsyncMock(return_value=pooled)
+ monkeypatch.setattr(crawler_pool, "get_crawler", mock)
+ monkeypatch.setattr(api, "_normalize_and_validate_seeds", lambda urls: urls)
+ monkeypatch.setattr(egress_broker, "enforce_egress", lambda _: None)
+ monkeypatch.setattr(governor, "clamp_deep_crawl", lambda _: None)
+ return mock
+
+
+async def test_pdf_scraping_strategy_gets_pdf_crawler(api, pool_mock, monkeypatch):
+ used = {}
+ real_crawler_cls = api.AsyncWebCrawler
+
+ def spy_crawler(*args, **kwargs):
+ crawler = real_crawler_cls(*args, **kwargs)
+ used["crawler"] = crawler
+ used["crawler_strategy"] = crawler.crawler_strategy
+ crawler.arun = AsyncMock(return_value=[])
+ crawler.close = AsyncMock(wraps=crawler.close)
+ return crawler
+
+ monkeypatch.setattr(api, "AsyncWebCrawler", spy_crawler)
+
+ response = await api.handle_crawl_request(
+ urls=["https://example.com/document.pdf"],
+ browser_config={"type": "BrowserConfig", "params": {}},
+ crawler_config=_crawler_config_payload(with_pdf_strategy=True),
+ config=CONFIG,
+ )
+
+ assert response["success"] is True
+ assert isinstance(used["crawler_strategy"], PDFCrawlerStrategy)
+ pool_mock.assert_not_awaited()
+ # The dedicated PDF crawler is not pooled, so the handler must close it.
+ used["crawler"].close.assert_awaited_once()
+
+
+async def test_pdf_strategy_with_hooks_rejected(api, pool_mock):
+ from fastapi import HTTPException
+
+ # A VALID hook action: without the guard this reaches set_hook and blows up
+ # with AttributeError (PDFCrawlerStrategy has no set_hook) -> 500. An invalid
+ # action would 400 via HookValidationError even without the guard, proving nothing.
+ hooks = {"hooks": [{"action": "block_resources", "params": {"resource_types": ["image"]}}]}
+ with pytest.raises(HTTPException) as exc_info:
+ await api.handle_crawl_request(
+ urls=["https://example.com/document.pdf"],
+ browser_config={"type": "BrowserConfig", "params": {}},
+ crawler_config=_crawler_config_payload(with_pdf_strategy=True),
+ config=CONFIG,
+ hooks_config=hooks,
+ )
+
+ assert exc_info.value.status_code == 400
+ assert "PDFContentScrapingStrategy" in exc_info.value.detail
+ pool_mock.assert_not_awaited()
+
+
+async def test_default_strategy_still_uses_pool(api, pool_mock):
+ response = await api.handle_crawl_request(
+ urls=["https://example.com/"],
+ browser_config={"type": "BrowserConfig", "params": {}},
+ crawler_config=_crawler_config_payload(with_pdf_strategy=False),
+ config=CONFIG,
+ )
+
+ assert response["success"] is True
+ pool_mock.assert_awaited_once()