An open source, non-profit web search engine
Say why a seed crawl wasn't started
Daoud Clarkef4321ba913f0
diff --git a/mwmbl/indexer/seed_crawl.py b/mwmbl/indexer/seed_crawl.pyindex c665254..550dd82 100644--- a/mwmbl/indexer/seed_crawl.py+++ b/mwmbl/indexer/seed_crawl.py@@ -26,6 +26,7 @@ import jsonimport timefrom collections import Counter, dequefrom datetime import datetime, timezone+from enum import StrEnumfrom http import HTTPStatusfrom logging import getLoggerfrom pathlib import Path@@ -50,6 +51,17 @@ STATUS_CRAWLING = "crawling"STATUS_DONE = "done"STATUS_FAILED = "failed"++class CrawlOutcome(StrEnum):+ """Why a search with crawl=true did or did not queue a crawl."""++ SCHEDULED = "scheduled"+ NO_RESULTS = "no_results"+ ALREADY_INDEXED = "already_indexed"+ ALREADY_RUNNING = "already_running"+ QUEUE_FULL = "queue_full"++QUEUE_KEY = "seed-crawl:queue"# Under the Redis client's five-second socket timeout, which a longer blocking pop would trip.QUEUE_POLL_SECONDS = 1@@ -79,34 +91,37 @@ def _now() -> str:def start_seed_crawl(user_id: int, query: str, index_pages: list[Document], staan_results: list[Document], new_staan_urls: set[str]-) -> bool:- """Queue a seed crawl of the Staan results the index lacked, returning whether it did.+) -> CrawlOutcome:+ """Queue a seed crawl of the Staan results the index lacked, returning whether it did, or why not.The seeds are the results the query did not retrieve. Of those, only the ones innew_staan_urls - which Combined Search's own write of Staan's results found missing fromthe index - count as pages the crawl added; the rest the index already held.- Nothing is queued when every Staan result is already in the index, when this user- already has a crawl queued or running, or when the queue is full.+ Nothing is queued when Staan returned nothing crawlable, when every Staan result is+ already in the index, when this user already has a crawl queued or running, or when the+ queue is full."""blacklisted_urls = find_blacklisted_urls(staan_results)allowed = [document for document in staan_results if document.url not in blacklisted_urls]indexed_urls = {document.url for document in index_pages}seed_urls = [document.url for document in allowed if document.url not in indexed_urls]+ if not allowed:+ return CrawlOutcome.NO_RESULTSif not seed_urls:- return False+ return CrawlOutcome.ALREADY_INDEXEDredis = get_redis_connection("default")# A slight overshoot from racing requests is harmless; the cap is there to stop one# user, or many, queueing hours of crawling.if redis.llen(QUEUE_KEY) >= settings.SEED_CRAWL_MAX_QUEUED:- return False+ return CrawlOutcome.QUEUE_FULL# Set atomically, so a double click or a retried request cannot queue the crawl twice.# The expiry outlasts the longest wait plus the crawl, and frees the user should the# worker die mid-crawl.lock_seconds = settings.SEED_CRAWL_MAX_SECONDS * (settings.SEED_CRAWL_MAX_QUEUED + 1)if not redis.set(_active_key(user_id), query, nx=True, ex=lock_seconds):- return False+ return CrawlOutcome.ALREADY_RUNNINGrecord_key = _record_key(user_id, query)domains = sorted({bare_host(document.url) for document in allowed})@@ -127,7 +142,13 @@ def start_seed_crawl(pipeline.expire(record_key, settings.SEED_CRAWL_RECORD_TTL_SECONDS)pipeline.lpush(QUEUE_KEY, json.dumps(job))pipeline.execute()- return True+ return CrawlOutcome.SCHEDULED+++def get_active_seed_crawl_query(user_id: int) -> str | None:+ """The query of this user's queued or running crawl, or None if they have none."""+ query = get_redis_connection("default").get(_active_key(user_id))+ return None if query is None else query.decode()def run_seed_crawl_worker() -> None:diff --git a/mwmbl/tinysearchengine/combined_search.py b/mwmbl/tinysearchengine/combined_search.pyindex ed4e620..b9fd25d 100644--- a/mwmbl/tinysearchengine/combined_search.py+++ b/mwmbl/tinysearchengine/combined_search.py@@ -43,7 +43,13 @@ from pydantic import Fieldfrom mwmbl import pricingfrom mwmbl.format import format_result_v2from mwmbl.indexer.index_batches import index_new_results_against_query-from mwmbl.indexer.seed_crawl import get_seed_crawl, get_seed_crawl_summary, start_seed_crawl+from mwmbl.indexer.seed_crawl import (+ CrawlOutcome,+ get_active_seed_crawl_query,+ get_seed_crawl,+ get_seed_crawl_summary,+ start_seed_crawl,+)from mwmbl.membership import combined_search_monthly_limitfrom mwmbl.models import Membership, UserBillingfrom mwmbl.quota import (@@ -73,11 +79,22 @@ class CombinedSearchResponse(SearchResponse):examples=[3],)crawl_scheduled: bool = Field(- description="Whether this search started a seed crawl (`crawl=true`). False when every "- "EUSP result is already in the index, when one of your crawls is still queued or running, or "- "when the crawl queue is full.",+ description="Whether this search started a seed crawl (`crawl=true`). `crawl_outcome` says why not.",examples=[True],)+ crawl_outcome: CrawlOutcome | None = Field(+ default=None,+ description="What `crawl=true` did: `scheduled` a crawl, or none because EUSP returned "+ "nothing to crawl (`no_results`), every EUSP result is already in the index "+ "(`already_indexed`), one of your crawls is still queued or running (`already_running`), "+ "or the crawl queue is full (`queue_full`). Null without `crawl=true`.",+ examples=["scheduled"],+ )+ active_crawl_query: str | None = Field(+ default=None,+ description="With `already_running`, the query of your crawl that is queued or running.",+ examples=["rust async runtimes"],+ )class NewPage(Schema):@@ -251,9 +268,14 @@ def init_router(ranker) -> None:asyncio.to_thread(index_staan_results, q, staan_results),)- crawl_scheduled = crawl and await sync_to_async(start_seed_crawl)(- user.id, q, retrieval.pages, staan_results, new_staan_urls- )+ crawl_outcome = None+ active_crawl_query = None+ if crawl:+ crawl_outcome = await sync_to_async(start_seed_crawl)(+ user.id, q, retrieval.pages, staan_results, new_staan_urls+ )+ if crawl_outcome == CrawlOutcome.ALREADY_RUNNING:+ active_crawl_query = await sync_to_async(get_active_seed_crawl_query)(user.id)formatted = [format_result_v2(result, i + 1, q) for i, result in enumerate(results)]return CombinedSearchResponse(@@ -263,7 +285,9 @@ def init_router(ranker) -> None:monthly_usage=monthly_usage,monthly_limit=monthly_limit,pages_indexed=len(new_staan_urls),- crawl_scheduled=crawl_scheduled,+ crawl_scheduled=crawl_outcome == CrawlOutcome.SCHEDULED,+ crawl_outcome=crawl_outcome,+ active_crawl_query=active_crawl_query,)@router.get(diff --git a/test/test_combined_search.py b/test/test_combined_search.pyindex 9d985e7..4dc2196 100644--- a/test/test_combined_search.py+++ b/test/test_combined_search.py@@ -529,6 +529,7 @@ def test_crawl_schedules_a_seed_crawl_of_what_the_index_lacked(body = _crawl(client, access_token).json()assert body["crawl_scheduled"] is True+ assert body["crawl_outcome"] == "scheduled"job = json.loads(redis_cache.rpop(seed_crawl.QUEUE_KEY))assert job == {"user_id": user.id,@@ -544,7 +545,10 @@ def test_crawl_schedules_a_seed_crawl_of_what_the_index_lacked(def test_no_crawl_without_the_flag(client, access_token, fresh_quota, redis_cache, crawl_sources):crawl_sources()- assert _get(client, access_token).json()["crawl_scheduled"] is False+ body = _get(client, access_token).json()++ assert body["crawl_scheduled"] is False+ assert body["crawl_outcome"] is Noneassert redis_cache.llen(seed_crawl.QUEUE_KEY) == 0@@ -554,10 +558,25 @@ def test_no_crawl_when_the_index_already_has_every_staan_result():crawl_sources(index=(INDEX_RESULT, STAAN_RESULT))- assert _crawl(client, access_token).json()["crawl_scheduled"] is False+ body = _crawl(client, access_token).json()++ assert body["crawl_scheduled"] is False+ assert body["crawl_outcome"] == "already_indexed"assert redis_cache.llen(seed_crawl.QUEUE_KEY) == 0+def test_a_crawl_already_running_is_named(client, access_token, fresh_quota, redis_cache, crawl_sources):+ crawl_sources()+ _crawl(client, access_token, query="tokio")++ body = _crawl(client, access_token, query="rust").json()++ assert body["crawl_scheduled"] is False+ assert body["crawl_outcome"] == "already_running"+ assert body["active_crawl_query"] == "tokio"++@pytest.mark.django_dbdef test_crawl_is_refused_with_an_api_key_and_not_counted(client, user, api_key, fresh_quota, redis_cache, crawl_sourcesdiff --git a/test/test_seed_crawl.py b/test/test_seed_crawl.pyindex ec34aa4..cee587e 100644--- a/test/test_seed_crawl.py+++ b/test/test_seed_crawl.py@@ -157,7 +157,9 @@ def test_only_staan_results_missing_from_the_index_are_seeds(redis_cache, monkeymonkeypatch.setattr(seed_crawl, "find_blacklisted_urls", lambda documents: set())index_pages = [Document("Async book", "https://rust-lang.github.io/async-book/", "")]- assert seed_crawl.start_seed_crawl(1, "tokio", index_pages, STAAN_RESULTS, set()) is True+ assert (+ seed_crawl.start_seed_crawl(1, "tokio", index_pages, STAAN_RESULTS, set()) == seed_crawl.CrawlOutcome.SCHEDULED+ )[job] = _queued_jobs(redis_cache)assert job["seed_urls"] == [SEED]@@ -180,18 +182,30 @@ def test_blacklisted_staan_results_are_neither_seeds_nor_domains(redis_cache, modef test_nothing_to_crawl_starts_nothing(redis_cache, monkeypatch):monkeypatch.setattr(seed_crawl, "find_blacklisted_urls", lambda documents: set())- assert seed_crawl.start_seed_crawl(1, "tokio", STAAN_RESULTS, STAAN_RESULTS, set()) is False+ assert (+ seed_crawl.start_seed_crawl(1, "tokio", STAAN_RESULTS, STAAN_RESULTS, set())+ == seed_crawl.CrawlOutcome.ALREADY_INDEXED+ )assert seed_crawl.get_seed_crawl(1, "tokio") is Noneassert _queued_jobs(redis_cache) == []+def test_nothing_starts_when_staan_returned_nothing_crawlable(redis_cache, monkeypatch):+ monkeypatch.setattr(seed_crawl, "find_blacklisted_urls", lambda documents: {SEED})++ assert seed_crawl.start_seed_crawl(1, "tokio", [], [STAAN_RESULTS[0]], set()) == seed_crawl.CrawlOutcome.NO_RESULTS+ assert seed_crawl.start_seed_crawl(1, "tokio", [], [], set()) == seed_crawl.CrawlOutcome.NO_RESULTS+ assert _queued_jobs(redis_cache) == []++def test_a_user_has_one_crawl_at_a_time(redis_cache, monkeypatch):monkeypatch.setattr(seed_crawl, "find_blacklisted_urls", lambda documents: set())- assert seed_crawl.start_seed_crawl(1, "tokio", [], STAAN_RESULTS, set()) is True- assert seed_crawl.start_seed_crawl(1, "tokio", [], STAAN_RESULTS, set()) is False- assert seed_crawl.start_seed_crawl(1, "rust", [], STAAN_RESULTS, set()) is False- assert seed_crawl.start_seed_crawl(2, "tokio", [], STAAN_RESULTS, set()) is True+ assert seed_crawl.start_seed_crawl(1, "tokio", [], STAAN_RESULTS, set()) == seed_crawl.CrawlOutcome.SCHEDULED+ assert seed_crawl.start_seed_crawl(1, "tokio", [], STAAN_RESULTS, set()) == seed_crawl.CrawlOutcome.ALREADY_RUNNING+ assert seed_crawl.start_seed_crawl(1, "rust", [], STAAN_RESULTS, set()) == seed_crawl.CrawlOutcome.ALREADY_RUNNING+ assert seed_crawl.get_active_seed_crawl_query(1) == "tokio"+ assert seed_crawl.start_seed_crawl(2, "tokio", [], STAAN_RESULTS, set()) == seed_crawl.CrawlOutcome.SCHEDULEDassert len(_queued_jobs(redis_cache)) == 2@@ -199,8 +213,8 @@ def test_nothing_is_queued_once_the_queue_is_full(redis_cache, monkeypatch, settmonkeypatch.setattr(seed_crawl, "find_blacklisted_urls", lambda documents: set())settings.SEED_CRAWL_MAX_QUEUED = 1- assert seed_crawl.start_seed_crawl(1, "tokio", [], STAAN_RESULTS, set()) is True- assert seed_crawl.start_seed_crawl(2, "tokio", [], STAAN_RESULTS, set()) is False+ assert seed_crawl.start_seed_crawl(1, "tokio", [], STAAN_RESULTS, set()) == seed_crawl.CrawlOutcome.SCHEDULED+ assert seed_crawl.start_seed_crawl(2, "tokio", [], STAAN_RESULTS, set()) == seed_crawl.CrawlOutcome.QUEUE_FULLassert seed_crawl.get_seed_crawl(2, "tokio") is None@@ -245,7 +259,7 @@ def test_the_worker_runs_a_queued_crawl(fake_web, redis_cache, user, index_path,assert seed_crawl.get_seed_crawl(user.id, "tokio")["status"] == "done"# The user can start another crawl once theirs has finished.- assert seed_crawl.start_seed_crawl(user.id, "rust", [], STAAN_RESULTS, set()) is True+ assert seed_crawl.start_seed_crawl(user.id, "rust", [], STAAN_RESULTS, set()) == seed_crawl.CrawlOutcome.SCHEDULED@pytest.mark.django_db@@ -262,7 +276,7 @@ def test_a_failed_crawl_is_recorded_and_not_retried(fake_web, redis_cache, user,assert record["status"] == "failed"assert record["finished_at"] is not Noneassert _queued_jobs(redis_cache) == []- assert seed_crawl.start_seed_crawl(user.id, "tokio", [], STAAN_RESULTS, set()) is True+ assert seed_crawl.start_seed_crawl(user.id, "tokio", [], STAAN_RESULTS, set()) == seed_crawl.CrawlOutcome.SCHEDULED@pytest.mark.django_db