Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Cut crawler CPU per page by 12x and crawl batches concurrently

Daoud Clarkec65f1bd38a7a
diff --git a/mwmbl/crawl.py b/mwmbl/crawl.py
index 8f7b71f..1290442 100644
--- a/mwmbl/crawl.py
+++ b/mwmbl/crawl.py
@@ -1,7 +1,6 @@
import argparse
import logging
import os
-import random
import time
from datetime import datetime, timedelta, timezone
from multiprocessing import Process
@@ -35,13 +34,14 @@ from mwmbl.crawler.device import get_device_name
from mwmbl.crawler.env_vars import (
CRAWL_DELAY_SECONDS,
CRAWL_SUBMIT_MODE,
+ CRAWL_THREADS,
CRAWLER_WORKERS,
MWMBL_API_KEY,
MWMBL_CONTACT_INFO,
SUBMIT_MODE_DRY_RUN,
SUBMIT_MODE_OFF,
)
-from mwmbl.crawler.retrieve import CRAWLER_VERSION, USER_AGENT, crawl_url
+from mwmbl.crawler.retrieve import CRAWLER_VERSION, USER_AGENT, crawl_batch
from mwmbl.indexer.index_batches import index_batches, index_pages
from mwmbl.indexer.update_urls import record_urls_in_database
from mwmbl.rankeval.evaluation.remote_index import RemoteIndex
@@ -200,32 +200,21 @@ class Crawler:
def process_batch(self):
"""
- Process a single batch of URLs by crawling them sequentially with rate limiting.
+ Process a single batch of URLs by crawling them concurrently with rate limiting.
This function handles the core crawling workflow:
1. Gets a batch of URLs from the Redis URL queue
- 2. Crawls each URL sequentially with configurable delay between requests
+ 2. Crawls the URLs on CRAWL_THREADS threads, each waiting CRAWL_DELAY_SECONDS between URLs
3. Records crawl results in the database for URL tracking
4. Pushes the completed batch to Redis queue for indexing
- The sequential crawling with delays respects rate limits and reduces load on target servers.
Each batch is processed as a HashedBatch object containing metadata and crawl results.
"""
user_id = "test"
urls = self.url_queue.get_batch(user_id)
- logger.info(f"Processing batch of {len(urls)} URLs")
-
- # Process URLs sequentially with rate limiting
- results = []
- for i, url in enumerate(urls):
- if i > 0: # Don't delay before the first URL
- # Add delay with 10% random fuzz
- delay = CRAWL_DELAY_SECONDS * (0.9 + 0.2 * random.random())
- time.sleep(delay)
-
- result = crawl_url(url, self.redis)
- results.append(result)
- logger.debug("Result", result)
+ logger.info(f"Processing batch of {len(urls)} URLs on {CRAWL_THREADS} threads")
+
+ results = crawl_batch(urls, CRAWL_THREADS, CRAWL_DELAY_SECONDS, self.redis)
js_timestamp = int(time.time() * 1000)
batch = HashedBatch.parse_obj(
diff --git a/mwmbl/crawler/README.md b/mwmbl/crawler/README.md
index 679197f..a7b4f52 100644
--- a/mwmbl/crawler/README.md
+++ b/mwmbl/crawler/README.md
@@ -14,10 +14,10 @@ The crawler can be configured using the following environment variables:
- `CRAWLER_WORKERS` (default: 2) - Number of separate operating system processes to spawn for crawling work (uses Python's multiprocessing.Process)
- `CRAWL_THREADS` (default: 20) - Number of threads per worker process for concurrent URL crawling (total threads = CRAWLER_WORKERS × CRAWL_THREADS)
-**Process Architecture**: The crawler spawns `CRAWLER_WORKERS` processes for crawling work, each using `CRAWL_THREADS` threads for concurrent URL fetching. Additionally, one separate process handles indexing work. For example, with default settings you get 10 crawler processes × 20 threads = 200 total crawling threads, plus 1 indexing process.
+**Process Architecture**: The crawler spawns `CRAWLER_WORKERS` processes for crawling work, each using `CRAWL_THREADS` threads for concurrent URL fetching. Additionally, one separate process handles indexing work. For example, with default settings you get 2 crawler processes × 20 threads = 40 total crawling threads, plus 1 indexing process. The queue gives each batch at most one URL per domain, so the threads of one batch never fetch pages from the same site at once.
### Rate Limiting Configuration
-- `CRAWL_DELAY_SECONDS` (default: 0.0) - Delay in seconds between crawling each URL within a batch. Includes 10% random fuzz (±10%) to avoid synchronized requests across workers. Set to 0 to disable delays.
+- `CRAWL_DELAY_SECONDS` (default: 0.0) - Delay in seconds each crawl thread waits between the URLs it crawls. Includes 10% random fuzz (±10%) to avoid synchronized requests across workers. Set to 0 to disable delays.
### Redis Configuration
- `REDIS_URL` (default: 'redis://127.0.0.1:6379') - Redis connection URL for URL queues and stats
diff --git a/mwmbl/crawler/retrieve.py b/mwmbl/crawler/retrieve.py
index 6041fdd..23dbfd9 100644
--- a/mwmbl/crawler/retrieve.py
+++ b/mwmbl/crawler/retrieve.py
@@ -1,5 +1,8 @@
import json
+import random
import re
+import ssl
+import threading
import time
from logging import getLogger
from multiprocessing.pool import ThreadPool
@@ -11,6 +14,8 @@ from urllib.robotparser import RobotFileParser
import requests
from redis import Redis
from requests import ReadTimeout
+from requests.adapters import HTTPAdapter
+from requests.utils import DEFAULT_CA_BUNDLE_PATH
from urllib3.exceptions import MaxRetryError, NewConnectionError
from mwmbl.crawler.env_vars import MWMBL_CONTACT_INFO
@@ -57,6 +62,45 @@ ROBOTS_CACHE_ERROR_TTL_SECONDS = 60 * 60
logger = getLogger(__name__)
+# One verifying context for every fetch. Left to itself, requests builds a fresh context for
+# each new connection and parses the whole CA bundle into it, which on OpenSSL 3 costs about
+# 100ms of CPU - most of what the crawler spent per page. requests no longer shares a
+# preloaded context, so the crawler has to.
+SSL_CONTEXT = ssl.create_default_context(cafile=DEFAULT_CA_BUNDLE_PATH)
+
+_thread_local = threading.local()
+
+
+class SharedContextAdapter(HTTPAdapter):
+ def init_poolmanager(self, connections, maxsize, block=False, **pool_kwargs):
+ super().init_poolmanager(connections, maxsize, block, ssl_context=SSL_CONTEXT, **pool_kwargs)
+
+ def cert_verify(self, conn, url, verify, cert):
+ """Keep verification on, but stop urllib3 reloading the bundle into SSL_CONTEXT.
+
+ The base class points every connection at the bundle file, and urllib3 then calls
+ load_verify_locations on the shared context per connection - the cost the shared
+ context exists to avoid. SSL_CONTEXT was built from that same bundle.
+ """
+ super().cert_verify(conn, url, verify, cert)
+ conn.ca_certs = None
+ conn.ca_cert_dir = None
+
+
+def get_session() -> requests.Session:
+ """A session per thread: requests does not promise a Session is safe to share.
+
+ Keeping it also keeps connections alive between fetches, so a page's robots.txt and the
+ page itself share one TLS handshake.
+ """
+ if not hasattr(_thread_local, "session"):
+ session = requests.Session()
+ # Otherwise every request scans os.environ for proxy and CA bundle settings.
+ session.trust_env = False
+ session.mount("https://", SharedContextAdapter())
+ _thread_local.session = session
+ return _thread_local.session
+
def fetch(url):
"""
@@ -75,7 +119,7 @@ def fetch(url):
headers = {"User-Agent": USER_AGENT}
for _ in range(MAX_REDIRECTS + 1):
validate_url(url)
- r = requests.get(url, stream=True, timeout=TIMEOUT_SECONDS, headers=headers, allow_redirects=False)
+ r = get_session().get(url, stream=True, timeout=TIMEOUT_SECONDS, headers=headers, allow_redirects=False)
if r.is_redirect and r.next is not None:
r.close()
@@ -97,6 +141,8 @@ def fetch(url):
logger.debug(f"Maximum size reached for URL {url}")
break
+ # A response left open holds its connection out of the session's pool.
+ r.close()
return r.status_code, content, url
raise ValueError(f"Too many redirects for URL {url}")
@@ -444,7 +490,21 @@ def crawl_url(url, redis: Redis):
}
-def crawl_batch(batch, num_threads, redis: Redis):
+def crawl_batch(urls: list[str], num_threads: int, delay_seconds: float, redis: Redis) -> list[dict]:
+ """Crawl a batch concurrently, returning results in the order of the URLs.
+
+ Fetching is almost all waiting on the network, so one URL at a time leaves the machine
+ idle. The queue hands out at most one URL per domain in a batch, so crawling a batch in
+ parallel does not put more load on any one site.
+
+ Each thread waits delay_seconds, with 10% random fuzz, between the URLs it crawls.
+ """
+
+ def crawl_after_delay(url: str) -> dict:
+ if delay_seconds and getattr(_thread_local, "has_crawled", False):
+ time.sleep(delay_seconds * (0.9 + 0.2 * random.random()))
+ _thread_local.has_crawled = True
+ return crawl_url(url, redis)
+
with ThreadPool(num_threads) as pool:
- result = pool.map(lambda url: crawl_url(url, redis), batch)
- return result
+ return pool.map(crawl_after_delay, urls)
diff --git a/test/test_crawl_functional.py b/test/test_crawl_functional.py
index 7a0271a..87390c4 100644
--- a/test/test_crawl_functional.py
+++ b/test/test_crawl_functional.py
@@ -11,8 +11,9 @@ import fakeredis
import pytest
from django.test import override_settings
-from mwmbl.crawl import REMOTE_INDEX_CACHE_EXPIRY, Crawler, crawl_url
+from mwmbl.crawl import REMOTE_INDEX_CACHE_EXPIRY, Crawler
from mwmbl.crawler.batch import HashedBatch, Item, ItemContent
+from mwmbl.crawler.retrieve import crawl_url
from mwmbl.crawler.urls import FoundURL, URLStatus
from mwmbl.indexer.blacklist_providers import StaticBlacklistProvider
from mwmbl.redis_url_queue import RedisURLQueue
@@ -153,7 +154,7 @@ class TestCrawlFunctional:
mock_url_queue.get_batch.return_value = ["https://example.com"]
crawler._url_queue = mock_url_queue
- with patch("mwmbl.crawl.crawl_url", return_value=mock_crawl_response):
+ with patch("mwmbl.crawler.retrieve.crawl_url", return_value=mock_crawl_response):
with patch("mwmbl.crawl.record_urls_in_database"):
# Should complete without errors
crawler.process_batch()
@@ -346,7 +347,7 @@ class TestCrawlFunctional:
crawler._redis = fake_redis
crawler._url_queue = url_queue
- with patch("mwmbl.crawl.crawl_url", return_value=mock_crawl_response):
+ with patch("mwmbl.crawler.retrieve.crawl_url", return_value=mock_crawl_response):
with patch("mwmbl.crawl.record_urls_in_database"):
# Mock Counter object for index_batches return value
mock_counter = Counter({"example": 1})
diff --git a/test/test_domain_moderation.py b/test/test_domain_moderation.py
index 951a979..4ed9b7c 100644
--- a/test/test_domain_moderation.py
+++ b/test/test_domain_moderation.py
@@ -11,6 +11,7 @@ import json
import sys
from datetime import timedelta
from pathlib import Path
+from types import SimpleNamespace
from unittest import mock
import joblib
@@ -1205,7 +1206,7 @@ A_PAGE = (
def crawl_with(responses: dict, domain: str) -> dict:
"""Crawl ``domain`` against canned HTTP responses, through the real crawler.
- Driven from requests.get rather than by stubbing crawl_url, because everything this
+ Driven from the session's get rather than by stubbing crawl_url, because everything this
covers lives in the plumbing between the fetch and the evidence.
"""
@@ -1217,7 +1218,7 @@ def crawl_with(responses: dict, domain: str) -> dict:
blacklist = mock.Mock(is_domain_blacklisted=mock.Mock(return_value=False))
with (
- mock.patch("mwmbl.crawler.retrieve.requests.get", get),
+ mock.patch("mwmbl.crawler.retrieve.get_session", return_value=SimpleNamespace(get=get)),
mock.patch("mwmbl.crawler.retrieve.validate_url"),
mock.patch("mwmbl.crawler.retrieve.robots_allowed", return_value=True),
mock.patch("mwmbl.moderation.evidence.get_snapshot_blacklist", return_value=blacklist),
diff --git a/test/test_retrieve_concurrency.py b/test/test_retrieve_concurrency.py
new file mode 100644
index 0000000..90888d0
--- /dev/null
+++ b/test/test_retrieve_concurrency.py
@@ -0,0 +1,91 @@
+"""
+The crawler's fetch path: one shared SSL context, a session per thread, and batches crawled
+concurrently with a per-thread delay.
+"""
+
+import ssl
+import threading
+
+import fakeredis
+import requests
+from urllib3 import HTTPSConnectionPool
+
+from mwmbl.crawler import retrieve
+from mwmbl.crawler.retrieve import SharedContextAdapter, crawl_batch, get_session
+
+
+def test_adapter_keeps_verification_but_not_the_bundle_path():
+ adapter = SharedContextAdapter()
+ conn = HTTPSConnectionPool("example.com")
+
+ adapter.cert_verify(conn, "https://example.com/", verify=True, cert=None)
+
+ assert conn.cert_reqs == "CERT_REQUIRED"
+ assert conn.ca_certs is None
+ assert conn.ca_cert_dir is None
+
+
+def test_shared_context_verifies_certificates():
+ assert retrieve.SSL_CONTEXT.verify_mode == ssl.CERT_REQUIRED
+ assert retrieve.SSL_CONTEXT.check_hostname
+
+
+def test_sessions_use_the_shared_context():
+ pool = (
+ get_session()
+ .get_adapter("https://example.com/")
+ .get_connection_with_tls_context(requests.Request("GET", "https://example.com/").prepare(), verify=True)
+ )
+
+ assert pool.conn_kw["ssl_context"] is retrieve.SSL_CONTEXT
+
+
+def test_session_is_per_thread():
+ sessions_by_thread = []
+ thread = threading.Thread(target=lambda: sessions_by_thread.append(get_session()))
+ thread.start()
+ thread.join()
+
+ assert get_session() is get_session()
+ assert sessions_by_thread[0] is not get_session()
+
+
+def test_crawl_batch_crawls_concurrently_and_keeps_order(monkeypatch):
+ # Every crawl waits for all three to be in flight at once, so this only finishes if
+ # they really run in parallel.
+ all_in_flight = threading.Barrier(3, timeout=5)
+
+ def fake_crawl_url(url, redis):
+ all_in_flight.wait()
+ return {"url": url}
+
+ monkeypatch.setattr(retrieve, "crawl_url", fake_crawl_url)
+ urls = ["https://a.test/", "https://b.test/", "https://c.test/"]
+
+ results = crawl_batch(urls, num_threads=3, delay_seconds=0.0, redis=fakeredis.FakeStrictRedis())
+
+ assert [result["url"] for result in results] == urls
+
+
+def test_crawl_batch_delays_between_urls_on_each_thread(monkeypatch):
+ sleeps = []
+ monkeypatch.setattr(retrieve, "crawl_url", lambda url, redis: {"url": url})
+ monkeypatch.setattr(retrieve.time, "sleep", sleeps.append)
+ urls = ["https://a.test/", "https://b.test/", "https://c.test/"]
+
+ crawl_batch(urls, num_threads=1, delay_seconds=2.0, redis=fakeredis.FakeStrictRedis())
+
+ assert len(sleeps) == 2
+ assert all(1.8 <= seconds <= 2.2 for seconds in sleeps)
+
+
+def test_crawl_batch_without_delay_never_sleeps(monkeypatch):
+ sleeps = []
+ monkeypatch.setattr(retrieve, "crawl_url", lambda url, redis: {"url": url})
+ monkeypatch.setattr(retrieve.time, "sleep", sleeps.append)
+
+ crawl_batch(
+ ["https://a.test/", "https://b.test/"], num_threads=1, delay_seconds=0.0, redis=fakeredis.FakeStrictRedis()
+ )
+
+ assert sleeps == []
diff --git a/test/test_ssrf.py b/test/test_ssrf.py
index 46d2edc..4e4c759 100644
--- a/test/test_ssrf.py
+++ b/test/test_ssrf.py
@@ -1,6 +1,7 @@
"""Tests for the SSRF guard and its wiring into fetch() and add_url()."""
import socket
+from types import SimpleNamespace
import pytest
from allauth.account.models import EmailAddress
@@ -110,10 +111,12 @@ class _FakeResponse:
def test_fetch_blocks_internal_url_without_request(monkeypatch):
calls = []
- monkeypatch.setattr(retrieve.requests, "get", lambda *a, **k: calls.append(a) or _FakeResponse(200))
+ monkeypatch.setattr(
+ retrieve, "get_session", lambda: SimpleNamespace(get=lambda *a, **k: calls.append(a) or _FakeResponse(200))
+ )
with pytest.raises(UnsafeURLError):
retrieve.fetch("http://127.0.0.1/secret")
- assert calls == [], "requests.get must not be called for an internal URL"
+ assert calls == [], "no request may be made for an internal URL"
def test_fetch_blocks_redirect_to_internal(monkeypatch):
@@ -124,14 +127,16 @@ def test_fetch_blocks_redirect_to_internal(monkeypatch):
# First (public) hop redirects to an internal address.
return _FakeResponse(301, headers={"Location": "http://127.0.0.1/"}, is_redirect=True)
- monkeypatch.setattr(retrieve.requests, "get", fake_get)
+ monkeypatch.setattr(retrieve, "get_session", lambda: SimpleNamespace(get=fake_get))
with pytest.raises(UnsafeURLError):
retrieve.fetch("http://93.184.216.34/start")
assert len(calls) == 1, "must stop after the first hop, before fetching the internal redirect target"
def test_fetch_returns_content_for_public_url(monkeypatch):
- monkeypatch.setattr(retrieve.requests, "get", lambda *a, **k: _FakeResponse(200, body=b"page body"))
+ monkeypatch.setattr(
+ retrieve, "get_session", lambda: SimpleNamespace(get=lambda *a, **k: _FakeResponse(200, body=b"page body"))
+ )
status, content, resolved_url = retrieve.fetch("http://93.184.216.34/page")
assert status == 200
assert content == b"page body"
@@ -147,7 +152,7 @@ def test_fetch_reports_the_host_that_answered_not_the_one_we_asked(monkeypatch):
return _FakeResponse(301, headers={"Location": "http://93.184.216.35/parked"}, is_redirect=True)
return _FakeResponse(200, body=b"parking page")
- monkeypatch.setattr(retrieve.requests, "get", fake_get)
+ monkeypatch.setattr(retrieve, "get_session", lambda: SimpleNamespace(get=fake_get))
status, _, resolved_url = retrieve.fetch("http://93.184.216.34/start")
assert status == 200
assert resolved_url == "http://93.184.216.35/parked"