Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Merge branch 'main' into claude/issue-411-traffic-admin

claude[bot]8c6304203eae
diff --cc mwmbl/admin_views.py
index ae38458,3a7471b..ed02f7f
--- a/mwmbl/admin_views.py
+++ b/mwmbl/admin_views.py
@@@ -1,6 -1,9 +1,7 @@@
- """Admin-only status pages: state that lives in Redis, which nothing else can show, and paying users.
-"""Admin-only status pages: the blacklist filtering state in Redis, the weekly index count,
-and paying users.
++"""Admin-only status pages: state that lives in Redis, which nothing else can show, the weekly
++index count, and paying users.
-The blacklist page gives visibility on the blacklist filtering state that lives in Redis.
-
-Retrieval filtering, the snapshot refresh and the index purge are three processes talking
+Blacklist status: retrieval filtering, the snapshot refresh and the index purge are three processes talking
to each other through Redis keys, and none of that state is reachable from the Django
admin: a snapshot that never publishes and a purge queue that never drains look exactly
like everything working, because retrieval quietly falls back to the built-in rules either
@@@ -32,7 -27,7 +33,7 @@@ from django.http import HttpReques
from django.shortcuts import render
from redis import RedisError
- from mwmbl import pricing, quota, traffic
-from mwmbl import count_urls, pricing, quota, search_setup
++from mwmbl import count_urls, pricing, quota, search_setup, traffic
from mwmbl.crawler.stats import BLACKLISTED_REMOVED_COUNT_KEY
from mwmbl.curated_domains import get_curated_domains
from mwmbl.indexer import blacklist_snapshot, purge_queue
@@@ -61,9 -47,12 +62,14 @@@ logger = getLogger(__name__
SNAPSHOT_TASK_NAME = "mwmbl.background.refresh_blacklist_snapshot"
PURGE_TASK_NAME = "mwmbl.background.purge_blacklisted_from_queue"
+ INDEX_COUNT_TASK_NAME = "mwmbl.background.count_index_urls"
+
++SECONDS_PER_DAY = 60 * 60 * 24
+
QUEUE_SAMPLE_SIZE = 50
REMOVED_COUNT_DAYS = 14
+ # As far back as published counts are kept.
-PUBLISHED_INDEX_COUNT_DAYS = count_urls.LONG_EXPIRE_SECONDS // (60 * 60 * 24)
++PUBLISHED_INDEX_COUNT_DAYS = count_urls.LONG_EXPIRE_SECONDS // SECONDS_PER_DAY
def _snapshot_status() -> dict:
@@@ -195,97 -183,24 +200,113 @@@ def blacklist_status_view(request)
return render(request, "admin/blacklist_status.html", context)
- SECONDS_PER_DAY = 60 * 60 * 24
+ @staff_member_required
+ def index_count_view(request):
+ context = {"title": "Index count"}
+ # Rendered with Redis down, like the blacklist page: the scan stalling because Redis
+ # is unreachable is one of the things this page is for.
+ try:
+ redis = count_urls.get_redis()
+ # The index this process already has open, rather than opening it again per request.
+ context["scan"] = count_urls.get_scan_status(redis, search_setup.tiny_index.num_pages)
+ context["published"] = count_urls.get_published_counts(redis, PUBLISHED_INDEX_COUNT_DAYS)
+ except RedisError as e:
+ logger.exception("Could not read the index count from Redis")
+ context["redis_error"] = str(e)
+
+ context["tasks"] = _task_status([INDEX_COUNT_TASK_NAME])
+ return render(request, "admin/index_count.html", context)
+
+# Both windows come from the expiries rather than from taste: a window wider than what Redis
+# keeps shows zeros for days that were never retained, which reads as no traffic rather than
+# as no data, and the two keys are not kept for the same length of time.
+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
+
+# Enough to see the shape of the tail without putting two thousand caller-supplied strings
+# through the template.
+TOP_USER_AGENTS = 100
+
+# Positions in the read_request_counts coordinate, which is (day, endpoint, headers, status).
+DAY, ENDPOINT, HEADERS, STATUS = 0, 1, 2, 3
+
+
+def _traffic_days(request: HttpRequest) -> list[date]:
+ """The days to report on, most recent first, matching _removed_counts above."""
+ try:
+ requested = int(request.GET.get("days", TRAFFIC_DEFAULT_DAYS))
+ except ValueError:
+ requested = TRAFFIC_DEFAULT_DAYS
+ days = min(max(requested, 1), TRAFFIC_MAX_DAYS)
+ today = utc_today()
+ return [today - timedelta(days=offset) for offset in range(days)]
+
+
+def _requests_by_label(counts: dict, dimension: int, labels: list) -> dict:
+ """Requests as endpoints against one dimension of the counter key.
+
+ The three tables on this page - per day, per header combination, per status class - are
+ the same table with a different column, so they are one function called three times.
+ Endpoints with no traffic are left out rather than padding each table with a dozen zero
+ rows, and the busiest comes first.
+ """
+ per_endpoint: dict[str, Counter] = defaultdict(Counter)
+ for coordinate, count in counts.items():
+ per_endpoint[coordinate[ENDPOINT]][coordinate[dimension]] += count
+
+ rows = [
+ {
+ "endpoint": endpoint,
+ "counts": [by_label[label] for label in labels],
+ "total": sum(by_label.values()),
+ }
+ for endpoint, by_label in per_endpoint.items()
+ ]
+ rows.sort(key=lambda row: (-row["total"], row["endpoint"]))
+
+ totals = [sum(by_label[label] for by_label in per_endpoint.values()) for label in labels]
+ return {"labels": labels, "rows": rows, "totals": totals, "total": sum(totals)}
+
+
+def _user_agents(redis_client, days: list[date], counts: dict) -> dict:
+ """The most-seen user agent strings, and how much traffic they do not account for.
+
+ The gap between the requests counted over these days and the sum of the tracked agents is
+ the tail the trim dropped, and the only place a client that randomises its user agent
+ shows up at all.
+ """
+ agent_days = days[:USER_AGENT_MAX_DAYS]
+ # The limit is the window's union, not one day's trim. Each day is already read down to
+ # TRACKED_USER_AGENTS of its own, so a week of browsers routinely sums to more distinct
+ # strings than that; cutting the sum to one day's limit again would put the readout's own
+ # cut into the gap below, where it reads as the trim's.
+ tracked = read_user_agent_counts(redis_client, agent_days, TRACKED_USER_AGENTS * len(agent_days))
+ tracked_total = sum(count for _, count in tracked)
+ agent_day_set = set(agent_days)
+ request_total = sum(count for coordinate, count in counts.items() if coordinate[DAY] in agent_day_set)
+
+ top = [
+ {
+ "user_agent": user_agent,
+ "count": count,
+ "share": 100 * count / tracked_total if tracked_total else 0,
+ }
+ for user_agent, count in tracked[:TOP_USER_AGENTS]
+ ]
+ return {
+ "days": agent_days,
+ "top": top,
+ "tracked": len(tracked),
+ "tracked_limit": TRACKED_USER_AGENTS,
+ "tracked_total": tracked_total,
+ "request_total": request_total,
+ "gap": request_total - tracked_total,
+ }
+
+
def _api_users() -> list[dict]:
"""Users holding a search API key, plus anyone with a Polar usage subscription.
diff --cc mwmbl/templates/admin/mwmbl_index.html
index 6beee1d,db5d247..c8f9811
--- a/mwmbl/templates/admin/mwmbl_index.html
+++ b/mwmbl/templates/admin/mwmbl_index.html
@@@ -14,10 -14,10 +14,14 @@@
<th scope="row"><a href="{% url 'blacklist_status' %}">Blacklist status</a></th>
<td>The published snapshot, the purge queue and the tasks that maintain them.</td>
</tr>
+ <tr>
+ <th scope="row"><a href="{% url 'search_traffic' %}">Search traffic</a></th>
+ <td>Requests per endpoint and per day, and the user agents that sent them.</td>
+ </tr>
+ <tr>
+ <th scope="row"><a href="{% url 'index_count' %}">Index count</a></th>
+ <td>Progress of the weekly scan counting unique URLs in the index, and its results.</td>
+ </tr>
<tr>
<th scope="row"><a href="{% url 'paying_users' %}">Paying users</a></th>
<td>API users and members, their quotas, usage and what they pay, and Seed Search usage.</td>
diff --cc mwmbl/urls.py
index 867809a,a7f6df0..b2bbd81
--- a/mwmbl/urls.py
+++ b/mwmbl/urls.py
@@@ -21,7 -21,7 +21,12 @@@ from django.urls import include, pat
from django.views.generic import RedirectView
import mwmbl.crawler.app as crawler
- from mwmbl.admin_views import blacklist_status_view, paying_users_view, search_traffic_view
-from mwmbl.admin_views import blacklist_status_view, index_count_view, paying_users_view
++from mwmbl.admin_views import (
++ blacklist_status_view,
++ index_count_view,
++ paying_users_view,
++ search_traffic_view,
++)
from mwmbl.api import api as v1_api
from mwmbl.api import register_routers, v2_api
from mwmbl.search_setup import combined_ranker, ranker, tiny_index
@@@ -56,8 -56,8 +61,9 @@@ urlpatterns =
# Before admin.site.urls so the admin catch-all does not shadow it. Access is gated by
# staff_member_required on the view, matching the rest of the admin.
path("admin/blacklist-status/", blacklist_status_view, name="blacklist_status"),
+ path("admin/search-traffic/", search_traffic_view, name="search_traffic"),
path("admin/paying-users/", paying_users_view, name="paying_users"),
+ path("admin/index-count/", index_count_view, name="index_count"),
path("admin/", admin.site.urls),
path("accounts/", include("allauth.urls")),
path("", index, name="index"),