An open source, non-profit web search engine
feat: add configurable rate limiting for crawler to reduce request bursting
thiswillbeyourgithub (aider)0de9a6a6c4d5
diff --git a/mwmbl/crawler/README.md b/mwmbl/crawler/README.mdindex 8677454..58b754c 100644--- a/mwmbl/crawler/README.md+++ b/mwmbl/crawler/README.md@@ -20,6 +20,9 @@ The crawler can be configured using the following environment variables:- `MAX_EXTRA_LINKS` (default: 50) - Maximum extra links to extract from non-good paragraphs- `MAX_SITE_URLS` (default: 100) - TODO: clarify usage of this variable+### Rate Limiting Configuration+- `CRAWL_DELAY_SECONDS` (default: 0.0) - Delay in seconds between crawl requests to reduce bursting. Change this only if necessary.+### Redis Configuration- `REDIS_URL` (default: 'redis://127.0.0.1:6379') - Redis connection URL for URL queues and statsdiff --git a/mwmbl/crawler/env_vars.py b/mwmbl/crawler/env_vars.pyindex 250edd4..f9fcc56 100644--- a/mwmbl/crawler/env_vars.py+++ b/mwmbl/crawler/env_vars.py@@ -18,5 +18,8 @@ MAX_NEW_LINKS = int(os.environ.get('MAX_NEW_LINKS', '50'))MAX_EXTRA_LINKS = int(os.environ.get('MAX_EXTRA_LINKS', '50'))MAX_SITE_URLS = int(os.environ.get('MAX_SITE_URLS', '100'))+# Rate limiting configuration - delay in seconds between crawl requests to reduce bursting+CRAWL_DELAY_SECONDS = float(os.environ.get('CRAWL_DELAY_SECONDS', '0.0'))+# Redis configurationREDIS_URL = os.environ.get('REDIS_URL', 'redis://127.0.0.1:6379')diff --git a/mwmbl/crawler/retrieve.py b/mwmbl/crawler/retrieve.pyindex 5ff014b..546a554 100644--- a/mwmbl/crawler/retrieve.py+++ b/mwmbl/crawler/retrieve.py@@ -13,7 +13,7 @@ from urllib3.exceptions import NewConnectionError, MaxRetryErrorfrom mwmbl.justext.core import html_to_domfrom mwmbl.justext.paragraph import Paragraph-from mwmbl.crawler.env_vars import TIMEOUT_SECONDS, MAX_FETCH_SIZE, MAX_NEW_LINKS, MAX_EXTRA_LINKS, MAX_SITE_URLS+from mwmbl.crawler.env_vars import TIMEOUT_SECONDS, MAX_FETCH_SIZE, MAX_NEW_LINKS, MAX_EXTRA_LINKS, MAX_SITE_URLS, CRAWL_DELAY_SECONDSALLOWED_EXCEPTIONS = (ValueError, ConnectionError, ReadTimeout, TimeoutError,OSError, NewConnectionError, MaxRetryError, SSLCertVerificationError)@@ -145,6 +145,11 @@ def get_new_links(paragraphs: list[Paragraph], current_url):def crawl_url(url):logger.info(f"Crawling URL {url}")++ # Rate limiting to reduce bursting - add delay between requests if configured+ if CRAWL_DELAY_SECONDS > 0:+ time.sleep(CRAWL_DELAY_SECONDS)+js_timestamp = int(time.time() * 1000)allowed = robots_allowed(url)if not allowed: