Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Retire the legacy batch endpoint and the counters it fed

Daoud Clarkedaf6b1dc8d72
diff --git a/mwmbl/crawler/app.py b/mwmbl/crawler/app.py
index 6eee5f7..d8c84f8 100644
--- a/mwmbl/crawler/app.py
+++ b/mwmbl/crawler/app.py
@@ -16,7 +16,6 @@ from ninja.errors import HttpError
from redis import Redis
from mwmbl.crawler.batch import (
- Batch,
DatasetRequest,
Error,
HashedBatch,
@@ -37,7 +36,6 @@ from mwmbl.settings import (
ENDPOINT_URL,
FILE_NAME_SUFFIX,
KEY_ID,
- MAX_BATCH_SIZE,
PUBLIC_URL_PREFIX,
PUBLIC_USER_ID_LENGTH,
USER_ID_LENGTH,
@@ -94,71 +92,16 @@ def _register_routes(r: Router | NinjaAPI, batch_cache: BatchCache, queued_batch
@r.post(
"/batches/",
- summary="Submit a crawl batch",
+ summary="Submit a crawl batch (removed)",
description=(
- "Deprecated - the new crawler uses the /results/ endpoint.\n\n"
- "Submit a batch of crawled pages to the Mwmbl index. "
- "Each batch must contain URLs that were previously assigned to this crawler via "
- "`POST /batches/new`. Batches are stored in object storage and queued for indexing. "
- f"Maximum {MAX_BATCH_SIZE} items per batch. "
- "The `user_id` must be exactly 64 characters."
+ "Removed - this endpoint served the old crawler and now always returns 410 Gone.\n\n"
+ "Crawlers should submit crawled pages via `POST /results/` instead."
),
)
- def post_batch(request, batch: Batch):
- if len(batch.items) > MAX_BATCH_SIZE:
- return r.create_response(
- request, f"Batch size too large (maximum {MAX_BATCH_SIZE}), got {len(batch.items)}", status=400
- )
-
- if len(batch.user_id) != USER_ID_LENGTH:
- return r.create_response(request, f"Incorrect user ID length, should be {USER_ID_LENGTH}", status=400)
-
- if len(batch.items) == 0:
- return {
- "status": "ok",
- }
-
- user = _get_user_from_batch(batch)
- if user is None:
- return r.create_response(
- request, "Invalid API key or insufficient scope (crawl scope required).", status=401
- )
-
- user_id_hash = _get_user_id_hash(batch)
-
- urls = [item.url for item in batch.items]
- invalid_urls = queued_batches.check_user_crawled_urls(user_id_hash, urls)
- if invalid_urls:
- return r.create_response(
- request,
- f"The following URLs were not assigned to the user for crawling:"
- f" {invalid_urls}. To suggest a domain to crawl, please visit "
- f"https://mwmbl.org/app/domain-submissions/new",
- status=400,
- )
-
- # Using an approach from https://stackoverflow.com/a/30476450
- now = datetime.now(timezone.utc)
- epoch_time = (now - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
- hashed_batch = HashedBatch(user_id_hash=user_id_hash, timestamp=epoch_time, items=batch.items)
-
- filename = upload_object(hashed_batch, now, user_id_hash, "batch")
-
- global last_batch
- last_batch = hashed_batch
-
- batch_url = f"{PUBLIC_URL_PREFIX}{filename}"
- batch_cache.store(hashed_batch, batch_url)
-
- # Update or create Device records for this batch
- if batch.device_name:
- Device.objects.update_or_create(user=user, hostname=batch.device_name, defaults={})
-
- return {
- "status": "ok",
- "public_user_id": user_id_hash,
- "url": batch_url,
- }
+ def post_batch(request):
+ # HttpError rather than r.create_response: `r` may be a Router, which has no
+ # create_response.
+ raise HttpError(410, "This endpoint has been removed. Submit crawled pages via POST /results/ instead.")
@r.post(
"/batches/new",
@@ -328,6 +271,11 @@ def _register_routes(r: Router | NinjaAPI, batch_cache: BatchCache, queued_batch
if dry_run:
return {"status": "dry-run", "url": None}
+ # Update or create Device records for this submission. This used to happen on the
+ # now-removed /batches/ endpoint, which was the only path that saw a device name.
+ if results.device_name:
+ Device.objects.update_or_create(user=api_key.user, hostname=results.device_name, defaults={})
+
index_path = f"{settings.DATA_PATH}/{settings.INDEX_NAME}"
index_documents(documents, index_path)
filename = upload_object(results, now, api_key.user.username, "results")
@@ -391,24 +339,7 @@ def create_router(batch_cache: BatchCache, queued_batches: RedisURLQueue, versio
return api
-def _get_user_from_batch(batch: Union[Batch, NewBatchRequest, DatasetRequest]):
- """Validate the API key from batch.user_id and return the user."""
- raw_key = batch.user_id
- key_hash = hashlib.sha256(raw_key.encode()).hexdigest()
- api_key = (
- ApiKey.objects.filter(
- key=key_hash,
- scopes__contains=[ApiKey.Scope.CRAWL],
- )
- .select_related("user")
- .first()
- )
- if api_key is None:
- return None
- return api_key.user
-
-
-def _get_user_id_hash(batch: Union[Batch, NewBatchRequest, DatasetRequest]):
+def _get_user_id_hash(batch: Union[NewBatchRequest, DatasetRequest]):
return hashlib.sha3_256(batch.user_id.encode("utf8")).hexdigest()
diff --git a/mwmbl/crawler/batch.py b/mwmbl/crawler/batch.py
index 858fb93..fbd9d3b 100644
--- a/mwmbl/crawler/batch.py
+++ b/mwmbl/crawler/batch.py
@@ -213,6 +213,11 @@ class Results(Schema):
description="Version string of the crawler that produced these results.",
example="1.2.0",
)
+ device_name: Optional[str] = Field(
+ default=None,
+ description="The crawler's device name (platform.uname().node), used to track the user's devices.",
+ example="my-device",
+ )
class PostResultsResponse(Schema):
diff --git a/mwmbl/crawler/stats.py b/mwmbl/crawler/stats.py
index b71ec2e..5ecc77d 100644
--- a/mwmbl/crawler/stats.py
+++ b/mwmbl/crawler/stats.py
@@ -10,10 +10,7 @@ from mwmbl.utils import utc_today
logger = getLogger(__name__)
-URL_DATE_COUNT_KEY = "url-count-{date}"
-URL_HOUR_COUNT_KEY = "url-count-hour-{hour}"
USERS_KEY = "users-{date}"
-USER_COUNT_KEY = "user-count-{date}"
HOST_COUNT_KEY = "host-count-{date}"
HOST_COUNT_ALL_KEY = "host-count-all-{date}"
HOST_COUNT_LINK_KEY = "host-count-link-{date}"
@@ -28,16 +25,6 @@ SHORT_EXPIRE_SECONDS = 60 * 60 * 24
LONG_EXPIRE_SECONDS = 60 * 60 * 24 * 30
-def hour_count_key(date_time: datetime) -> str:
- """Key naming the hour a crawl happened in, e.g. ``url-count-hour-2026-09-08 13:00:00``.
-
- Formatted rather than built from a truncated datetime so that the key does not depend
- on whether ``date_time`` is aware: ``str()`` of an aware datetime carries a ``+00:00``
- suffix, which would split the reader in :meth:`StatsManager.get_stats` and zero the hourly chart.
- """
- return URL_HOUR_COUNT_KEY.format(hour=date_time.strftime("%Y-%m-%d %H:00:00"))
-
-
class DomainStats(BaseModel):
domain_name: str
num_crawled: int
@@ -97,11 +84,7 @@ class StatsManager:
blacklisted_results_removed_daily = {}
for i in range(29, -1, -1):
date_i = date - timedelta(days=i)
- url_count_key = URL_DATE_COUNT_KEY.format(date=date_i)
- url_count = self.redis.get(url_count_key)
- if url_count is None:
- url_count = 0
- urls_crawled_daily[str(date_i)] = url_count
+ urls_crawled_daily[str(date_i)] = 0
user_day_count_key = USERS_KEY.format(date=date_i)
user_day_count = self.redis.scard(user_day_count_key)
@@ -131,21 +114,10 @@ class StatsManager:
blacklisted_removed_count = 0
blacklisted_results_removed_daily[str(date_i)] = blacklisted_removed_count
- hour_counts = []
- for i in range(date_time.hour + 1):
- hour_key = hour_count_key(date_time.replace(hour=i))
- hour_count = self.redis.get(hour_key)
- if hour_count is None:
- hour_count = 0
- hour_counts.append(hour_count)
-
- user_count_key = USER_COUNT_KEY.format(date=date_time.date())
- user_counts = self.redis.zrevrange(user_count_key, 0, 100, withscores=True)
-
- host_key = HOST_COUNT_KEY.format(date=date_time.date())
- host_counts = self.redis.zrevrange(host_key, 0, 100, withscores=True)
-
- urls_crawled_today = list(urls_crawled_daily.values())[-1]
+ hour_counts = [0] * (date_time.hour + 1)
+ user_counts: list[tuple[str, int]] = []
+ host_counts: list[tuple[str, int]] = []
+ urls_crawled_today = 0
index_stats = get_counts()
user_results_count_key = USER_RESULTS_COUNT_KEY.format(date=date_time.date())
diff --git a/test/test_batches_endpoint_removed.py b/test/test_batches_endpoint_removed.py
new file mode 100644
index 0000000..f2356e5
--- /dev/null
+++ b/test/test_batches_endpoint_removed.py
@@ -0,0 +1,130 @@
+"""
+Tests for the removal of the legacy crawl-batch submission endpoint.
+
+`POST /crawler/batches/` served the old crawler and now returns 410 Gone. Device
+registration used to hang off it, so it has moved to `POST /crawler/results` - the
+only remaining submission path, and the one the devices page is built on.
+"""
+
+from unittest.mock import patch
+
+import pytest
+from allauth.account.models import EmailAddress
+from django.contrib.auth import get_user_model
+from django.test import Client
+
+from mwmbl.models import ApiKey, Device, generate_api_key
+
+User = get_user_model()
+
+
+def api_client():
+ return Client()
+
+
+def crawl_user(db):
+ user = User.objects.create_user(
+ username="crawluser",
+ password="testpass123",
+ )
+ EmailAddress.objects.create(user=user, email=user.email, primary=True, verified=True)
+ return user
+
+
+def crawl_api_key(crawl_user):
+ raw_key, key_hash = generate_api_key()
+ obj = ApiKey.objects.create(
+ user=crawl_user,
+ key=key_hash,
+ name="Test crawl key",
+ scopes=[ApiKey.Scope.CRAWL],
+ )
+ obj.raw_key = raw_key
+ return obj
+
+
+def api_key_header(raw_key):
+ return {"HTTP_X_API_KEY": raw_key}
+
+
+def test_post_batch_returns_410(api_client):
+ response = api_client.post(
+ "/api/v1/crawler/batches/",
+ content_type="application/json",
+ data={"user_id": "a" * 64, "items": [], "device_name": "my-device"},
+ )
+ assert response.status_code == 410
+
+
+def test_post_batch_returns_410_for_a_body_it_can_no_longer_parse(api_client):
+ """The endpoint no longer binds the legacy Batch schema, so an old or malformed
+ payload must still get 410 rather than a validation error."""
+ response = api_client.post(
+ "/api/v1/crawler/batches/",
+ content_type="application/json",
+ data={"nonsense": True},
+ )
+ assert response.status_code == 410
+
+
+def test_post_results_registers_the_device(api_client, crawl_api_key, crawl_user):
+ """Device registration moved here from the removed /batches/ endpoint."""
+ with (
+ patch("mwmbl.crawler.app.index_documents"),
+ patch("mwmbl.crawler.app.upload_object", return_value="fake/path.json.gz"),
+ patch("mwmbl.crawler.app.stats_manager"),
+ ):
+ response = api_client.post(
+ "/api/v1/crawler/results",
+ content_type="application/json",
+ data={"results": [], "device_name": "my-device"},
+ **api_key_header(crawl_api_key.raw_key),
+ )
+
+ assert response.status_code == 200
+ assert Device.objects.filter(user=crawl_user, hostname="my-device").exists()
+
+
+def test_post_results_without_a_device_name_registers_nothing(api_client, crawl_api_key, crawl_user):
+ with (
+ patch("mwmbl.crawler.app.index_documents"),
+ patch("mwmbl.crawler.app.upload_object", return_value="fake/path.json.gz"),
+ patch("mwmbl.crawler.app.stats_manager"),
+ ):
+ response = api_client.post(
+ "/api/v1/crawler/results",
+ content_type="application/json",
+ data={"results": []},
+ **api_key_header(crawl_api_key.raw_key),
+ )
+
+ assert response.status_code == 200
+ assert not Device.objects.filter(user=crawl_user).exists()
+
+
+def test_post_results_is_idempotent_for_a_repeated_device(api_client, crawl_api_key, crawl_user):
+ """unique_together on (user, hostname) means a second submission must update, not duplicate."""
+ with (
+ patch("mwmbl.crawler.app.index_documents"),
+ patch("mwmbl.crawler.app.upload_object", return_value="fake/path.json.gz"),
+ patch("mwmbl.crawler.app.stats_manager"),
+ ):
+ for _ in range(2):
+ response = api_client.post(
+ "/api/v1/crawler/results",
+ content_type="application/json",
+ data={"results": [], "device_name": "my-device"},
+ **api_key_header(crawl_api_key.raw_key),
+ )
+ assert response.status_code == 200
+
+ assert Device.objects.filter(user=crawl_user, hostname="my-device").count() == 1