An open source, non-profit web search engine
Bound device registration
Daoud Clarkeb7d3a99fa0a2
diff --git a/mwmbl/crawler/app.py b/mwmbl/crawler/app.pyindex a63a482..dfb107b 100644--- a/mwmbl/crawler/app.py+++ b/mwmbl/crawler/app.py@@ -21,8 +21,9 @@ from mwmbl.crawler.batch import (Results,)from mwmbl.crawler.stats import MwmblStats, StatsManager+from mwmbl.devices import record_devicefrom mwmbl.indexer.index_batches import index_documents-from mwmbl.models import ApiKey, Device+from mwmbl.models import ApiKeyfrom mwmbl.settings import (APPLICATION_KEY,BUCKET_NAME,@@ -261,7 +262,7 @@ def _register_routes(r: Router | NinjaAPI):# 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={})+ record_device(api_key.user, results.device_name)index_path = f"{settings.DATA_PATH}/{settings.INDEX_NAME}"index_documents(documents, index_path)diff --git a/mwmbl/crawler/batch.py b/mwmbl/crawler/batch.pyindex f7d22ef..acb7aed 100644--- a/mwmbl/crawler/batch.py+++ b/mwmbl/crawler/batch.py@@ -196,8 +196,13 @@ class Results(Schema):)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",+ description=(+ "A name identifying the crawler installation, used to list the user's devices. "+ "Truncated to 255 characters. Not the machine hostname - submissions are stored "+ "in public object storage, so the reference crawler reports MWMBL_DEVICE_NAME or "+ "a random id it generates on first run."+ ),+ example="crawler-3f7a1c9e",)diff --git a/mwmbl/devices.py b/mwmbl/devices.pynew file mode 100644index 0000000..483cbff--- /dev/null+++ b/mwmbl/devices.py@@ -0,0 +1,33 @@+"""Recording the crawler devices a user submits results from."""++from mwmbl.models import Device++# Devices are cosmetic: they exist so a user can tell their own crawlers apart in the UI.+# Nothing depends on the list being complete, so a bound is cheap insurance against a+# client that varies the name it reports - whether by accident (a container with a random+# hostname per start) or deliberately - filling the table one row per submission.+MAX_DEVICES_PER_USER = 50++HOSTNAME_MAX_LENGTH = Device._meta.get_field("hostname").max_length+++def record_device(user, hostname: str) -> None:+ """Note that `user` is crawling from `hostname`, creating the device if it is new.++ The name is truncated rather than rejected. It arrives on the same request as the+ crawl results, Django does not validate field lengths on save(), and an over-long name+ would otherwise raise DataError before indexing and lose every page in the submission -+ a heavy price for a label.++ Over the cap, the least recently seen devices are dropped rather than the new one being+ refused, so the list always reflects what the user is actually crawling with now.+ """+ _, created = Device.objects.update_or_create(user=user, hostname=hostname[:HOSTNAME_MAX_LENGTH], defaults={})+ if not created:+ return++ stale_ids = list(+ Device.objects.filter(user=user).order_by("-last_seen").values_list("id", flat=True)[MAX_DEVICES_PER_USER:]+ )+ if stale_ids:+ Device.objects.filter(id__in=stale_ids).delete()diff --git a/test/test_batches_endpoint_removed.py b/test/test_batches_endpoint_removed.pyindex a8e4593..d161119 100644--- a/test/test_batches_endpoint_removed.py+++ b/test/test_batches_endpoint_removed.py@@ -13,6 +13,7 @@ from allauth.account.models import EmailAddressfrom django.contrib.auth import get_user_modelfrom django.test import Client+from mwmbl.devices import HOSTNAME_MAX_LENGTH, MAX_DEVICES_PER_USER, record_devicefrom mwmbl.models import ApiKey, Device, generate_api_keyUser = get_user_model()@@ -165,3 +166,35 @@ def test_request_new_batch_returns_410(api_client):data={"user_id": "a" * 64},)assert response.status_code == 410+++def test_an_over_long_device_name_is_truncated_not_fatal(api_client, crawl_api_key, crawl_user):+ """Device.hostname is varchar(255) and Django does not validate lengths on save(), so+ an unbounded name used to raise DataError before indexing and lose the whole submission."""+ with (+ patch("mwmbl.crawler.app.index_documents") as 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": "x" * 500},+ **api_key_header(crawl_api_key.raw_key),+ )++ assert response.status_code == 200+ index_documents.assert_called_once()+ assert Device.objects.get(user=crawl_user).hostname == "x" * HOSTNAME_MAX_LENGTH+++def test_devices_per_user_are_capped(crawl_user):+ """A client varying the name it reports must not grow the table without bound."""+ for i in range(MAX_DEVICES_PER_USER + 10):+ record_device(crawl_user, f"device-{i}")++ assert Device.objects.filter(user=crawl_user).count() == MAX_DEVICES_PER_USER+ # The most recent survive; the least recently seen are the ones dropped.+ assert Device.objects.filter(user=crawl_user, hostname=f"device-{MAX_DEVICES_PER_USER + 9}").exists()