An open source, non-profit web search engine
Add the crawler options a CI smoke run needs
Daoud Clarkec9f341211c0f
diff --git a/mwmbl/crawl.py b/mwmbl/crawl.pyindex 6515cb3..edfad66 100644--- a/mwmbl/crawl.py+++ b/mwmbl/crawl.py@@ -1,3 +1,4 @@+import argparseimport loggingimport osimport random@@ -29,7 +30,15 @@ print("Mwmbl crawling statistics: https://mwmbl.org/stats")django.setup()from mwmbl.crawler.batch import HashedBatch, Result, Results-from mwmbl.crawler.env_vars import CRAWL_DELAY_SECONDS, CRAWLER_WORKERS, MWMBL_API_KEY, MWMBL_CONTACT_INFO+from mwmbl.crawler.env_vars import (+ CRAWL_DELAY_SECONDS,+ CRAWL_SUBMIT_MODE,+ 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_urlfrom mwmbl.indexer.index_batches import index_batches, index_pagesfrom mwmbl.indexer.update_urls import record_urls_in_database@@ -71,7 +80,7 @@ def _fetch_curated_domains() -> set[str]:# Validate environment variables when actually neededdef validate_environment():"""Validate required environment variables for crawler operation."""- if not MWMBL_API_KEY.strip():+ if CRAWL_SUBMIT_MODE != SUBMIT_MODE_OFF and not MWMBL_API_KEY.strip():raise ValueError("An environment variable MWMBL_API_KEY must be set to run the crawler")if MWMBL_CONTACT_INFO == "[email protected]":@@ -234,11 +243,17 @@ class Crawler:)for doc in new_items]- results = Results(api_key=MWMBL_API_KEY, results=result_items, crawler_version=CRAWLER_VERSION)- logger.info(f"Posting {len(result_items)} results")- response = requests.post("https://api.mwmbl.org/api/v1/crawler/results", json=results.dict())- logger.info(f"Response: {response.text}")- response.raise_for_status()+ if CRAWL_SUBMIT_MODE == SUBMIT_MODE_OFF:+ logger.info(f"Submission is off, not posting {len(result_items)} results")+ else:+ results = Results(api_key=MWMBL_API_KEY, results=result_items, crawler_version=CRAWLER_VERSION)+ results_url = f"{REMOTE_SERVER}/api/v1/crawler/results"+ if CRAWL_SUBMIT_MODE == SUBMIT_MODE_DRY_RUN:+ results_url += "?dry_run=true"+ logger.info(f"Posting {len(result_items)} results to {results_url}")+ response = requests.post(results_url, json=results.dict())+ logger.info(f"Response: {response.text}")+ response.raise_for_status()new_remote_items = remote_index.retrieve(term, refresh=True)# Check how many of our items were indexed@@ -273,6 +288,20 @@ class Crawler:logger.exception(f"Error running indexing: '{err}'")time.sleep(10)+ def run_once(self):+ """+ Crawl one batch and index it, in this process, then return.++ The continuous loops swallow every exception and restart, which is what a+ long-running volunteer crawler wants and useless as a check: the process stays+ alive and reports nothing while every pass fails. This runs the same pipeline+ with errors fatal, so a caller - CI, mainly - can use the exit code.+ """+ validate_environment()+ self.check_redis()+ self.process_batch()+ self.run_indexing()+def run(self):"""Main entry point for the crawler.@@ -374,5 +403,28 @@ def run():return get_default_crawler().run()+def run_once():+ """Run a single crawl and indexing pass (backward compatibility)."""+ return get_default_crawler().run_once()+++def main():+ parser = argparse.ArgumentParser(prog="mwmbl-crawl", description="Run the Mwmbl crawler.")+ parser.add_argument(+ "--once",+ action="store_true",+ help=(+ "Crawl one batch, index it and exit, failing on the first error instead of "+ "restarting. Intended for smoke tests, not for crawling."+ ),+ )+ args = parser.parse_args()++ if args.once:+ run_once()+ else:+ run()++if __name__ == "__main__":- run()+ main()diff --git a/mwmbl/crawler/README.md b/mwmbl/crawler/README.mdindex e46a43f..679197f 100644--- a/mwmbl/crawler/README.md+++ b/mwmbl/crawler/README.md@@ -43,7 +43,7 @@ The crawler fetches **web pages (HTML content)** from URLs, specifically:This is an **on-demand, distributed crawler**:1. **URL Assignment**: Users request batches of URLs to crawl via `/api/v1/crawler/batches/new`-2. **Batch Processing**: The system assigns up to 100 URLs at a time (configurable via `BATCH_SIZE`)+2. **Batch Processing**: The system assigns up to 100 URLs at a time (configurable via the `CRAWL_BATCH_SIZE` environment variable)3. **Crawling**: Users crawl those URLs with rate limiting (configurable delay between requests)4. **Result Submission**: Users submit crawled results back via `/api/v1/crawler/batches/`diff --git a/mwmbl/crawler/env_vars.py b/mwmbl/crawler/env_vars.pyindex 556e49e..a73548f 100644--- a/mwmbl/crawler/env_vars.py+++ b/mwmbl/crawler/env_vars.py@@ -16,3 +16,29 @@ MWMBL_API_KEY = os.environ.get("MWMBL_API_KEY", "")# Contact information configuration - required for responsible crawlingMWMBL_CONTACT_INFO = os.environ.get("MWMBL_CONTACT_INFO", "[email protected]")++# Bounds for running the crawler somewhere that is not a volunteer's machine - CI, mainly.+# The defaults are the unbounded behaviour a volunteer crawler has always had.++# URLs assigned per batch.+CRAWL_BATCH_SIZE = int(os.environ.get("CRAWL_BATCH_SIZE", "100"))++# Comma-separated domains to crawl. When set, these replace the queue's usual candidates,+# so a run touches only sites we chose rather than a sample of the live URL queue.+CRAWL_ALLOWED_DOMAINS = frozenset(+ domain.strip() for domain in os.environ.get("CRAWL_ALLOWED_DOMAINS", "").split(",") if domain.strip()+)++# What to do with results the crawler decides are worth submitting:+# index - post them normally, so they go into the Mwmbl index (the default)+# dry-run - post them with ?dry_run=true, so the server authenticates and validates+# them but indexes nothing+# off - do not post at all, and do not require an API key+SUBMIT_MODE_INDEX = "index"+SUBMIT_MODE_DRY_RUN = "dry-run"+SUBMIT_MODE_OFF = "off"+SUBMIT_MODES = {SUBMIT_MODE_INDEX, SUBMIT_MODE_DRY_RUN, SUBMIT_MODE_OFF}++CRAWL_SUBMIT_MODE = os.environ.get("CRAWL_SUBMIT_MODE", SUBMIT_MODE_INDEX)+if CRAWL_SUBMIT_MODE not in SUBMIT_MODES:+ raise ValueError(f"CRAWL_SUBMIT_MODE must be one of {sorted(SUBMIT_MODES)}, got {CRAWL_SUBMIT_MODE!r}")diff --git a/mwmbl/redis_url_queue.py b/mwmbl/redis_url_queue.pyindex a7736d7..d4c7bd9 100644--- a/mwmbl/redis_url_queue.py+++ b/mwmbl/redis_url_queue.py@@ -9,6 +9,7 @@ from typing import Callablefrom redis import Redisfrom mwmbl.crawler.domains import TOP_DOMAINS, DomainLinkDatabase+from mwmbl.crawler.env_vars import CRAWL_ALLOWED_DOMAINS, CRAWL_BATCH_SIZEfrom mwmbl.crawler.urls import FoundURLfrom mwmbl.hn_top_domains_filtered import DOMAINSfrom mwmbl.indexer.blacklist import get_default_blacklist_provider@@ -36,7 +37,6 @@ MAX_OTHER_DOMAINS = 10000NUM_TOP_DOMAIN_URLS_TO_INCLUDE = 50NUM_OTHER_URLS_TO_INCLUDE = 100-BATCH_SIZE = 100# Discount URLs crawled recently - this is the scale - currently 10 monthsSCORE_TIME_CONSTANT = 60 * 60 * 24 * 30 * 10@@ -106,27 +106,40 @@ class RedisURLQueue:logger.info(f"Queued {len(found_urls)} URLs, number of domains: {self.redis.zcard(DOMAIN_SCORE_KEY)}")def get_batch(self, user_id: str) -> list[str]:- top_scoring_domains = set(self.redis.zrange(DOMAIN_SCORE_KEY, 0, 2000, desc=True))- top_other_domains = top_scoring_domains - DOMAINS.keys()curated_domains = self.get_curated_domains_function()- domains = list(CORE_DOMAINS)- top_curated_domains = (DOMAINS.keys() & top_scoring_domains) | curated_domains- if len(top_curated_domains) > NUM_TOP_DOMAIN_URLS_TO_INCLUDE:- domains += random.sample(list(top_curated_domains), NUM_TOP_DOMAIN_URLS_TO_INCLUDE)+ if CRAWL_ALLOWED_DOMAINS:+ # An allowlist replaces the candidates outright: a CI crawl has to touch a set+ # of sites we chose, not a sample of whatever the live queue happens to hold.+ # Sorting keeps the seed choice reproducible despite the randomised+ # PYTHONHASHSEED the crawler image sets.+ domains = sorted(CRAWL_ALLOWED_DOMAINS)+ seed_domains = sorted(CRAWL_ALLOWED_DOMAINS)else:- domains += list(top_curated_domains)+ top_scoring_domains = set(self.redis.zrange(DOMAIN_SCORE_KEY, 0, 2000, desc=True))+ top_other_domains = top_scoring_domains - DOMAINS.keys()- if len(top_other_domains) > NUM_OTHER_URLS_TO_INCLUDE:- domains += random.sample(list(top_other_domains), NUM_OTHER_URLS_TO_INCLUDE)- else:- domains += list(top_other_domains)+ domains = list(CORE_DOMAINS)+ top_curated_domains = (DOMAINS.keys() & top_scoring_domains) | curated_domains+ if len(top_curated_domains) > NUM_TOP_DOMAIN_URLS_TO_INCLUDE:+ domains += random.sample(list(top_curated_domains), NUM_TOP_DOMAIN_URLS_TO_INCLUDE)+ else:+ domains += list(top_curated_domains)++ if len(top_other_domains) > NUM_OTHER_URLS_TO_INCLUDE:+ domains += random.sample(list(top_other_domains), NUM_OTHER_URLS_TO_INCLUDE)+ else:+ domains += list(top_other_domains)++ seed_domains = list(DOMAINS.keys() | curated_domains)domains = [domain for domain in domains if not self.blacklist_provider.is_domain_blacklisted(domain)]logger.info(f"Getting batch from domains {domains}")- # Add a random url as the root domain of one of DOMAINS- random_domain = random.choice(list(DOMAINS.keys() | curated_domains))+ # Add a random url as the root domain of one of DOMAINS. The seed needs the same+ # blacklist filter as the rest: it is a URL we are about to fetch.+ seed_domains = [domain for domain in seed_domains if not self.blacklist_provider.is_domain_blacklisted(domain)]+ random_domain = random.choice(seed_domains)urls = [f"https://{random_domain}/"]# Pop the highest scoring URL from each domain@@ -146,7 +159,7 @@ class RedisURLQueue:for url, score in domain_urls_scores:urls.append(url)- if len(urls) >= BATCH_SIZE:+ if len(urls) >= CRAWL_BATCH_SIZE:breaklogger.info(f"Returning URLs: {urls}")diff --git a/pyproject.toml b/pyproject.tomlindex a333f51..4453fc4 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -68,7 +68,7 @@ indexer = [[project.scripts]mwmbl-tinysearchengine = "mwmbl.main:run"-mwmbl-crawl = "mwmbl.crawl:run"+mwmbl-crawl = "mwmbl.crawl:main"[dependency-groups]dev = [diff --git a/test/test_crawler_ci_options.py b/test/test_crawler_ci_options.pynew file mode 100644index 0000000..fc92de4--- /dev/null+++ b/test/test_crawler_ci_options.py@@ -0,0 +1,218 @@+"""The options that make the crawler safe to run somewhere that is not a volunteer's machine.++A CI smoke test needs a crawl that is bounded (a handful of URLs), aimed at sites we chose,+and unable to write into the production index. These cover the three knobs that give it that,+plus the one-shot mode that turns the run into an exit code.+"""++from datetime import datetime+from random import Random+from unittest.mock import MagicMock, patch++import fakeredis+import pytest++from mwmbl.crawl import Crawler, validate_environment+from mwmbl.crawler.urls import FoundURL, URLStatus+from mwmbl.indexer.blacklist_providers import StaticBlacklistProvider+from mwmbl.redis_url_queue import RedisURLQueue+from mwmbl.utils import parse_url+++def fake_redis():+ return fakeredis.FakeRedis(decode_responses=True, health_check_interval=30)+++def blacklist_provider():+ return StaticBlacklistProvider({"spam.com"})+++def url_queue(fake_redis, blacklist_provider):+ return RedisURLQueue(fake_redis, lambda: set(), blacklist_provider)+++def found_url(url: str) -> FoundURL:+ return FoundURL(+ url=url,+ user_id_hash="test_user_hash",+ status=URLStatus.NEW,+ timestamp=datetime.utcnow(),+ last_crawled=None,+ )+++# ---------------------------------------------------------------------------+# CRAWL_BATCH_SIZE+# ---------------------------------------------------------------------------+++def test_batch_size_bounds_the_number_of_urls(url_queue):+ """CI wants a crawl of ten URLs, not a hundred."""+ url_queue.queue_urls([found_url(f"https://example{i}.com/page") for i in range(50)])++ with patch("mwmbl.redis_url_queue.CRAWL_BATCH_SIZE", 10):+ batch = url_queue.get_batch("test_user")++ # The seed URL is appended before the loop checks the bound, so ten is the last size+ # at which another domain can still be added.+ assert len(batch) <= 11, f"batch of {len(batch)} ignored CRAWL_BATCH_SIZE"+++def test_batch_size_defaults_to_the_unbounded_behaviour():+ """The default has to stay what volunteer crawlers have always run with."""+ from mwmbl.crawler.env_vars import CRAWL_BATCH_SIZE++ assert CRAWL_BATCH_SIZE == 100+++# ---------------------------------------------------------------------------+# CRAWL_ALLOWED_DOMAINS+# ---------------------------------------------------------------------------+++def test_allowed_domains_restrict_the_crawl(url_queue):+ """Every URL in the batch, seed included, must come from the allowlist."""+ url_queue.queue_urls([found_url(f"https://example{i}.com/page") for i in range(20)])+ allowed = frozenset({"mwmbl.org", "en.wikipedia.org"})++ with patch("mwmbl.redis_url_queue.CRAWL_ALLOWED_DOMAINS", allowed):+ batch = url_queue.get_batch("test_user")++ assert batch, "the allowlist produced no URLs at all"+ crawled_domains = {parse_url(url).netloc for url in batch}+ assert crawled_domains <= allowed, f"crawled outside the allowlist: {crawled_domains - allowed}"+++def test_allowed_domains_still_honour_the_blacklist(fake_redis, blacklist_provider):+ """An allowlisted domain that is blacklisted must not be crawled."""+ queue = RedisURLQueue(fake_redis, lambda: set(), blacklist_provider)++ with patch("mwmbl.redis_url_queue.CRAWL_ALLOWED_DOMAINS", frozenset({"spam.com", "mwmbl.org"})):+ batch = queue.get_batch("test_user")++ assert not any(parse_url(url).netloc == "spam.com" for url in batch)+++def test_allowed_domains_pick_the_seed_deterministically(url_queue):+ """The crawler image randomises PYTHONHASHSEED, so set ordering must not pick the seed URL.++ Two crawler processes given the same allowlist have to seed from the same domain, which+ means choosing from a sorted sequence rather than from the set itself.+ """+ allowed = frozenset({"mwmbl.org", "en.wikipedia.org", "example.org"})+ expected_domain = Random(1).choice(sorted(allowed))++ with (+ patch("mwmbl.redis_url_queue.CRAWL_ALLOWED_DOMAINS", allowed),+ patch("mwmbl.redis_url_queue.random", Random(1)),+ ):+ batch = url_queue.get_batch("test_user")++ assert batch[0] == f"https://{expected_domain}/"+++def test_no_allowlist_leaves_domain_selection_alone(url_queue):+ """The default path must keep sampling the live queue as before."""+ url_queue.queue_urls([found_url(f"https://example{i}.com/page") for i in range(20)])++ batch = url_queue.get_batch("test_user")++ assert batch+ assert not all(parse_url(url).netloc == parse_url(batch[0]).netloc for url in batch)+++# ---------------------------------------------------------------------------+# CRAWL_SUBMIT_MODE+# ---------------------------------------------------------------------------+++def test_api_key_is_required_when_results_are_submitted():+ with (+ patch("mwmbl.crawl.CRAWL_SUBMIT_MODE", "index"),+ patch("mwmbl.crawl.MWMBL_API_KEY", ""),+ patch("mwmbl.crawl.MWMBL_CONTACT_INFO", "[email protected]"),+ ):+ with pytest.raises(ValueError, match="MWMBL_API_KEY"):+ validate_environment()+++def test_api_key_is_not_required_when_submission_is_off():+ """Fork pull requests get no secrets, so the keyless run has to be a supported mode."""+ with (+ patch("mwmbl.crawl.CRAWL_SUBMIT_MODE", "off"),+ patch("mwmbl.crawl.MWMBL_API_KEY", ""),+ patch("mwmbl.crawl.MWMBL_CONTACT_INFO", "[email protected]"),+ ):+ validate_environment()+++def test_contact_info_is_required_whatever_the_submit_mode():+ """We are fetching other people's pages either way."""+ with (+ patch("mwmbl.crawl.CRAWL_SUBMIT_MODE", "off"),+ patch("mwmbl.crawl.MWMBL_API_KEY", ""),+ patch("mwmbl.crawl.MWMBL_CONTACT_INFO", "[email protected]"),+ ):+ with pytest.raises(ValueError, match="MWMBL_CONTACT_INFO"):+ validate_environment()+++# ---------------------------------------------------------------------------+# --once+# ---------------------------------------------------------------------------+++def test_run_once_does_one_pass_and_returns():+ crawler = Crawler()++ with (+ patch("mwmbl.crawl.validate_environment"),+ patch.object(Crawler, "check_redis"),+ patch.object(Crawler, "process_batch") as process_batch,+ patch.object(Crawler, "run_indexing") as run_indexing,+ ):+ crawler.run_once()++ process_batch.assert_called_once_with()+ run_indexing.assert_called_once_with()+++def test_run_once_propagates_errors_instead_of_restarting():+ """The whole point: the continuous loops swallow this, so a broken crawler looks healthy."""+ crawler = Crawler()++ with (+ patch("mwmbl.crawl.validate_environment"),+ patch.object(Crawler, "check_redis"),+ patch.object(Crawler, "process_batch", side_effect=RuntimeError("crawl failed")),+ patch.object(Crawler, "run_indexing") as run_indexing,+ ):+ with pytest.raises(RuntimeError, match="crawl failed"):+ crawler.run_once()++ run_indexing.assert_not_called()+++def test_once_flag_selects_the_single_pass():+ from mwmbl.crawl import main++ crawler = MagicMock()+ with patch("mwmbl.crawl.get_default_crawler", return_value=crawler), patch("sys.argv", ["mwmbl-crawl", "--once"]):+ main()++ crawler.run_once.assert_called_once_with()+ crawler.run.assert_not_called()+++def test_no_flag_runs_continuously():+ from mwmbl.crawl import main++ crawler = MagicMock()+ with patch("mwmbl.crawl.get_default_crawler", return_value=crawler), patch("sys.argv", ["mwmbl-crawl"]):+ main()++ crawler.run.assert_called_once_with()+ crawler.run_once.assert_not_called()