An open source, non-profit web search engine
Add an endpoint counting the pages a seed crawl added
Claude7c6723f41fec
diff --git a/mwmbl/indexer/seed_crawl.py b/mwmbl/indexer/seed_crawl.pyindex 3a5d1dd..8ced6cd 100644--- a/mwmbl/indexer/seed_crawl.py+++ b/mwmbl/indexer/seed_crawl.py@@ -11,7 +11,7 @@ much of the frontier it holds. Each round is indexed as it finishes, so what a cadded is visible while it is still running.What it added is recorded in Redis against the user and the query, where-GET /api/v2/combined-search/new-pages reads it, and counted on the user for their stats.+GET /api/v2/combined-search/new-pages (and /new-pages/count) reads it, and counted on the user for their stats."""import hashlib@@ -170,19 +170,32 @@ def crawl_within_domains(seed_urls: list[str], domains: set[str], redis):yield len(batch), documents-def get_seed_crawl(user_id: int, query: str) -> dict | None:- """The record of this user's seed crawl for this query, or None if there is none."""+def get_seed_crawl_summary(user_id: int, query: str) -> dict | None:+ """This user's seed crawl for this query without its pages, or None if there is none.++ Counts the pages rather than reading them, so it stays cheap for a crawl that has added+ a thousand.+ """redis = get_redis_connection("default")record = redis.hgetall(_record_key(user_id, query))if not record:return Nonefields = {key.decode(): value.decode() for key, value in record.items()}- pages = [json.loads(page) for page in redis.lrange(_pages_key(user_id, query), 0, -1)]return {"query": fields["query"],"status": fields["status"],"started_at": fields["started_at"],"finished_at": fields.get("finished_at"),"pages_crawled": int(fields["pages_crawled"]),- "pages": pages,+ "pages_indexed": redis.llen(_pages_key(user_id, query)),}+++def get_seed_crawl(user_id: int, query: str) -> dict | None:+ """This user's seed crawl for this query with the pages it added, or None if there is none."""+ summary = get_seed_crawl_summary(user_id, query)+ if summary is None:+ return None+ redis = get_redis_connection("default")+ pages = [json.loads(page) for page in redis.lrange(_pages_key(user_id, query), 0, -1)]+ return {**summary, "pages": pages}diff --git a/mwmbl/tinysearchengine/combined_search.py b/mwmbl/tinysearchengine/combined_search.pyindex 717e20d..86f9c88 100644--- a/mwmbl/tinysearchengine/combined_search.py+++ b/mwmbl/tinysearchengine/combined_search.py@@ -44,7 +44,7 @@ from mwmbl import pricingfrom mwmbl.background import seed_crawlfrom mwmbl.format import format_result_v2from mwmbl.indexer.index_batches import index_results_against_query-from mwmbl.indexer.seed_crawl import get_seed_crawl, start_seed_crawl+from mwmbl.indexer.seed_crawl import get_seed_crawl, get_seed_crawl_summary, start_seed_crawlfrom mwmbl.membership import combined_search_monthly_limitfrom mwmbl.models import Membership, UserBillingfrom mwmbl.quota import (@@ -86,12 +86,16 @@ class NewPage(Schema):extract: str-class SeedCrawlResponse(Schema):+class SeedCrawlSummaryResponse(Schema):query: strstatus: str = Field(description="`crawling` while the crawl runs, then `done`.", examples=["crawling"])started_at: strfinished_at: str | Nonepages_crawled: int = Field(description="Pages fetched so far, including ones that added nothing.")+ pages_indexed: int = Field(description="Pages the crawl has added to the Mwmbl index so far.", examples=[42])+++class SeedCrawlResponse(SeedCrawlSummaryResponse):pages: list[NewPage] = Field(description="Pages the crawl has added to the Mwmbl index so far.")@@ -120,7 +124,8 @@ DESCRIPTION = ("With `crawl=true` (JWT only), the search also starts a background crawl of the EUSP results ""that were not already in the Mwmbl index, following their links within the domains EUSP "f"returned, up to {settings.SEED_CRAWL_MAX_PAGES:,} pages. "- "`GET /api/v2/combined-search/new-pages?q=...` lists what it has added.\n\n"+ "`GET /api/v2/combined-search/new-pages?q=...` lists what it has added, and "+ "`GET /api/v2/combined-search/new-pages/count?q=...` counts it.\n\n""If EUSP is down or unconfigured, the request loses its extra recall, not its ""results: the index's results are ranked and returned as usual.\n\n""**Query parameter:** `q` - the search query string (required)."@@ -272,3 +277,18 @@ def init_router(ranker) -> None:if record is None:raise HttpError(404, "No seed crawl for this query.")return record++ @router.get(+ "new-pages/count",+ response=SeedCrawlSummaryResponse,+ auth=JWTAuth(),+ summary="Count of pages added by a seed crawl",+ description="How many pages the seed crawl started by `crawl=true` for this query has "+ "added to the Mwmbl index, so far or in all, without listing them. 404 when there is no "+ "crawl for this query; records are kept for a week.",+ )+ def new_pages_count(request, q: str):+ summary = get_seed_crawl_summary(request.user.id, q)+ if summary is None:+ raise HttpError(404, "No seed crawl for this query.")+ return summarydiff --git a/test/test_combined_search.py b/test/test_combined_search.pyindex 730823c..d8eb629 100644--- a/test/test_combined_search.py+++ b/test/test_combined_search.py@@ -599,3 +599,31 @@ def test_new_pages_only_shows_the_users_own_crawls(client, access_token, fresh_q@pytest.mark.django_dbdef test_new_pages_requires_a_jwt(client, api_key):assert client.get(f"{NEW_PAGES_URL}?q=tokio", HTTP_X_API_KEY=api_key.raw_key).status_code == 401+++def test_new_pages_count_reports_how_many_pages_the_crawl_added(+ client, user, access_token, fresh_quota, redis_cache, crawl_sources+):+ crawl_sources()+ _crawl(client, access_token)+ redis_cache.rpush(f"{seed_crawl._record_key(user.id, 'tokio')}:pages", '{"url": "u", "title": "t", "extract": ""}')++ response = client.get(f"{NEW_PAGES_URL}/count?q=tokio", HTTP_AUTHORIZATION=f"Bearer {access_token}")++ assert response.status_code == 200+ assert response.json()["pages_indexed"] == 1+ assert response.json()["status"] == "crawling"+ assert "pages" not in response.json()+++def test_new_pages_count_is_404_without_a_crawl(client, access_token, redis_cache):+ response = client.get(f"{NEW_PAGES_URL}/count?q=tokio", HTTP_AUTHORIZATION=f"Bearer {access_token}")++ assert response.status_code == 404+++def test_new_pages_count_requires_a_jwt(client, api_key):+ assert client.get(f"{NEW_PAGES_URL}/count?q=tokio", HTTP_X_API_KEY=api_key.raw_key).status_code == 401diff --git a/test/test_openapi.py b/test/test_openapi.pyindex 3f98670..d2f02b6 100644--- a/test/test_openapi.py+++ b/test/test_openapi.py@@ -209,6 +209,7 @@ def test_v2_openapi_spec_generation():"/api/v2/super-search/","/api/v2/combined-search/","/api/v2/combined-search/new-pages",+ "/api/v2/combined-search/new-pages/count",}diff --git a/test/test_seed_crawl.py b/test/test_seed_crawl.pyindex 6920730..7813788 100644--- a/test/test_seed_crawl.py+++ b/test/test_seed_crawl.py@@ -170,6 +170,7 @@ def test_the_record_lists_the_new_pages_once_the_crawl_is_done(fake_web, redis_cassert record["status"] == "done"assert record["finished_at"] is not Noneassert record["pages_crawled"] == 3+ assert record["pages_indexed"] == 3assert [page["url"] for page in record["pages"]] == [SEED,"https://tokio.rs/tutorial",@@ -201,6 +202,16 @@ def test_pages_already_in_the_index_are_not_counted_as_new(fake_web, redis_cacheassert [page["url"] for page in record["pages"]] == ["https://tokio.rs/tutorial"]+def test_the_summary_counts_the_pages_without_listing_them(fake_web, redis_cache, user, index_path):+ _run(user, index_path)++ summary = seed_crawl.get_seed_crawl_summary(user.id, "tokio")++ assert summary["pages_indexed"] == 3+ assert "pages" not in summary++@pytest.mark.django_dbdef test_new_pages_are_added_to_the_users_total(fake_web, redis_cache, user, index_path):_run(user, index_path)