An open source, non-profit web search engine
Merge branch 'main' into claude/issue-411-traffic-admin
claude[bot]4474abea7794
diff --cc mwmbl/admin_views.pyindex 67aaa7a,a000a5f..c67daea--- a/mwmbl/admin_views.py+++ b/mwmbl/admin_views.py@@@ -1,6 -1,8 +1,6 @@@- """Admin-only visibility on state that lives in Redis, which nothing else can show.-"""Admin-only status pages: the blacklist filtering state in Redis, and paying users.++"""Admin-only status pages: state that lives in Redis, which nothing else can show, 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 talkingto each other through Redis keys, and none of that state is reachable from the Djangoadmin: a snapshot that never publishes and a purge queue that never drains look exactlylike everything working, because retrieval quietly falls back to the built-in rules either@@@ -26,11 -21,12 +26,13 @@@ from logging import getLoggefrom background_task.models import CompletedTask, Taskfrom django.conf import settingsfrom django.contrib.admin.views.decorators import staff_member_required+ from django.core.cache import cache+ from django.db.models import F, OuterRef, Q, Subquery+from django.http import HttpRequestfrom django.shortcuts import renderfrom redis import RedisError- from mwmbl import traffic-from mwmbl import pricing, quota++from mwmbl import pricing, quota, trafficfrom mwmbl.crawler.stats import BLACKLISTED_REMOVED_COUNT_KEYfrom mwmbl.curated_domains import get_curated_domainsfrom mwmbl.indexer import blacklist_snapshot, purge_queue@@@ -41,15 -37,8 +43,17 @@@ from mwmbl.indexer.blacklist_snapshot iget_snapshot_blacklist,)from mwmbl.indexer.purge_queue import MAX_QUEUE_SIZE, PURGE_QUEUE_KEY, peek_purge_queue+ from mwmbl.membership import TIERS, combined_search_monthly_limit+ from mwmbl.models import ApiKey, Membership, MwmblUser+from mwmbl.traffic import (+ HEADER_LABELS,+ STATUS_LABELS,+ TRACKED_USER_AGENTS,+ TRAFFIC_EXPIRE_SECONDS,+ USER_AGENT_EXPIRE_SECONDS,+ read_request_counts,+ read_user_agent_counts,+)from mwmbl.utils import utc_todaylogger = getLogger(__name__)@@@ -191,118 -180,157 +195,274 @@@ def blacklist_status_view(request)return render(request, "admin/blacklist_status.html", context)+SECONDS_PER_DAY = 60 * 60 * 24++# 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]+ tracked = read_user_agent_counts(redis_client, agent_days, TRACKED_USER_AGENTS)+ tracked_total = sum(count for _, count in tracked)+ request_total = sum(count for coordinate, count in counts.items() if coordinate[DAY] in set(agent_days))++ 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.++ Subscribers are included even without a key, because they are still being billed for+ the month's usage until it is reported. A subscriber at $0 has given card details but+ is still hard-capped at the free allowance.+ """+ last_key_use = (+ ApiKey.objects.filter(user=OuterRef("pk"), scopes__contains=[ApiKey.Scope.SEARCH])+ .order_by(F("last_used").desc(nulls_last=True))+ .values("last_used")[:1]+ )+ users = list(+ MwmblUser.objects.filter(+ Q(apikey__scopes__contains=[ApiKey.Scope.SEARCH]) | Q(billing__polar_subscription_id__gt="")+ )+ .distinct()+ .select_related("billing")+ .annotate(last_key_use=Subquery(last_key_use))+ )+ # One round trip for every counter rather than one per row.+ usage_keys = {user.id: quota._monthly_key(user.id) for user in users}+ usage_by_key = cache.get_many(list(usage_keys.values()))++ api_users = []+ for user in users:+ usage = usage_by_key.get(usage_keys[user.id], 0)+ billing = getattr(user, "billing", None)+ subscribed = billing is not None and billing.polar_subscription_id != ""+ spend_cents = billing.max_monthly_spend_cents if billing else 0+ if not subscribed:+ status = "no subscription"+ elif spend_cents == 0:+ status = "free"+ elif billing.cancel_at_period_end:+ status = "canceling"+ else:+ status = "active"+ api_users.append(+ {+ "user": user,+ "status": status,+ "subscribed": subscribed,+ "max_monthly_spend_cents": spend_cents,+ "monthly_cap": pricing.effective_monthly_request_cap(spend_cents),+ "usage": usage,+ "estimated_cost_cents": pricing.estimated_cost_cents(usage),+ "last_key_use": user.last_key_use,+ "current_period_end": billing.current_period_end if billing else None,+ "polar_customer_id": billing.polar_customer_id if billing else "",+ }+ )+ api_users.sort(key=lambda api_user: (api_user["estimated_cost_cents"], api_user["usage"]), reverse=True)+ return api_users+++ def _members() -> list[dict]:+ price_by_tier = {tier_info.tier.value: tier_info.monthly_price_pence for tier_info in TIERS}+ memberships = list(Membership.objects.select_related("user").order_by("-started"))+ usage_keys = {+ membership.user_id: quota._combined_search_monthly_key(membership.user_id) for membership in memberships+ }+ usage_by_key = cache.get_many(list(usage_keys.values()))++ return [+ {+ "user": membership.user,+ "tier": membership.get_tier_display(),+ "monthly_price_pence": price_by_tier[membership.tier],+ "combined_search_limit": combined_search_monthly_limit(membership.tier),+ "combined_search_usage": usage_by_key.get(usage_keys[membership.user_id], 0),+ "current_period_end": membership.current_period_end,+ "cancel_at_period_end": membership.cancel_at_period_end,+ "started": membership.started,+ }+ for membership in memberships+ ]+++ def _tier_summary(members: list[dict]) -> list[dict]:+ summary = []+ for tier_info in TIERS:+ tier_members = [member for member in members if member["tier"] == tier_info.tier.label]+ summary.append(+ {+ "tier": tier_info.tier.label,+ "count": len(tier_members),+ "monthly_price_pence": tier_info.monthly_price_pence,+ "monthly_revenue_pence": len(tier_members) * tier_info.monthly_price_pence,+ }+ )+ return summary+++ SEED_SEARCH_TOP_USERS = 25+++ def _seed_search_stats() -> dict:+ """This month's Seed Search (Combined Search) usage by signed-in users, by tier.++ Combined Search refuses API keys, so every counter belongs to a signed-in web user.+ "free" is everyone without a membership, matching COMBINED_SEARCH_MONTHLY_LIMITS.+ """+ counts = quota.get_all_monthly_combined_search_counts()+ users_by_id = MwmblUser.objects.in_bulk(list(counts))+ # Counters outlive deleted accounts until they expire, so skip users that no longer exist.+ counts = {user_id: count for user_id, count in counts.items() if user_id in users_by_id}+ tier_by_user = dict(Membership.objects.filter(user_id__in=counts).values_list("user_id", "tier"))++ tier_names = ["free"] + [tier_info.tier.value for tier_info in TIERS]+ by_tier = {tier: {"tier": tier, "users": 0, "queries": 0, "at_limit": 0} for tier in tier_names}+ rows = []+ for user_id, count in counts.items():+ tier = tier_by_user.get(user_id, "free")+ limit = combined_search_monthly_limit(tier)+ tier_stats = by_tier[tier]+ tier_stats["users"] += 1+ tier_stats["queries"] += count+ tier_stats["at_limit"] += count >= limit+ rows.append({"user": users_by_id[user_id], "tier": tier, "usage": count, "limit": limit})++ for tier_stats in by_tier.values():+ tier_stats["limit"] = combined_search_monthly_limit(tier_stats["tier"])++ rows.sort(key=lambda row: row["usage"], reverse=True)+ return {+ "users": len(counts),+ "queries": sum(counts.values()),+ "at_limit": sum(tier_stats["at_limit"] for tier_stats in by_tier.values()),+ "by_tier": list(by_tier.values()),+ "top_users": rows[:SEED_SEARCH_TOP_USERS],+ }+++@staff_member_required+def search_traffic_view(request):+ days = _traffic_days(request)+ context = {+ "title": "Search traffic",+ "days": days,+ "window_choices": TRAFFIC_WINDOW_CHOICES,+ "max_days": TRAFFIC_MAX_DAYS,+ "user_agent_max_days": USER_AGENT_MAX_DAYS,+ "top_user_agents": TOP_USER_AGENTS,+ # Off means the page is telling the truth about Redis and nothing about the traffic,+ # which is not something a reader should have to infer from empty rows.+ "counting_enabled": settings.SEARCH_TRAFFIC_COUNTING,+ }++ # As on the blacklist page: everything below this line comes from Redis, and a page about+ # what Redis holds has to render when Redis is down.+ try:+ redis_client = traffic.get_redis()+ counts = read_request_counts(redis_client, days)+ context["by_day"] = _requests_by_label(counts, DAY, days)+ 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)+ except RedisError as e:+ logger.exception("Could not read search traffic from Redis")+ context["redis_error"] = str(e)++ return render(request, "admin/search_traffic.html", context)+++++ @staff_member_required+ def paying_users_view(request):+ api_users = _api_users()+ members = _members()+ tier_summary = _tier_summary(members)+ # Members still paying out the current period after cancelling are counted: they have paid.+ context = {+ "title": "Paying users",+ "api_users": api_users,+ "api_subscribed_count": sum(1 for api_user in api_users if api_user["subscribed"]),+ "api_billed_count": sum(1 for api_user in api_users if api_user["estimated_cost_cents"] > 0),+ "api_estimated_revenue_cents": sum(api_user["estimated_cost_cents"] for api_user in api_users),+ "members": members,+ "tier_summary": tier_summary,+ "seed_search": _seed_search_stats(),+ "membership_revenue_pence": sum(tier["monthly_revenue_pence"] for tier in tier_summary),+ "free_keyed_monthly_limit": pricing.FREE_KEYED_MONTHLY_LIMIT,+ "price_per_1000_queries_cents": pricing.PRICE_PER_1000_QUERIES_CENTS,+ }+ return render(request, "admin/paying_users.html", context)diff --cc mwmbl/templates/admin/mwmbl_index.htmlindex f7dc871,f4b3fa2..6beee1d--- 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 'paying_users' %}">Paying users</a></th>+ <td>API users and members, their quotas, usage and what they pay, and Seed Search usage.</td>+ </tr></table></div>{% endblock %}diff --cc mwmbl/urls.pyindex 1974168,2fd16b0..867809a--- a/mwmbl/urls.py+++ b/mwmbl/urls.py@@@ -21,10 -21,10 +21,10 @@@ from django.urls import include, patfrom django.views.generic import RedirectViewimport mwmbl.crawler.app as crawler- from mwmbl.admin_views import blacklist_status_view, search_traffic_view-from mwmbl.admin_views import blacklist_status_view, paying_users_view++from mwmbl.admin_views import blacklist_status_view, paying_users_view, search_traffic_viewfrom mwmbl.api import api as v1_apifrom mwmbl.api import register_routers, v2_api- from mwmbl.search_setup import ranker+ from mwmbl.search_setup import combined_ranker, ranker, tiny_indexfrom mwmbl.tinysearchengine import searchfrom mwmbl.views import (CurationDetailView,@@@ -56,7 -56,7 +56,8 @@@ 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/", admin.site.urls),path("accounts/", include("allauth.urls")),path("", index, name="index"),