Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Fix robots.txt spamming by adding Redis caching

Daoud Clarkea11be6eb641f
diff --git a/mwmbl/crawl.py b/mwmbl/crawl.py
index db8684f..da79577 100644
--- a/mwmbl/crawl.py
+++ b/mwmbl/crawl.py
@@ -153,7 +153,7 @@ class Crawler:
delay = CRAWL_DELAY_SECONDS * (0.9 + 0.2 * random.random())
time.sleep(delay)
- result = crawl_url(url)
+ result = crawl_url(url, self.redis)
results.append(result)
logger.debug("Result", result)
diff --git a/mwmbl/crawler/retrieve.py b/mwmbl/crawler/retrieve.py
index f9958fd..00d6307 100644
--- a/mwmbl/crawler/retrieve.py
+++ b/mwmbl/crawler/retrieve.py
@@ -1,13 +1,16 @@
+import json
import re
import time
from logging import getLogger
from multiprocessing.pool import ThreadPool
from ssl import SSLCertVerificationError
+from typing import List, Optional
from urllib.parse import urlparse, urlunsplit, urljoin
from urllib.robotparser import RobotFileParser
import requests
from mwmbl.justext import core, utils
+from redis import Redis
from requests import ReadTimeout
from urllib3.exceptions import NewConnectionError, MaxRetryError
@@ -40,6 +43,8 @@ MAX_SITE_URLS = 100
CRAWLER_VERSION: str = "0.2.0"
USER_AGENT = f"mwmbl/{CRAWLER_VERSION} (https://github.com/mwmbl/mwmbl/ contact {MWMBL_CONTACT_INFO})"
+ROBOTS_CACHE_TTL_SECONDS = 60 * 60 * 24
+ROBOTS_CACHE_ERROR_TTL_SECONDS = 60 * 60
logger = getLogger(__name__)
@@ -85,25 +90,38 @@ def fetch(url):
raise ValueError(f"Too many redirects for URL {url}")
-def robots_allowed(url):
+def robots_allowed(url: str, redis: Redis = None) -> bool:
try:
parsed_url = urlparse(url)
except ValueError:
logger.info(f"Unable to parse URL: {url}")
return False
+ domain = parsed_url.netloc
robots_url = urlunsplit((parsed_url.scheme, parsed_url.netloc, 'robots.txt', '', ''))
- parse_robots = RobotFileParser(robots_url)
+ if redis:
+ cached_content = _get_robots_from_cache(redis, domain)
+ if cached_content is not None:
+ logger.debug(f"Robots cache hit for {domain}")
+ parse_robots = RobotFileParser()
+ parse_robots.parse(cached_content)
+ allowed = parse_robots.can_fetch(USER_AGENT, url)
+ logger.debug(f"Robots allowed for {url} (cached): {allowed}")
+ return allowed
try:
status_code, content = fetch(robots_url)
except ALLOWED_EXCEPTIONS as e:
logger.debug(f"Robots error: {robots_url}, {e}")
+ if redis:
+ _cache_robots_content(redis, domain, [], error=True)
return True
if status_code != 200:
logger.debug(f"Robots status code: {status_code}")
+ if redis:
+ _cache_robots_content(redis, domain, [], error=True)
return True
decoded = None
@@ -116,14 +134,54 @@ def robots_allowed(url):
if decoded is None:
logger.info(f"Unable to decode robots file {robots_url}")
+ if redis:
+ _cache_robots_content(redis, domain, [], error=True)
return True
+ parse_robots = RobotFileParser()
parse_robots.parse(decoded)
allowed = parse_robots.can_fetch(USER_AGENT, url)
+
+ if redis:
+ _cache_robots_content(redis, domain, decoded, error=False)
+
logger.debug(f"Robots allowed for {url}: {allowed}")
return allowed
+def _get_robots_from_cache(redis: Redis, domain: str) -> Optional[List[str]]:
+ cache_key = f"robots:{domain}"
+ cached = redis.get(cache_key)
+ if cached is None:
+ return None
+
+ try:
+ data = json.loads(cached)
+ if time.time() > data['expires_at']:
+ redis.delete(cache_key)
+ return None
+ return data['content']
+ except (json.JSONDecodeError, KeyError) as e:
+ logger.warning(f"Invalid cache entry for {cache_key}: {e}, removing")
+ redis.delete(cache_key)
+ return None
+
+
+def _cache_robots_content(redis: Redis, domain: str, content: List[str], error: bool = False):
+ cache_key = f"robots:{domain}"
+ now = time.time()
+ ttl = ROBOTS_CACHE_ERROR_TTL_SECONDS if error else ROBOTS_CACHE_TTL_SECONDS
+
+ cache_data = {
+ 'content': content,
+ 'cached_at': int(now),
+ 'expires_at': int(now + ttl)
+ }
+
+ redis.setex(cache_key, ttl, json.dumps(cache_data))
+ logger.debug(f"Cached robots.txt for {domain}, expires in {ttl}s")
+
+
def _resolve_and_validate_link(href: str, current_url: str) -> str | None:
"""Resolve a raw href to an absolute URL and validate it. Returns None if invalid."""
href = urljoin(current_url, href)
@@ -213,10 +271,10 @@ def get_og_meta(dom) -> tuple[str, str]:
return og_title, og_desc
-def crawl_url(url):
+def crawl_url(url, redis=None):
logger.info(url)
js_timestamp = int(time.time() * 1000)
- allowed = robots_allowed(url)
+ allowed = robots_allowed(url, redis)
if not allowed:
return {
'url': url,
@@ -342,9 +400,10 @@ def crawl_url(url):
}
-def crawl_batch(batch, num_threads):
+def crawl_batch(batch, num_threads, redis=None):
+ from functools import partial
with ThreadPool(num_threads) as pool:
- result = pool.map(crawl_url, batch)
+ result = pool.map(partial(crawl_url, redis=redis), batch)
return result
diff --git a/mwmbl/tinysearchengine/super_search.py b/mwmbl/tinysearchengine/super_search.py
index f8ff367..a67da30 100644
--- a/mwmbl/tinysearchengine/super_search.py
+++ b/mwmbl/tinysearchengine/super_search.py
@@ -68,7 +68,7 @@ _CRAWL_EXECUTOR = ThreadPoolExecutor(
async def _crawl(url: str):
"""Run the synchronous crawl_url on the dedicated crawl executor."""
loop = asyncio.get_running_loop()
- return await loop.run_in_executor(_CRAWL_EXECUTOR, crawl_url, url)
+ return await loop.run_in_executor(_CRAWL_EXECUTOR, crawl_url, url, None)
# ---------------------------------------------------------------------------
diff --git a/scripts/verify_user_ids_beta.py b/scripts/verify_user_ids_beta.py
index d5962e6..cc026d5 100644
--- a/scripts/verify_user_ids_beta.py
+++ b/scripts/verify_user_ids_beta.py
@@ -60,7 +60,7 @@ def main():
results = []
for url in urls:
print(f" {url}")
- raw = crawl_url(url)
+ raw = crawl_url(url, None)
content = raw.get("content")
if content and not raw.get("error") and content.get("title"):
last_crawled = int(raw["timestamp"] / 1000) # ms → seconds
diff --git a/test/test_super_search.py b/test/test_super_search.py
index 471293a..72ad4c3 100644
--- a/test/test_super_search.py
+++ b/test/test_super_search.py
@@ -179,7 +179,7 @@ def test_promoted_results_use_top_k(client, api_key, monkeypatch):
# Scores in descending order — only the top-2 should be promoted.
_stub_scoring(monkeypatch, [0.9, 0.5, 0.1] + [0.0] * 20)
- def fake_crawl(url):
+ def fake_crawl(url, redis=None):
return {"url": url, "status": 200, "timestamp": 0, "content": None, "error": None}
monkeypatch.setattr("mwmbl.tinysearchengine.super_search.crawl_url", fake_crawl)
@@ -221,7 +221,7 @@ def test_heap_replacement_promotes_better_late_doc(client, api_key, monkeypatch)
# Best (0.9) beats the minimum and must be promoted.
_stub_scoring(monkeypatch, [0.1, 0.1, 0.1, 0.9] + [0.0] * 20)
- def fake_crawl(url):
+ def fake_crawl(url, redis=None):
return {"url": url, "status": 200, "timestamp": 0, "content": None, "error": None}
monkeypatch.setattr("mwmbl.tinysearchengine.super_search.crawl_url", fake_crawl)
@@ -253,7 +253,7 @@ def test_heap_equal_score_does_not_enter_full_heap(client, api_key, monkeypatch)
})
_stub_scoring(monkeypatch, [0.5, 0.5, 0.5] + [0.0] * 20)
- def fake_crawl(url):
+ def fake_crawl(url, redis=None):
return {"url": url, "status": 200, "timestamp": 0, "content": None, "error": None}
monkeypatch.setattr("mwmbl.tinysearchengine.super_search.crawl_url", fake_crawl)
@@ -279,7 +279,7 @@ def test_final_results_event_emitted(client, api_key, monkeypatch):
})
_stub_scoring(monkeypatch, [0.5] + [0.0] * 20)
- def fake_crawl(url):
+ def fake_crawl(url, redis=None):
return {"url": url, "status": 200, "timestamp": 0, "content": None, "error": None}
monkeypatch.setattr("mwmbl.tinysearchengine.super_search.crawl_url", fake_crawl)
@@ -414,7 +414,7 @@ def test_link_following_adds_followed_docs(client, api_key, monkeypatch):
})
_stub_scoring(monkeypatch, [0.9] + [0.0] * 20)
- def fake_crawl(url):
+ def fake_crawl(url, redis=None):
if url == "https://parent.example/":
return {"url": url, "status": 200, "content": {
"title": "Python parent", "extract": "python parent text",
@@ -457,7 +457,7 @@ def test_no_duplicate_consecutive_results_frames(client, api_key, monkeypatch):
})
_stub_scoring(monkeypatch, [0.9, 0.8] + [0.0] * 40)
- def fake_crawl(url):
+ def fake_crawl(url, redis=None):
return {"url": url, "status": 200, "content": None}
monkeypatch.setattr("mwmbl.tinysearchengine.super_search.crawl_url", fake_crawl)
diff --git a/uv.lock b/uv.lock
index 5fd5809..87c84ac 100644
--- a/uv.lock
+++ b/uv.lock
@@ -801,7 +801,7 @@ requires-dist = [
{ name = "numpy", specifier = "==1.23.2" },
{ name = "objgraph", specifier = ">=3.6.1" },
{ name = "pandas", specifier = ">=1.3.5,<2.0.0" },
- { name = "polar-sdk", specifier = ">=0.10.0" },
+ { name = "polar-sdk", specifier = "==0.31.7" },
{ name = "psutil", specifier = ">=6.0.0" },
{ name = "psycopg2-binary", specifier = ">=2.9.3" },
{ name = "py-spy", specifier = ">=0.4.1" },
@@ -956,7 +956,7 @@ wheels = [
[[package]]
name = "polar-sdk"
-version = "0.31.3"
+version = "0.31.7"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "httpcore" },
@@ -965,9 +965,9 @@ dependencies = [
{ name = "pydantic" },
{ name = "standardwebhooks" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/19/cb/60c71f31c2c0afe9fc70c593a218ffde6c017b03f9a581e2af0ea63b5230/polar_sdk-0.31.3.tar.gz", hash = "sha256:d69b73e66040adab5ace51bb67c72d91edfca56c67c6aad5cbe6a5cb2a1295f7", size = 303751, upload-time = "2026-04-10T09:42:54.574Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/78/8f/c60e5793fa9d1ea4344ae61522567ba2b8660170341794e869b936fcd5c2/polar_sdk-0.31.7.tar.gz", hash = "sha256:05fd6d47c15b2bae5efa068bee8f2251527db982584a81b5c78e042b9723874a", size = 323115, upload-time = "2026-06-12T06:51:02.634Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/ef/23/bd856ec12a8faef40bfb6b30e7add657952c7266f5f0ac7c156067fa30ea/polar_sdk-0.31.3-py3-none-any.whl", hash = "sha256:22fa1ae3fa2c79cf2279dd3b1ff633d193132197dcdd807ec7191fb14544ff80", size = 853744, upload-time = "2026-04-10T09:42:53.032Z" },
+ { url = "https://files.pythonhosted.org/packages/dc/e0/a88026b9432c7e2c0c096911ddc97cb06f483036a00a8afd5254efe1c16a/polar_sdk-0.31.7-py3-none-any.whl", hash = "sha256:acff8f3405046d45fa31130674f269314586fee1d3d2fec221eed21cb8697340", size = 902336, upload-time = "2026-06-12T06:51:01.002Z" },
]
[[package]]