An open source, non-profit web search engine
Count the status class too, and stop calling the trim a privacy control
Daoud Clarke1857e98e6804
diff --git a/mwmbl/traffic.py b/mwmbl/traffic.pyindex f03d926..1f4cc7f 100644--- a/mwmbl/traffic.py+++ b/mwmbl/traffic.py@@ -7,9 +7,10 @@ no request's behaviour changes.Deliberately raw. Classifying a request as a bot or a browser here would fix a taxonomy inthe Redis keys before anyone has looked at the traffic, and a key dimension is not somethingyou can change your mind about later. What is counted is what arrived: requests per-endpoint, split by which of the two headers were present, and requests per verbatim user-agent. Any rule about what a bot looks like then applies when the numbers are read, over-strings we already have, and can be applied differently next week. #412 is where a+endpoint, split by which of the two headers were present and by the status class that came+back, and requests per verbatim user agent. Any rule about what a bot looks like then+applies when the numbers are read, over strings we already have, and can be applied+differently next week. #412 is where aclassification earns its place, once there is data to design it against."""@@ -21,7 +22,7 @@ from typing import Optionalimport redisfrom django.conf import settings-from django.http import HttpRequest+from django.http import HttpRequest, HttpResponsefrom redis.exceptions import RedisErrorfrom mwmbl.utils import utc_today@@ -100,7 +101,20 @@ def header_label(request: HttpRequest) -> str:return "language" if has_language else "neither"-REQUEST_COUNT_KEY = "traffic:req:{date}:{endpoint}:{headers}"+# The status class the client got, and like the header split a description rather than a+# judgement. A request that 4xx'd cost us a URL match and nothing else; one that 2xx'd cost+# us a ranker run. Without this dimension a bot sending malformed queries that never reach+# the index is indistinguishable from a visitor being served, which is the whole question+# #410 is asking. The class rather than the code, because the codes are the view's business+# and this counter should not have an opinion about how many of them there are.+STATUS_LABELS = ["1xx", "2xx", "3xx", "4xx", "5xx"]+++def status_label(response: HttpResponse) -> str:+ return f"{response.status_code // 100}xx"+++REQUEST_COUNT_KEY = "traffic:req:{date}:{endpoint}:{headers}:{status}"USER_AGENT_COUNT_KEY = "traffic:user-agents:{date}"# Thirty days, matching the public daily crawler counters in mwmbl/crawler/stats.py.@@ -109,13 +123,12 @@ USER_AGENT_COUNT_KEY = "traffic:user-agents:{date}"TRAFFIC_EXPIRE_SECONDS = 60 * 60 * 24 * 30# Seven days for the user agents: they are here to be read and argued about, not to be a-# permanent series, and a short window limits what a verbatim string can later be used for.+# permanent series, and a week is long enough to see which clients come back.USER_AGENT_EXPIRE_SECONDS = 60 * 60 * 24 * 7-# How many user agents a day survives, which is both the memory bound on a sorted set whose-# members the caller chooses and the privacy control. What it drops is the tail, and a user-# agent seen once is both most of a browser fingerprint and a lone person; what survives is-# by construction a client somebody runs at volume.+# The memory bound on a sorted set whose members the caller chooses. What it drops is the+# tail, which is also the least interesting part of it: what these strings are here to find+# is a client somebody runs at volume, and one seen once cannot be that.TRACKED_USER_AGENTS = 2000# Trimming on one request in five hundred holds the set within a few hundred rows of the@@ -147,7 +160,7 @@ def get_redis() -> redis.Redis:return _redis-def record_request(request: HttpRequest) -> None:+def record_request(request: HttpRequest, response: HttpResponse) -> None:"""Count one search request. Never raises: a counter that costs a search its results isworse than no counter, which is the rule external_cache already follows."""if not settings.SEARCH_TRAFFIC_COUNTING:@@ -161,12 +174,15 @@ def record_request(request: HttpRequest) -> None:try:pipeline = get_redis().pipeline()- request_key = REQUEST_COUNT_KEY.format(date=today, endpoint=endpoint, headers=header_label(request))+ request_key = REQUEST_COUNT_KEY.format(+ date=today, endpoint=endpoint, headers=header_label(request), status=status_label(response)+ )pipeline.incr(request_key)pipeline.expire(request_key, TRAFFIC_EXPIRE_SECONDS)- # Its own key, not a dimension on the counter above: nothing joins a user agent to- # an address or a query, so no row says a particular person searched for something.+ # Its own key rather than another dimension on the counter above, because the user+ # agent is the one part of this the caller chooses: crossed with endpoint, headers+ # and status it would multiply an unbounded set by two hundred and forty.user_agent_key = USER_AGENT_COUNT_KEY.format(date=today)user_agent = request.headers.get("User-Agent", "")[:MAX_USER_AGENT_LENGTH] or MISSING_USER_AGENTpipeline.zincrby(user_agent_key, 1, user_agent)@@ -179,23 +195,27 @@ def record_request(request: HttpRequest) -> None:logger.warning("Could not record search traffic for %s", endpoint, exc_info=True)-def read_request_counts(redis_client, days: list[date]) -> dict[tuple[date, str, str], int]:- """Request counts for the given days, keyed by (day, endpoint, header label).+def read_request_counts(redis_client, days: list[date]) -> dict[tuple[date, str, str, str], int]:+ """Request counts for the given days, keyed by (day, endpoint, header label, status class).One mget over the known labels rather than a scan: nothing indexes which traffic keysexist, and SCAN on a shared Redis is not something a readout should do. Combinationswith no traffic are absent rather than zero."""coordinates = [- (day, endpoint, headers) for day in days for endpoint in ALL_ENDPOINT_LABELS for headers in HEADER_LABELS+ (day, endpoint, headers, status)+ for day in days+ for endpoint in ALL_ENDPOINT_LABELS+ for headers in HEADER_LABELS+ for status in STATUS_LABELS]counts = redis_client.mget([- REQUEST_COUNT_KEY.format(date=day, endpoint=endpoint, headers=headers)- for day, endpoint, headers in coordinates+ REQUEST_COUNT_KEY.format(date=day, endpoint=endpoint, headers=headers, status=status)+ for day, endpoint, headers, status in coordinates])- return {coordinate: int(count) for coordinate, count in zip(coordinates, counts) if count}+ return {coordinate: int(count) for coordinate, count in zip(coordinates, counts) if count is not None}def read_user_agent_counts(redis_client, days: list[date], limit: int) -> list[tuple[str, int]]:@@ -205,7 +225,7 @@ def read_user_agent_counts(redis_client, days: list[date], limit: int) -> list[t"""pipeline = redis_client.pipeline()for day in days:- pipeline.zrevrange(USER_AGENT_COUNT_KEY.format(date=day), 0, TRACKED_USER_AGENTS, withscores=True)+ pipeline.zrevrange(USER_AGENT_COUNT_KEY.format(date=day), 0, TRACKED_USER_AGENTS - 1, withscores=True)totals: Counter = Counter()for day_counts in pipeline.execute():diff --git a/mwmbl/traffic_middleware.py b/mwmbl/traffic_middleware.pyindex 63a6608..fe102a4 100644--- a/mwmbl/traffic_middleware.py+++ b/mwmbl/traffic_middleware.py@@ -19,9 +19,10 @@ class SearchTrafficMiddleware:def __call__(self, request):response = self.get_response(request)- # After the view, so resolver_match is populated. For the Super Search SSE view this- # is the start of the stream rather than the end of it, which is the right moment to- # count a search - but it means the response has no body to look at yet, and reading- # response.content would raise. Nothing here touches it.- record_request(request)+ # After the view, so resolver_match is populated and the status code is known. For+ # the Super Search SSE view this is the start of the stream rather than the end of+ # it, which is the right moment to count a search - but it means the response has no+ # body to look at yet, and reading response.content would raise. Only the status+ # code is read here, never the body.+ record_request(request, response)return responsediff --git a/test/test_traffic.py b/test/test_traffic.pyindex b60e958..a448918 100644--- a/test/test_traffic.py+++ b/test/test_traffic.py@@ -5,6 +5,7 @@ that reaches for Redis and the CI job runs none. Everything here turns it back oin a fakeredis, the way test_admin_blacklist_status.py does."""+import loggingfrom datetime import timedeltaimport fakeredis@@ -12,9 +13,10 @@ import pytestfrom asgiref.sync import iscoroutinefunction, markcoroutinefunctionfrom django.conf import settingsfrom django.core.handlers.base import BaseHandler-from django.http import StreamingHttpResponse+from django.http import HttpResponseServerError, StreamingHttpResponsefrom django.test import override_settingsfrom redis.exceptions import ConnectionError as RedisConnectionError+from redis.exceptions import TimeoutError as RedisTimeoutErrorfrom mwmbl import trafficfrom mwmbl.traffic_middleware import SearchTrafficMiddleware@@ -54,8 +56,8 @@ def counting(monkeypatch, settings):return client-def count_for(endpoint, headers="user_agent+language"):- key = traffic.REQUEST_COUNT_KEY.format(date=utc_today(), endpoint=endpoint, headers=headers)+def count_for(endpoint, headers="user_agent+language", status="2xx"):+ key = traffic.REQUEST_COUNT_KEY.format(date=utc_today(), endpoint=endpoint, headers=headers, status=status)return traffic.get_redis().get(key)@@ -152,14 +154,50 @@ def test_every_search_route_has_a_label():def test_the_headers_that_arrived_are_counted_and_nothing_is_inferred_from_them(counting, client, headers, expected):client.get("/api/v1/search/", {"s": "python"}, **headers)- assert count_for("v1_search", expected) == "1"+ assert count_for("v1_search", headers=expected) == "1"+++ "request_args,expected_status",+ [+ # A query that reached the ranker, and one that never got past validation.+ (("get", "/api/v1/search/", {"s": "python"}), "2xx"),+ (("get", "/api/v1/search/", {}), "4xx"),+ # Routed, so it is counted, but no view ever ran.+ (("head", "/api/v1/search/", {"s": "python"}), "4xx"),+ ],+)+def test_what_the_request_cost_us_is_counted_separately_from_whether_it_was_served(+ counting, client, request_args, expected_status+):+ """Without this split a bot sending malformed queries looks like a served visitor."""+ method, path, query = request_args+ getattr(client, method)(path, query, **BROWSER_HEADERS)++ assert count_for("v1_search", status=expected_status) == "1"+ others = [status for status in traffic.STATUS_LABELS if status != expected_status]+ assert all(count_for("v1_search", status=status) is None for status in others)+++def test_a_server_error_is_counted_as_one(counting, rf):+ """A view that broke still cost us whatever it did before it broke.++ Django's innermost convert_exception_to_response turns a raised view into a 500 before+ any middleware above it runs, so a response is what this sees either way.+ """+ request = rf.get("/api/v1/search/", {"s": "python"}, **BROWSER_HEADERS)+ request.resolver_match = type("Match", (), {"view_name": "api-v1:search"})()++ SearchTrafficMiddleware(lambda _: HttpResponseServerError())(request)++ assert count_for("v1_search", status="5xx") == "1"def test_the_counters_expire(counting, client):client.get("/api/v1/search/", {"s": "python"}, **BROWSER_HEADERS)requests_key = traffic.REQUEST_COUNT_KEY.format(- date=utc_today(), endpoint="v1_search", headers="user_agent+language"+ date=utc_today(), endpoint="v1_search", headers="user_agent+language", status="2xx")user_agents_key = traffic.USER_AGENT_COUNT_KEY.format(date=utc_today())assert 0 < counting.ttl(requests_key) <= traffic.TRAFFIC_EXPIRE_SECONDS@@ -219,8 +257,8 @@ def test_the_readout_returns_a_count_per_day_endpoint_and_header_combination(coucounts = traffic.read_request_counts(counting, [utc_today()])assert counts == {- (utc_today(), "v1_search", "user_agent+language"): 2,- (utc_today(), "v2_search", "neither"): 1,+ (utc_today(), "v1_search", "user_agent+language", "2xx"): 2,+ (utc_today(), "v2_search", "neither", "2xx"): 1,}@@ -231,19 +269,58 @@ def test_the_readout_survives_a_day_with_no_traffic(counting):assert traffic.read_user_agent_counts(counting, days, 10) == []-def test_a_dead_redis_does_not_change_the_response(client, monkeypatch, settings):[email protected]("failure", [RedisConnectionError("Connection refused"), RedisTimeoutError("Timed out")])+def test_a_dead_redis_does_not_change_the_response(client, monkeypatch, settings, caplog, failure):+ """The failure is raised from execute(), which is the only part of this that does I/O.++ redis.Redis.pipeline() just builds an object, so a client that raises there would be+ testing a path production cannot take.+ """++ class DeadPipeline:+ def __getattr__(self, _name):+ return lambda *args, **kwargs: None++ def execute(self):+ raise failure+class DeadRedis:def pipeline(self):- raise RedisConnectionError("Connection refused")+ return DeadPipeline()with_counting_off = client.get("/api/v1/search/", {"s": "python"}, **BROWSER_HEADERS)settings.SEARCH_TRAFFIC_COUNTING = Truemonkeypatch.setattr(traffic, "_redis", DeadRedis())- with_dead_redis = client.get("/api/v1/search/", {"s": "python"}, **BROWSER_HEADERS)+ with caplog.at_level(logging.WARNING, logger="mwmbl.traffic"):+ with_dead_redis = client.get("/api/v1/search/", {"s": "python"}, **BROWSER_HEADERS)assert with_dead_redis.status_code == with_counting_off.status_code == 200assert with_dead_redis.content == with_counting_off.content+ assert "Could not record search traffic for v1_search" in caplog.text+++def test_the_client_is_built_for_a_counter_rather_than_a_cache(monkeypatch, settings):+ """get_redis() is the one part of this module the other tests never execute, because+ they all inject traffic._redis. Its arguments are what keeps a sick Redis from being a+ slow search, so changing any of them should fail here rather than in production."""+ monkeypatch.setattr(traffic, "_redis", None)+ settings.REDIS_URL = "redis://redis.example:6379"++ pool = traffic.get_redis().connection_pool++ assert (pool.connection_kwargs["host"], pool.connection_kwargs["port"]) == ("redis.example", 6379)+ # Bytes here would make read_user_agent_counts return unusable keys in production.+ assert pool.connection_kwargs["decode_responses"] is True+ assert pool.connection_kwargs["socket_connect_timeout"] == traffic.REDIS_CONNECT_TIMEOUT_SECONDS+ assert pool.connection_kwargs["socket_timeout"] == traffic.REDIS_TIMEOUT_SECONDS+ # And no retries, which is what bounds a stalled Redis at one socket timeout rather than+ # four of them plus redis-py's second-scale backoff. The client default is three retries;+ # what suppresses it is that ConnectionPool.from_url does not forward it to the+ # connection. Constructing a connection is the only way to see the value that results,+ # and does no I/O.+ connection = pool.connection_class(**pool.connection_kwargs)+ assert connection.retry.get_retries() == 0def test_a_streaming_response_is_counted_without_being_consumed(counting, rf):