Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Count distinct search callers per day, to size k-anonymous n-gram counting

Claudeeae23ae1d5df
diff --git a/mwmbl/admin_views.py b/mwmbl/admin_views.py
index 7aa5102..e8b9f20 100644
--- a/mwmbl/admin_views.py
+++ b/mwmbl/admin_views.py
@@ -49,10 +49,14 @@ from mwmbl.membership import TIERS, VOLUNTEER_TIERS, combined_search_monthly_lim
from mwmbl.models import ApiKey, Membership, MwmblUser
from mwmbl.traffic import (
HEADER_LABELS,
+ IDENTITY_ENDPOINTS,
+ IDENTITY_EXPIRE_SECONDS,
STATUS_LABELS,
+ TRACKED_IDENTITIES,
TRACKED_USER_AGENTS,
TRAFFIC_EXPIRE_SECONDS,
USER_AGENT_EXPIRE_SECONDS,
+ read_identity_counts,
read_request_counts,
read_user_agent_counts,
)
@@ -227,6 +231,10 @@ TRAFFIC_MAX_DAYS = TRAFFIC_EXPIRE_SECONDS // SECONDS_PER_DAY
TRAFFIC_DEFAULT_DAYS = 7
TRAFFIC_WINDOW_CHOICES = [1, 7, TRAFFIC_MAX_DAYS]
USER_AGENT_MAX_DAYS = USER_AGENT_EXPIRE_SECONDS // SECONDS_PER_DAY
+IDENTITY_MAX_DAYS = IDENTITY_EXPIRE_SECONDS // SECONDS_PER_DAY
+
+# The share of a day's searches carried by its busiest N callers, at each of these N.
+IDENTITY_SHARE_RANKS = [1, 10, 100, 1000]
# Enough to see the shape of the tail without putting two thousand caller-supplied strings
# through the template.
@@ -309,6 +317,37 @@ def _user_agents(redis_client, days: list[date], counts: dict) -> dict:
}
+def _identities(redis_client, days: list[date], counts: dict) -> dict:
+ """How many distinct callers searched each day, and how concentrated their searches are.
+
+ The shares are of the day's served searches as the request counter has them, so the
+ callers the trim dropped still count towards the total they are a share of.
+ """
+ identity_days = days[:IDENTITY_MAX_DAYS]
+ searches_by_day: Counter = Counter()
+ for coordinate, count in counts.items():
+ if coordinate[ENDPOINT] in IDENTITY_ENDPOINTS and coordinate[STATUS] == "2xx":
+ searches_by_day[coordinate[DAY]] += count
+
+ rows = []
+ for day, (distinct, tracked) in read_identity_counts(redis_client, identity_days).items():
+ searches = searches_by_day[day]
+ rows.append(
+ {
+ "day": day,
+ "searches": searches,
+ "distinct": distinct,
+ "shares": [100 * sum(tracked[:rank]) / searches if searches else 0 for rank in IDENTITY_SHARE_RANKS],
+ }
+ )
+ return {
+ "rows": rows,
+ "ranks": IDENTITY_SHARE_RANKS,
+ "endpoints": sorted(IDENTITY_ENDPOINTS),
+ "tracked_limit": TRACKED_IDENTITIES,
+ }
+
+
def _api_users() -> list[dict]:
"""Users holding a search API key, plus anyone with a Polar usage subscription.
@@ -477,6 +516,7 @@ def search_traffic_view(request):
context["by_headers"] = _requests_by_label(counts, HEADERS, HEADER_LABELS)
context["by_status"] = _requests_by_label(counts, STATUS, STATUS_LABELS)
context["user_agents"] = _user_agents(redis_client, days, counts)
+ context["identities"] = _identities(redis_client, days, counts)
except RedisError as e:
logger.exception("Could not read search traffic from Redis")
context["redis_error"] = str(e)
diff --git a/mwmbl/templates/admin/search_traffic.html b/mwmbl/templates/admin/search_traffic.html
index 4259aca..219aa01 100644
--- a/mwmbl/templates/admin/search_traffic.html
+++ b/mwmbl/templates/admin/search_traffic.html
@@ -140,6 +140,37 @@
{% endif %}
</div>
+ <div class="module">
+ <h2>Distinct callers</h2>
+ <table>
+ <thead>
+ <tr>
+ <th>Day</th><th class="num">Searches</th><th class="num">Distinct callers</th>
+ {% for rank in identities.ranks %}<th class="num">Top {{ rank|intcomma }}</th>{% endfor %}
+ </tr>
+ </thead>
+ <tbody>
+ {% for row in identities.rows %}
+ <tr>
+ <td>{{ row.day }}</td>
+ <td class="num">{{ row.searches|intcomma }}</td>
+ <td class="num">{{ row.distinct|intcomma }}</td>
+ {% for share in row.shares %}<td class="num">{{ share|floatformat:1 }}%</td>{% endfor %}
+ </tr>
+ {% endfor %}
+ </tbody>
+ </table>
+ <p class="note">
+ Served searches on {% for endpoint in identities.endpoints %}<code>{{ endpoint }}</code>{% if not forloop.last %}, {% endif %}{% endfor %},
+ the ones query n-grams would be counted from. A caller is an IPv4 address or an IPv6
+ /64, so a SearxNG instance is one caller however many people use it. The distinct
+ count is a HyperLogLog, accurate to about 1%. The Top columns are the share of the
+ day's searches made by its busiest callers, from the {{ identities.tracked_limit|intcomma }}
+ kept per day. Callers are stored only as a token keyed on the day and the secret key,
+ so no address is kept and a caller cannot be followed from one day to the next.
+ </p>
+ </div>
+
{% endif %}
</div>
diff --git a/mwmbl/traffic.py b/mwmbl/traffic.py
index 23df148..c96e370 100644
--- a/mwmbl/traffic.py
+++ b/mwmbl/traffic.py
@@ -14,6 +14,7 @@ differently next week. #412 is where a
classification earns its place, once there is data to design it against.
"""
+import ipaddress
import random
from collections import Counter
from datetime import date
@@ -23,6 +24,7 @@ from typing import Optional
import redis
from django.conf import settings
from django.http import HttpRequest, HttpResponse
+from django.utils.crypto import salted_hmac
from redis.exceptions import RedisError
from mwmbl.utils import utc_today
@@ -124,6 +126,8 @@ def status_label(response: HttpResponse) -> str:
REQUEST_COUNT_KEY = "traffic:req:{date}:{endpoint}:{headers}:{status}"
USER_AGENT_COUNT_KEY = "traffic:user-agents:{date}"
+IDENTITY_DISTINCT_KEY = "traffic:identities:{date}"
+IDENTITY_COUNT_KEY = "traffic:identity-counts:{date}"
# Thirty days, matching the public daily crawler counters in mwmbl/crawler/stats.py.
# Production Redis runs allkeys-lru (see mwmbl/indexer/blacklist_snapshot.py), so a longer
@@ -147,6 +151,24 @@ USER_AGENT_TRIM_PROBABILITY = 1 / 500
# A missing user agent is a real answer, so it gets a row rather than being dropped.
MISSING_USER_AGENT = "(none)"
+# Who is searching, for sizing a k-anonymous count of query n-grams: how many distinct
+# callers there are in a day, and how much of the traffic the busiest carry. A SearxNG
+# instance forwards no client address, so it is one caller however many people use it.
+# Only searches somebody typed and got an answer to, since those are what n-grams would be
+# counted from: /complete is keystrokes and /raw is mostly the crawler's index sync.
+IDENTITY_ENDPOINTS = {"legacy_search", "v1_search", "v2_search", "ui_search"}
+
+# Kept as long as the user agents and trimmed the same way, for the same reasons.
+IDENTITY_EXPIRE_SECONDS = USER_AGENT_EXPIRE_SECONDS
+TRACKED_IDENTITIES = 2000
+IDENTITY_TRIM_PROBABILITY = 1 / 500
+
+# A household or a small network gets a /64, so one IPv6 caller is the whole prefix.
+IPV6_IDENTITY_PREFIX = 64
+
+# 64 bits: collisions are negligible at a few million callers a day.
+IDENTITY_HASH_LENGTH = 16
+
# Aggressive by design. django-redis is configured with 5 s timeouts, which is fine for a
# cache lookup a view is waiting on and far too slow for a counter: this runs on every
# request, on the one thread asgiref gives the whole sync middleware chain.
@@ -168,6 +190,32 @@ def get_redis() -> redis.Redis:
return _redis
+def client_network(request: HttpRequest) -> str:
+ """The caller's address, or its /64 for IPv6.
+
+ The last X-Forwarded-For entry is the one our nginx saw: dokku sets the header to
+ $remote_addr, and anything earlier in the list would be the client's own say-so.
+ """
+ forwarded_for = request.headers.get("X-Forwarded-For")
+ address = forwarded_for.split(",")[-1].strip() if forwarded_for else request.META["REMOTE_ADDR"]
+ try:
+ ip = ipaddress.ip_address(address)
+ except ValueError:
+ # Still a caller, just not one with a parseable address, and record_request must not raise.
+ return address
+ if ip.version == 6:
+ return str(ipaddress.ip_network(f"{ip}/{IPV6_IDENTITY_PREFIX}", strict=False))
+ return str(ip)
+
+
+def client_identity(request: HttpRequest, day: date) -> str:
+ """An opaque per-day token for the caller. Keyed on the day so tokens cannot be joined
+ across days, and on SECRET_KEY so the address space cannot be hashed to reverse them
+ without it. No address is ever stored."""
+ digest = salted_hmac(f"mwmbl.traffic.identity:{day}", client_network(request), algorithm="sha256")
+ return digest.hexdigest()[:IDENTITY_HASH_LENGTH]
+
+
def record_request(request: HttpRequest, response: HttpResponse) -> None:
"""Count one search request. Never raises: a counter that costs a search its results is
worse than no counter, which is the rule external_cache already follows."""
@@ -198,6 +246,17 @@ def record_request(request: HttpRequest, response: HttpResponse) -> None:
if random.random() < USER_AGENT_TRIM_PROBABILITY:
pipeline.zremrangebyrank(user_agent_key, 0, -TRACKED_USER_AGENTS - 1)
+ if endpoint in IDENTITY_ENDPOINTS and response.status_code // 100 == 2:
+ identity = client_identity(request, today)
+ distinct_key = IDENTITY_DISTINCT_KEY.format(date=today)
+ pipeline.pfadd(distinct_key, identity)
+ pipeline.expire(distinct_key, IDENTITY_EXPIRE_SECONDS)
+ identity_count_key = IDENTITY_COUNT_KEY.format(date=today)
+ pipeline.zincrby(identity_count_key, 1, identity)
+ pipeline.expire(identity_count_key, IDENTITY_EXPIRE_SECONDS)
+ if random.random() < IDENTITY_TRIM_PROBABILITY:
+ pipeline.zremrangebyrank(identity_count_key, 0, -TRACKED_IDENTITIES - 1)
+
pipeline.execute()
except RedisError:
logger.warning("Could not record search traffic for %s", endpoint, exc_info=True)
@@ -240,3 +299,21 @@ def read_user_agent_counts(redis_client, days: list[date], limit: int) -> list[t
for user_agent, count in day_counts:
totals[user_agent] += int(count)
return totals.most_common(limit)
+
+
+def read_identity_counts(redis_client, days: list[date]) -> dict[date, tuple[int, list[int]]]:
+ """Per day, the distinct callers and the tracked callers' search counts, busiest first.
+
+ Per day rather than summed, because the tokens change at midnight and the same caller
+ on two days is two rows that cannot be matched up.
+ """
+ pipeline = redis_client.pipeline()
+ for day in days:
+ pipeline.pfcount(IDENTITY_DISTINCT_KEY.format(date=day))
+ pipeline.zrevrange(IDENTITY_COUNT_KEY.format(date=day), 0, TRACKED_IDENTITIES - 1, withscores=True)
+ results = pipeline.execute()
+
+ readout = {}
+ for day, distinct, tracked in zip(days, results[0::2], results[1::2]):
+ readout[day] = (distinct, [int(count) for _, count in tracked])
+ return readout
diff --git a/test/test_admin_search_traffic.py b/test/test_admin_search_traffic.py
index d5669ad..20e0fb0 100644
--- a/test/test_admin_search_traffic.py
+++ b/test/test_admin_search_traffic.py
@@ -232,3 +232,43 @@ def test_view_renders_when_redis_is_down(staff_client, monkeypatch):
def test_admin_index_links_to_the_traffic_page(staff_client):
assert TRAFFIC_URL in staff_client.get("/admin/").content.decode()
+
+
+def record_callers(redis_client, searches_by_caller, day=None):
+ """Seed the caller keys the way record_request writes them, and the matching requests."""
+ day = day or utc_today()
+ for caller, searches in searches_by_caller.items():
+ redis_client.pfadd(traffic.IDENTITY_DISTINCT_KEY.format(date=day), caller)
+ redis_client.zincrby(traffic.IDENTITY_COUNT_KEY.format(date=day), searches, caller)
+ record(redis_client, "v1_search", day=day, count=sum(searches_by_caller.values()))
+
+
+def test_callers_are_counted_and_their_share_is_of_all_searches(redis_client):
+ record_callers(redis_client, {"instance": 90, "browser": 6, "phone": 4})
+ # Served searches by callers the trim dropped, and traffic that is not a typed search.
+ record(redis_client, "ui_search", count=100)
+ record(redis_client, "v1_raw", count=1000)
+ record(redis_client, "v1_search", status="4xx", count=1000)
+
+ identities = admin_views._identities(traffic.get_redis(), *window(1))
+
+ [today] = identities["rows"]
+ assert today["searches"] == 200
+ assert today["distinct"] == 3
+ assert today["shares"] == [45, 50, 50, 50]
+
+
+def test_the_caller_window_stops_at_the_caller_expiry(redis_client):
+ identities = admin_views._identities(traffic.get_redis(), *window(traffic.TRAFFIC_EXPIRE_SECONDS // 86400))
+
+ assert len(identities["rows"]) == admin_views.IDENTITY_MAX_DAYS
+
+
+def test_view_renders_the_callers(staff_client, redis_client):
+ record_callers(redis_client, {"instance": 1234})
+
+ response = staff_client.get(TRAFFIC_URL)
+
+ assert response.status_code == 200
+ assert "Distinct callers" in response.content.decode()
+ assert response.context["identities"]["rows"][0]["shares"][0] == 100
diff --git a/test/test_traffic.py b/test/test_traffic.py
index a448918..72e76b0 100644
--- a/test/test_traffic.py
+++ b/test/test_traffic.py
@@ -332,3 +332,105 @@ def test_a_streaming_response_is_counted_without_being_consumed(counting, rf):
assert count_for("super_search") == "1"
assert b"".join(response.streaming_content) == b"ab"
+
+
+def identity_counts():
+ key = traffic.IDENTITY_COUNT_KEY.format(date=utc_today())
+ return sorted(int(count) for _, count in traffic.get_redis().zrange(key, 0, -1, withscores=True))
+
+
+def distinct_identities():
+ return traffic.get_redis().pfcount(traffic.IDENTITY_DISTINCT_KEY.format(date=utc_today()))
+
+
+def test_each_address_is_one_caller(counting, client):
+ for address, searches in [("203.0.113.1", 3), ("203.0.113.2", 1)]:
+ for _ in range(searches):
+ client.get("/api/v1/search/", {"s": "python"}, REMOTE_ADDR=address)
+
+ assert distinct_identities() == 2
+ assert identity_counts() == [1, 3]
+
+
+def test_an_ipv6_caller_is_its_whole_64(counting, client):
+ client.get("/api/v1/search/", {"s": "python"}, REMOTE_ADDR="2001:db8:1:2::1")
+ client.get("/api/v1/search/", {"s": "python"}, REMOTE_ADDR="2001:db8:1:2:ffff::9")
+ client.get("/api/v1/search/", {"s": "python"}, REMOTE_ADDR="2001:db8:1:3::1")
+
+ assert identity_counts() == [1, 2]
+
+
+def test_the_caller_is_the_address_our_nginx_saw(rf):
+ """Earlier X-Forwarded-For entries are whatever the client claimed."""
+ request = rf.get("/", HTTP_X_FORWARDED_FOR="10.0.0.1, 198.51.100.7", REMOTE_ADDR="172.17.0.1")
+
+ assert traffic.client_network(request) == "198.51.100.7"
+
+
+def test_an_unparseable_address_is_still_a_caller(rf):
+ request = rf.get("/", HTTP_X_FORWARDED_FOR="unknown")
+
+ assert traffic.client_network(request) == "unknown"
+
+
+def test_no_address_is_stored_and_tokens_change_daily(counting, client, rf):
+ client.get("/api/v1/search/", {"s": "python"}, REMOTE_ADDR="203.0.113.1")
+
+ stored = [
+ str(value)
+ for key in counting.keys("traffic:identity*")
+ if counting.type(key) == "zset"
+ for value in counting.zrange(key, 0, -1)
+ ]
+ assert stored and all("203.0.113" not in value for value in stored)
+ request = rf.get("/", REMOTE_ADDR="203.0.113.1")
+ yesterday = utc_today() - timedelta(days=1)
+ assert traffic.client_identity(request, utc_today()) != traffic.client_identity(request, yesterday)
+
+
+ "path,query,endpoint",
+ [
+ ("/api/v1/search/complete", {"q": "pyth"}, "v1_complete"),
+ ("/api/v1/search/raw", {"s": "python"}, "v1_raw"),
+ ("/app/home/", {"q": "py"}, "ui_keystroke"),
+ ],
+)
+def test_only_typed_searches_are_attributed_to_a_caller(counting, client, path, query, endpoint):
+ client.get(path, query, **BROWSER_HEADERS)
+
+ assert count_for(endpoint) == "1"
+ assert distinct_identities() == 0
+
+
+def test_an_unserved_search_is_not_attributed_to_a_caller(counting, rf):
+ request = rf.get("/api/v1/search/", {"s": "python"})
+ request.resolver_match = type("Match", (), {"view_name": "api-v1:search"})()
+
+ traffic.record_request(request, HttpResponseServerError())
+
+ assert distinct_identities() == 0
+
+
+def test_the_caller_keys_expire_and_are_trimmed(counting, client, monkeypatch):
+ monkeypatch.setattr(traffic, "TRACKED_IDENTITIES", 1)
+ client.get("/api/v1/search/", {"s": "python"}, REMOTE_ADDR="203.0.113.1")
+ monkeypatch.setattr(traffic, "IDENTITY_TRIM_PROBABILITY", 1)
+ client.get("/api/v1/search/", {"s": "python"}, REMOTE_ADDR="203.0.113.1")
+ client.get("/api/v1/search/", {"s": "python"}, REMOTE_ADDR="203.0.113.2")
+
+ assert identity_counts() == [2]
+ for key in [traffic.IDENTITY_DISTINCT_KEY, traffic.IDENTITY_COUNT_KEY]:
+ assert 0 < counting.ttl(key.format(date=utc_today())) <= traffic.IDENTITY_EXPIRE_SECONDS
+
+
+def test_the_readout_gives_distinct_callers_and_counts_per_day(counting, client):
+ yesterday = utc_today() - timedelta(days=1)
+ client.get("/api/v1/search/", {"s": "python"}, REMOTE_ADDR="203.0.113.1")
+ client.get("/api/v1/search/", {"s": "python"}, REMOTE_ADDR="203.0.113.1")
+ client.get("/api/v1/search/", {"s": "python"}, REMOTE_ADDR="203.0.113.2")
+
+ assert traffic.read_identity_counts(counting, [utc_today(), yesterday]) == {
+ utc_today(): (2, [2, 1]),
+ yesterday: (0, []),
+ }