Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Retire POST /crawler/batches/new

Daoud Clarkee0c4a3217fd5
diff --git a/mwmbl/api.py b/mwmbl/api.py
index 54f3f07..63f9143 100644
--- a/mwmbl/api.py
+++ b/mwmbl/api.py
@@ -131,12 +131,12 @@ def v2_invalid_request_handler(request, exc: InvalidRequest):
# Routers are imported after the api instances are created to avoid circular imports,
# and after init functions have been called from urls.py.
-def register_routers(ranker, queued_batches):
+def register_routers(ranker):
"""
Initialise and register all sub-routers on the v1 and v2 APIs.
This is called from urls.py after Django app setup is complete, so that
- dependencies (ranker, queued_batches) are available.
+ dependencies (ranker) are available.
"""
import mwmbl.crawler.app as crawler_module
import mwmbl.tinysearchengine.search as search_module
@@ -147,7 +147,7 @@ def register_routers(ranker, queued_batches):
search_module.init_router(ranker)
search_module.init_v2_router(ranker)
super_search_module.init_router()
- crawler_module.init_router(queued_batches)
+ crawler_module.init_router()
api.add_router("/search/", search_module.router, tags=["Search"])
api.add_router("/crawler/", crawler_module.router, tags=["Crawler"])
diff --git a/mwmbl/crawler/app.py b/mwmbl/crawler/app.py
index 43be995..a63a482 100644
--- a/mwmbl/crawler/app.py
+++ b/mwmbl/crawler/app.py
@@ -4,8 +4,6 @@ import json
import os
from datetime import datetime, timezone
from logging import getLogger
-from queue import Empty
-from typing import Union
from uuid import uuid4
import boto3
@@ -19,14 +17,12 @@ from mwmbl.crawler.batch import (
DatasetRequest,
Error,
HashedDataset,
- NewBatchRequest,
PostResultsResponse,
Results,
)
from mwmbl.crawler.stats import MwmblStats, StatsManager
from mwmbl.indexer.index_batches import index_documents
from mwmbl.models import ApiKey, Device
-from mwmbl.redis_url_queue import RedisURLQueue
from mwmbl.settings import (
APPLICATION_KEY,
BUCKET_NAME,
@@ -81,7 +77,7 @@ def upload_object(model_object: Schema, now: datetime, user_id_hash: str, object
return filename
-def _register_routes(r: Router | NinjaAPI, queued_batches: RedisURLQueue):
+def _register_routes(r: Router | NinjaAPI):
"""Register all crawler routes on the given router or API instance."""
@r.post(
@@ -99,22 +95,19 @@ def _register_routes(r: Router | NinjaAPI, queued_batches: RedisURLQueue):
@r.post(
"/batches/new",
- summary="Request URLs to crawl",
+ summary="Request URLs to crawl (removed)",
description=(
- "Deprecated - crawlers should now determine their own batches.\n\n"
- "Request a new batch of URLs assigned to this crawler for crawling. "
- "Returns a list of URLs that this crawler should fetch and submit back via "
- "`POST /batches/`. Returns an empty list if no URLs are currently queued. "
- "The `user_id` must be exactly 64 characters."
+ "Removed - this handed out URLs to be submitted back via the now-removed "
+ "`POST /batches/`, so it always returns 410 Gone.\n\n"
+ "Crawlers now choose their own URLs and submit them via `POST /results/`."
),
)
- def request_new_batch(request, batch_request: NewBatchRequest) -> list[str]:
- user_id_hash = _get_user_id_hash(batch_request)
- try:
- urls = queued_batches.get_batch(user_id_hash)
- except Empty:
- return []
- return urls
+ def request_new_batch(request):
+ # Not an empty list: get_batch() pops URLs off the queue permanently, so every
+ # legacy crawler still polling this was draining the crawl frontier into results
+ # it could no longer submit. An error tells its operator the client is dead;
+ # an empty list would have left it polling a queue it can never contribute to.
+ raise HttpError(410, "This endpoint has been removed. Crawlers now choose their own URLs.")
@r.get(
"/batches/{date_str}/users/{public_user_id}",
@@ -321,19 +314,19 @@ def _register_routes(r: Router | NinjaAPI, queued_batches: RedisURLQueue):
}
-def init_router(queued_batches: RedisURLQueue):
+def init_router():
"""Initialise the module-level router (called from urls.py for the unified v1 API)."""
- _register_routes(router, queued_batches)
+ _register_routes(router)
-def create_router(queued_batches: RedisURLQueue, version: str) -> NinjaAPI:
+def create_router(version: str) -> NinjaAPI:
"""Create a standalone NinjaAPI for a specific version (used for legacy routes)."""
api = NinjaAPI(urls_namespace=f"crawler-{version}")
- _register_routes(api, queued_batches)
+ _register_routes(api)
return api
-def _get_user_id_hash(batch: Union[NewBatchRequest, DatasetRequest]):
+def _get_user_id_hash(batch: DatasetRequest):
return hashlib.sha3_256(batch.user_id.encode("utf8")).hexdigest()
diff --git a/mwmbl/search_setup.py b/mwmbl/search_setup.py
index 6d62721..812818c 100644
--- a/mwmbl/search_setup.py
+++ b/mwmbl/search_setup.py
@@ -1,32 +1,17 @@
-import os
from pathlib import Path
from django.conf import settings
-from redis import Redis
-from mwmbl.curated_domains import get_curated_domains
from mwmbl.indexer.blacklist_snapshot import get_snapshot_blacklist
-from mwmbl.redis_url_queue import RedisURLQueue
from mwmbl.tinysearchengine.completer import Completer
from mwmbl.tinysearchengine.indexer import Document, TinyIndex
from mwmbl.tinysearchengine.ltr import RustXGBPipeline
from mwmbl.tinysearchengine.ltr_rank import LTRRanker
from mwmbl.tinysearchengine.mmr_rank import MMRRanker
-redis = Redis.from_url(os.environ.get("REDIS_URL", "redis://127.0.0.1:6379"), decode_responses=True)
-
# Pull the blacklist snapshot in at worker startup rather than letting the first query
# pay for the ~11 MB Redis read. Subsequent refreshes happen on a daemon thread.
-snapshot_blacklist = get_snapshot_blacklist()
-
-# Hand the snapshot to the URL queue too. Left to its own default it would build a
-# get_default_blacklist_provider(), and POST /crawler/batches/new calls get_batch() ->
-# is_domain_blacklisted(), which would download and parse the remote blocklists inside a
-# request handler and pin ~156 MB of domain strings in each of the (cpu_count * 2 + 1)
-# gunicorn workers - the cost the snapshot exists to avoid. The processes that legitimately
-# need the full provider (update_urls, update_batches, the standalone crawler in crawl.py,
-# whose Redis has no published snapshot) construct their own queue and are unaffected.
-queued_batches = RedisURLQueue(redis, get_curated_domains, blacklist_provider=snapshot_blacklist)
+get_snapshot_blacklist()
completer = Completer()
index_path = Path(settings.DATA_PATH) / settings.INDEX_NAME
diff --git a/mwmbl/urls.py b/mwmbl/urls.py
index c8c8bf0..4240ed9 100644
--- a/mwmbl/urls.py
+++ b/mwmbl/urls.py
@@ -24,7 +24,7 @@ import mwmbl.crawler.app as crawler
from mwmbl.admin_views import blacklist_status_view
from mwmbl.api import api as v1_api
from mwmbl.api import register_routers, v2_api
-from mwmbl.search_setup import queued_batches, ranker
+from mwmbl.search_setup import ranker
from mwmbl.tinysearchengine import search
from mwmbl.views import (
CurationDetailView,
@@ -45,7 +45,7 @@ from mwmbl.views import (
# Initialise the unified v1 API by registering all sub-routers with their runtime dependencies.
# This must be called before urlpatterns is evaluated.
-register_routers(ranker=ranker, queued_batches=queued_batches)
+register_routers(ranker=ranker)
def trigger_error(request):
@@ -73,7 +73,7 @@ urlpatterns = [
path("app/domains/<str:domain>/", domain_view, name="domain"),
# TODO: these are the old APIs, deprecated and to be removed once all clients have moved over
path("search/", search.create_router(ranker, "0.1").urls),
- path("crawler/", crawler.create_router(queued_batches=queued_batches, version="0.1").urls),
+ path("crawler/", crawler.create_router(version="0.1").urls),
# Unified v1 API — search returns plain list; single docs page at /api/v1/docs
path("api/v1/", v1_api.urls),
# v2 API — search returns object with quota metadata; docs at /api/v2/docs
diff --git a/test/test_batches_endpoint_removed.py b/test/test_batches_endpoint_removed.py
index 12f783c..a8e4593 100644
--- a/test/test_batches_endpoint_removed.py
+++ b/test/test_batches_endpoint_removed.py
@@ -154,3 +154,14 @@ def test_post_dataset_bad_user_id_returns_400_on_the_router_mounted_api(api_clie
},
)
assert response.status_code == 400
+
+
+def test_request_new_batch_returns_410(api_client):
+ """It popped URLs off the queue permanently for clients that can no longer submit them."""
+ response = api_client.post(
+ "/api/v1/crawler/batches/new",
+ content_type="application/json",
+ data={"user_id": "a" * 64},
+ )
+ assert response.status_code == 410