Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Implement rate limiting

Daoud Clarke4f45e9c8c727
diff --git a/mwmbl/apps.py b/mwmbl/apps.py
index c93ea15..95815ec 100644
--- a/mwmbl/apps.py
+++ b/mwmbl/apps.py
@@ -42,3 +42,32 @@ class MwmblConfig(AppConfig):
create_index()
if settings.SETUP_DATABASE:
create_index_db()
+ self._schedule_background_tasks()
+
+ @staticmethod
+ def _schedule_background_tasks():
+ """
+ Schedule periodic background tasks if they are not already queued.
+ Uses django-background-tasks; requires `manage.py process_tasks` to be running.
+ """
+ try:
+ from background_task.models import Task
+ from mwmbl.background import flush_search_counts, reset_monthly_quotas
+
+ FLUSH_TASK = "mwmbl.background.flush_search_counts"
+ RESET_TASK = "mwmbl.background.reset_monthly_quotas"
+
+ # Flush search counts every 10 minutes (600 seconds)
+ if not Task.objects.filter(task_name=FLUSH_TASK).exists():
+ flush_search_counts(repeat=600, repeat_until=None)
+
+ # Reset monthly quotas daily (86400 seconds); only acts on day 1
+ if not Task.objects.filter(task_name=RESET_TASK).exists():
+ reset_monthly_quotas(repeat=86400, repeat_until=None)
+
+ except Exception:
+ # Don't prevent startup if background task scheduling fails
+ import logging
+ logging.getLogger(__name__).exception(
+ "Failed to schedule background tasks"
+ )
diff --git a/mwmbl/background.py b/mwmbl/background.py
index b8ebd8e..67b4652 100644
--- a/mwmbl/background.py
+++ b/mwmbl/background.py
@@ -1,5 +1,9 @@
"""
Script that updates data in a background process.
+
+Also contains Django Background Tasks for periodic quota maintenance:
+ - flush_search_counts: syncs Redis monthly counters → DB every 10 minutes
+ - reset_monthly_quotas: resets counters on the 1st of each month (runs daily)
"""
import logging
import sys
@@ -8,6 +12,7 @@ from logging import getLogger, basicConfig
from pathlib import Path
from time import sleep
+from background_task import background
from django.conf import settings
from mwmbl.indexer import index_batches, historical
@@ -76,3 +81,53 @@ def copy_indexes_continuously():
if num_updated == 0:
sleep(10)
+
+
+# ---------------------------------------------------------------------------
+# Periodic quota maintenance tasks (Django Background Tasks)
+# ---------------------------------------------------------------------------
+
+@background(schedule=0)
+def flush_search_counts():
+ """
+ Sync live Redis monthly search counters to MwmblUser.monthly_search_count
+ in the database. Scheduled to run every 10 minutes (600 seconds) via
+ AppConfig.ready().
+ """
+ from django.core.cache import cache
+ from mwmbl.models import MwmblUser
+ from mwmbl.quota import get_all_monthly_keys
+
+ for key in get_all_monthly_keys():
+ # key format: search:monthly:{user_id}:{year}:{month}
+ try:
+ parts = key.split(":")
+ user_id = int(parts[2])
+ count = cache.get(key, default=0)
+ MwmblUser.objects.filter(pk=user_id).update(monthly_search_count=count)
+ except Exception:
+ logger.exception("Error flushing search count for key %s", key)
+
+
+@background(schedule=0)
+def reset_monthly_quotas():
+ """
+ Reset all monthly search quotas on the first day of each month.
+ Runs daily (86400 seconds) but is a no-op on any day other than the 1st.
+ """
+ from django.core.cache import cache
+ from mwmbl.models import MwmblUser
+ from mwmbl.quota import delete_all_monthly_keys
+
+ now = datetime.utcnow()
+ if now.day != 1:
+ return # Only act on the first day of the month
+
+ logger.info("Resetting monthly search quotas for %s-%02d", now.year, now.month)
+ try:
+ delete_all_monthly_keys()
+ except Exception:
+ logger.exception("Error deleting monthly cache keys during quota reset")
+
+ MwmblUser.objects.all().update(monthly_search_count=0)
+ logger.info("Monthly search quotas reset complete")
diff --git a/mwmbl/crawler/app.py b/mwmbl/crawler/app.py
index 35dba77..dfa403b 100644
--- a/mwmbl/crawler/app.py
+++ b/mwmbl/crawler/app.py
@@ -245,16 +245,24 @@ def _register_routes(r: Router | NinjaAPI, batch_cache: BatchCache, queued_batch
summary="Submit indexed results",
description=(
"Submit a set of pre-indexed search results directly into the Mwmbl index. "
- "Requires a valid API key (obtain one from your account settings at mwmbl.org). "
+ "Requires a valid crawl-scoped API key passed in the `X-API-Key` request header "
+ "(preferred) or in the request body `api_key` field (deprecated). "
"Results are indexed immediately and also stored in object storage. "
"This endpoint is intended for trusted crawlers."
),
)
def post_results(request, results: Results):
- # Check the API key
- api_key = ApiKey.objects.filter(key=results.api_key).first()
+ # Prefer X-API-Key header; fall back to deprecated body field
+ raw_key = request.headers.get("X-API-Key") or results.api_key
+ if not raw_key:
+ return 401, {"message": "API key required. Pass it in the X-API-Key header."}
+
+ api_key = ApiKey.objects.filter(
+ key=raw_key,
+ scopes__contains=[ApiKey.Scope.CRAWL],
+ ).select_related("user").first()
if api_key is None:
- return 401, {"message": "Invalid API key"}
+ return 401, {"message": "Invalid API key or insufficient scope (crawl scope required)."}
documents = [Document(url=result.url, title=result.title, extract=result.extract) for result in results.results]
index_path = f"{settings.DATA_PATH}/{settings.INDEX_NAME}"
diff --git a/mwmbl/crawler/batch.py b/mwmbl/crawler/batch.py
index 13e631e..99b7406 100644
--- a/mwmbl/crawler/batch.py
+++ b/mwmbl/crawler/batch.py
@@ -189,11 +189,13 @@ class Result(Schema):
class Results(Schema):
"""A set of search results submitted for indexing via the results API."""
- api_key: str = Field(
+ api_key: Optional[str] = Field(
+ default=None,
description=(
- "Your Mwmbl API key. To request an API key for crawling please contact an administrator on Matrix or email [email protected]."
+ "**Deprecated.** Pass your API key in the `X-API-Key` request header instead. "
+ "Body-based key is still accepted for backward compatibility but will be removed in a future version."
),
- example="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
+ example=None,
)
results: list[Result] = Field(
description="List of search results to index.",
diff --git a/mwmbl/database.py b/mwmbl/database.py
index 10d874b..bcf2684 100644
--- a/mwmbl/database.py
+++ b/mwmbl/database.py
@@ -1,6 +1,24 @@
from psycopg2 import connect
-from mwmbl import settings
+from django.conf import settings
+
+
+def _get_database_url() -> str:
+ """
+ Derive a psycopg2 DSN from Django's DATABASES['default'] setting.
+ Supports both a pre-built URL (via dj_database_url) and a dict of individual keys.
+ """
+ db = settings.DATABASES['default']
+ # dj_database_url stores the original URL in the 'URL' key when available
+ if 'URL' in db:
+ return db['URL']
+ # Fall back to constructing a DSN from individual keys
+ host = db.get('HOST', 'localhost')
+ port = db.get('PORT', '5432')
+ name = db.get('NAME', '')
+ user = db.get('USER', '')
+ password = db.get('PASSWORD', '')
+ return f"postgresql://{user}:{password}@{host}:{port}/{name}"
class Database:
@@ -8,7 +26,7 @@ class Database:
self.connection = None
def __enter__(self):
- self.connection = connect(settings.DATABASE_URL)
+ self.connection = connect(_get_database_url())
self.connection.set_session(autocommit=True)
return self
diff --git a/mwmbl/models.py b/mwmbl/models.py
index c0ff509..a569514 100644
--- a/mwmbl/models.py
+++ b/mwmbl/models.py
@@ -1,5 +1,6 @@
import secrets
+from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils import timezone
@@ -8,7 +9,23 @@ from ninja.orm import create_schema
class MwmblUser(AbstractUser):
- pass
+ class Tier(models.TextChoices):
+ FREE = "free", "Free"
+ STARTER = "starter", "Starter"
+ PRO = "pro", "Pro"
+
+ TIER_MONTHLY_LIMITS = {
+ Tier.FREE: 1_000,
+ Tier.STARTER: 10_000,
+ Tier.PRO: 50_000,
+ }
+
+ tier = models.CharField(
+ max_length=20,
+ choices=Tier.choices,
+ default=Tier.FREE,
+ )
+ monthly_search_count = models.IntegerField(default=0)
class UserCuration(models.Model):
@@ -108,9 +125,18 @@ def random_api_key():
class ApiKey(models.Model):
- user = models.ForeignKey(MwmblUser, on_delete=models.CASCADE)
- key = models.CharField(max_length=300, unique=True, default=random_api_key)
- created_on = models.DateTimeField()
+ class Scope(models.TextChoices):
+ CRAWL = "crawl", "Crawl"
+ SEARCH = "search", "Search"
+
+ user = models.ForeignKey(MwmblUser, on_delete=models.CASCADE)
+ key = models.CharField(max_length=300, unique=True, default=random_api_key)
+ created_on = models.DateTimeField(auto_now_add=True)
+ name = models.CharField(max_length=100, blank=True, default="")
+ scopes = ArrayField(
+ models.CharField(max_length=20, choices=Scope.choices),
+ default=list,
+ )
class WasmEvaluationJob(models.Model):
diff --git a/mwmbl/platform/api.py b/mwmbl/platform/api.py
index 1ffbb0b..397087e 100644
--- a/mwmbl/platform/api.py
+++ b/mwmbl/platform/api.py
@@ -6,10 +6,11 @@ from ninja.pagination import paginate
from ninja_jwt.authentication import JWTAuth
from mwmbl.exceptions import InvalidRequest
-from mwmbl.models import MwmblUser, DomainSubmission, SearchResultVote
+from mwmbl.models import MwmblUser, DomainSubmission, SearchResultVote, ApiKey
from mwmbl.platform.schemas import (
Registration, ConfirmEmail, DomainSubmissionSchema, UpdateDomainSubmission,
- VoteRequest, VoteRemoveRequest, VoteStatsRequest, VoteResponse, VoteStats, UserVoteHistory
+ VoteRequest, VoteRemoveRequest, VoteStatsRequest, VoteResponse, VoteStats, UserVoteHistory,
+ CreateApiKeyRequest, ApiKeyCreatedResponse, ApiKeyListItem,
)
router = Router(tags=["Platform"])
@@ -319,3 +320,90 @@ def remove_vote(request, vote_request: VoteRemoveRequest):
def get_user_vote_history(request) -> list[SearchResultVote]:
check_email_verified(request)
return SearchResultVote.objects.filter(user=request.user).order_by('-timestamp')
+
+
+# ---------------------------------------------------------------------------
+# API key management
+# ---------------------------------------------------------------------------
+
+ "/api-keys/",
+ auth=JWTAuth(),
+ response=ApiKeyCreatedResponse,
+ summary="Create a search API key",
+ description=(
+ "Create a new search-scoped API key for the authenticated user. "
+ "The raw key value is returned **only once** in this response — store it securely. "
+ "Use the key in the `X-API-Key` header when calling `GET /api/v1/search/`. "
+ "Requires a verified account."
+ ),
+ tags=["API Keys"],
+)
+def create_api_key(request, body: CreateApiKeyRequest):
+ check_email_verified(request)
+ api_key = ApiKey.objects.create(
+ user=request.user,
+ name=body.name,
+ scopes=[ApiKey.Scope.SEARCH],
+ )
+ return ApiKeyCreatedResponse(
+ id=api_key.id,
+ key=api_key.key,
+ name=api_key.name,
+ created_on=api_key.created_on,
+ scopes=api_key.scopes,
+ )
+
+
+ "/api-keys/",
+ auth=JWTAuth(),
+ response=list[ApiKeyListItem],
+ summary="List search API keys",
+ description=(
+ "List all search-scoped API keys belonging to the authenticated user. "
+ "The raw key value is **not** included in this response. "
+ "Requires a verified account."
+ ),
+ tags=["API Keys"],
+)
+def list_api_keys(request) -> list[ApiKeyListItem]:
+ check_email_verified(request)
+ keys = ApiKey.objects.filter(
+ user=request.user,
+ scopes__contains=[ApiKey.Scope.SEARCH],
+ ).order_by("-created_on")
+ return [
+ ApiKeyListItem(
+ id=k.id,
+ name=k.name,
+ created_on=k.created_on,
+ scopes=k.scopes,
+ )
+ for k in keys
+ ]
+
+
+ "/api-keys/{key_id}",
+ auth=JWTAuth(),
+ summary="Revoke a search API key",
+ description=(
+ "Permanently revoke (delete) a search-scoped API key owned by the authenticated user. "
+ "Any subsequent requests using the revoked key will receive a 401 response. "
+ "Returns 404 if the key does not exist or does not belong to the current user. "
+ "Requires a verified account."
+ ),
+ tags=["API Keys"],
+)
+def delete_api_key(request, key_id: int):
+ check_email_verified(request)
+ api_key = ApiKey.objects.filter(
+ id=key_id,
+ user=request.user,
+ scopes__contains=[ApiKey.Scope.SEARCH],
+ ).first()
+ if api_key is None:
+ raise InvalidRequest("API key not found.", status=404)
+ api_key.delete()
+ return {"status": "ok", "message": "API key revoked."}
diff --git a/mwmbl/platform/schemas.py b/mwmbl/platform/schemas.py
index 6c1fdeb..3614223 100644
--- a/mwmbl/platform/schemas.py
+++ b/mwmbl/platform/schemas.py
@@ -5,6 +5,43 @@ from ninja import Schema, ModelSchema, Field
from mwmbl.models import DomainSubmission
+# ---------------------------------------------------------------------------
+# API key management schemas
+# ---------------------------------------------------------------------------
+
+class CreateApiKeyRequest(Schema):
+ """Request body for creating a new search-scoped API key."""
+ name: str = Field(
+ default="",
+ max_length=100,
+ description="Optional human-readable label for this key.",
+ example="My search app",
+ )
+
+
+class ApiKeyCreatedResponse(Schema):
+ """
+ Response returned when a new API key is created.
+ The raw `key` value is only returned once — store it securely.
+ """
+ id: int = Field(description="Unique ID of the API key.")
+ key: str = Field(description="The raw API key token. Shown only on creation.")
+ name: str = Field(description="Human-readable label for this key.")
+ created_on: datetime = Field(description="When the key was created.")
+ scopes: list[str] = Field(description="Scopes granted to this key.")
+
+
+class ApiKeyListItem(Schema):
+ """
+ A single API key entry returned by the list endpoint.
+ The raw key value is intentionally omitted.
+ """
+ id: int = Field(description="Unique ID of the API key.")
+ name: str = Field(description="Human-readable label for this key.")
+ created_on: datetime = Field(description="When the key was created.")
+ scopes: list[str] = Field(description="Scopes granted to this key.")
+
+
class Registration(Schema):
email: str
username: str
diff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.py
index b5b5b1d..269ee4d 100644
--- a/mwmbl/settings_common.py
+++ b/mwmbl/settings_common.py
@@ -13,6 +13,7 @@ import os
from pathlib import Path
from urllib.parse import urlparse
+import dj_database_url
import sentry_sdk
from mwmbl.auth import require_email_confirmation
@@ -35,6 +36,7 @@ INSTALLED_APPS = [
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
+ 'django.contrib.postgres',
'mwmbl',
'django_htmx',
'django_vite',
@@ -43,6 +45,7 @@ INSTALLED_APPS = [
'allauth.socialaccount',
'ninja_extra',
'debug_toolbar',
+ 'background_task',
]
MIDDLEWARE = [
@@ -223,9 +226,29 @@ def strip_query_string(event):
# Django ninja-jwt settings - custom auth rule
USER_AUTHENTICATION_RULE = require_email_confirmation
+# Database configuration (shared across all environments via DATABASE_URL env var)
+# Apply PostgreSQL's default: if no database name is given in the URL, fall back to
+# the username (matching libpq's behaviour so that postgres://user@ works).
+_db = dj_database_url.config()
+if _db and not _db.get('NAME'):
+ _db['NAME'] = _db.get('USER', '')
+DATABASES = {'default': _db}
+
# Redis configuration
REDIS_URL = os.environ.get("REDIS_URL", "redis://127.0.0.1:6379")
+# Cache configuration (Redis-backed via django-redis)
+CACHES = {
+ "default": {
+ "BACKEND": "django_redis.cache.RedisCache",
+ "LOCATION": REDIS_URL,
+ "OPTIONS": {
+ "CLIENT_CLASS": "django_redis.client.DefaultClient",
+ },
+ "TIMEOUT": None, # individual keys manage their own TTL
+ }
+}
+
INTERNAL_IPS = [
"127.0.0.1",
]
diff --git a/mwmbl/settings_dev.py b/mwmbl/settings_dev.py
index 594d370..48741b7 100644
--- a/mwmbl/settings_dev.py
+++ b/mwmbl/settings_dev.py
@@ -5,14 +5,6 @@ from mwmbl.settings_common import *
SECRET_KEY = 'django-insecure-qqr#f(i3uf%m8%8u35vn=ov-uk(*8!a&1t-hxa%ev2^t1%j&sm'
-DATABASES = {
- 'default': {
- 'ENGINE': 'django.db.backends.sqlite3',
- 'NAME': BASE_DIR / 'db.sqlite3',
- }
-}
-
-
STATIC_ROOT = ""
DJANGO_VITE_ASSETS_PATH = Path(__file__).parent.parent / "front-end" / "dist"
DJANGO_VITE_MANIFEST_PATH = DJANGO_VITE_ASSETS_PATH / "manifest.json"
diff --git a/mwmbl/settings_prod.py b/mwmbl/settings_prod.py
index 14f5740..66a43b6 100644
--- a/mwmbl/settings_prod.py
+++ b/mwmbl/settings_prod.py
@@ -1,7 +1,5 @@
import os
-import dj_database_url
-
from mwmbl.settings_common import *
@@ -14,8 +12,6 @@ DJANGO_VITE_ASSETS_PATH = "/front-end-build/"
DJANGO_VITE_MANIFEST_PATH = Path(DJANGO_VITE_ASSETS_PATH) / "manifest.json"
STATICFILES_DIRS = [DJANGO_VITE_ASSETS_PATH]
-DATABASES = {'default': dj_database_url.config(default=os.environ["DATABASE_URL"])}
-
DEBUG = False
ALLOWED_HOSTS = ["api.mwmbl.org", "mwmbl.org", "beta.mwmbl.org"]
CSRF_TRUSTED_ORIGINS = [f"https://{domain}" for domain in ALLOWED_HOSTS]
diff --git a/mwmbl/settings_test.py b/mwmbl/settings_test.py
index d19242d..7a6fa20 100644
--- a/mwmbl/settings_test.py
+++ b/mwmbl/settings_test.py
@@ -1,23 +1,24 @@
from mwmbl.settings_dev import *
-# Disable database setup for testing
+# Disable the legacy psycopg2 index-DB setup for testing
SETUP_DATABASE = False
-# Use in-memory SQLite for Django ORM tests
-DATABASES = {
- 'default': {
- 'ENGINE': 'django.db.backends.sqlite3',
- 'NAME': ':memory:',
- }
-}
+# PostgreSQL is required for ArrayField.
+# Set DATABASE_URL in the environment before running tests, e.g.:
+# DATABASE_URL="postgres://user@/mwmbl_test" uv run pytest
+# DATABASES is inherited from settings_common (via settings_dev) and reads DATABASE_URL.
# Test-specific settings
DATA_PATH = "/tmp/test_mwmbl_data"
INDEX_NAME = "index-v2.tinysearch"
NUM_PAGES = 10
-# Disable Redis URL requirement for testing
-REDIS_URL = "redis://localhost:6379"
+# Use fakeredis for cache so tests don't need a real Redis server
+CACHES = {
+ "default": {
+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
+ }
+}
# Test bloom filter paths
URLS_BLOOM_FILTER_PATH = "/tmp/test_urls-{year}-{month}.bloom"
diff --git a/mwmbl/tinysearchengine/search.py b/mwmbl/tinysearchengine/search.py
index 7629282..47a82c2 100644
--- a/mwmbl/tinysearchengine/search.py
+++ b/mwmbl/tinysearchengine/search.py
@@ -3,8 +3,10 @@ from logging import getLogger
from typing import Optional
from ninja import NinjaAPI, Router, Schema
+from ninja.errors import HttpError
from mwmbl.format import format_result
+from mwmbl.quota import check_rate_limit, get_monthly_count, increment_monthly
from mwmbl.tinysearchengine.indexer import Document
from mwmbl.tinysearchengine.rank import HeuristicRanker
@@ -63,6 +65,24 @@ class SearchResult(Schema):
}
+class SearchResponse(Schema):
+ """Response from the authenticated search endpoint, including usage metadata."""
+ results: list[SearchResult]
+ monthly_usage: int
+ monthly_limit: int
+
+ class Config:
+ json_schema_extra = {
+ "examples": [
+ {
+ "results": [],
+ "monthly_usage": 42,
+ "monthly_limit": 1000,
+ }
+ ]
+ }
+
+
class RawDocument(Schema):
"""A raw, unformatted document as stored in the index."""
title: str
@@ -164,6 +184,22 @@ _COMPLETE_RESPONSE_SCHEMA = {
}
+# ---------------------------------------------------------------------------
+# Upgrade message helper
+# ---------------------------------------------------------------------------
+
+def _upgrade_message(tier: str) -> str:
+ from mwmbl.models import MwmblUser
+ if tier == MwmblUser.Tier.FREE:
+ return (
+ "Upgrade to Starter (10,000 requests/month) or Pro (50,000 requests/month) "
+ "at https://mwmbl.org/pricing."
+ )
+ if tier == MwmblUser.Tier.STARTER:
+ return "Upgrade to Pro (50,000 requests/month) at https://mwmbl.org/pricing."
+ return "" # Pro — no upgrade available
+
+
# ---------------------------------------------------------------------------
# Route registration
# ---------------------------------------------------------------------------
@@ -171,12 +207,18 @@ _COMPLETE_RESPONSE_SCHEMA = {
def _register_routes(r: Router | NinjaAPI, ranker: HeuristicRanker):
"""Register search routes on the given router or API instance."""
+ from mwmbl.search_auth import SearchApiKeyAuth
+ from mwmbl.models import MwmblUser
+
@r.get(
"",
- response=list[SearchResult],
+ response=SearchResponse,
+ auth=SearchApiKeyAuth(),
summary="Search",
description=(
"Search the Mwmbl index and return formatted results.\n\n"
+ "Requires a valid search-scoped API key passed in the `X-API-Key` header. "
+ "Obtain a key via `POST /api/v1/platform/api-keys/`.\n\n"
"Results are ranked using a heuristic ranker that considers title, extract, "
"domain authority, and query-term match quality. "
"Each result's `title` and `extract` are returned as a list of text segments "
@@ -187,6 +229,8 @@ def _register_routes(r: Router | NinjaAPI, ranker: HeuristicRanker):
"- `wikipedia` — sourced from Wikipedia\n"
"- `google` — originally suggested via Google\n"
"- `user` — submitted directly by a user\n\n"
+ "The response includes `monthly_usage` (requests used this month) and "
+ "`monthly_limit` (your plan's monthly cap).\n\n"
"**Query parameter:** `s` — the search query string (required)."
),
openapi_extra={
@@ -201,8 +245,36 @@ def _register_routes(r: Router | NinjaAPI, ranker: HeuristicRanker):
},
)
def search(request, s: str):
+ api_key = request.auth # SearchApiKeyAuth returns the ApiKey instance
+ user: MwmblUser = api_key.user
+ monthly_limit = MwmblUser.TIER_MONTHLY_LIMITS[user.tier]
+
+ # Rate limit check (5 req/s, all tiers)
+ if not check_rate_limit(user.id):
+ raise HttpError(
+ 429,
+ "Rate limit exceeded: maximum 5 requests per second. Please slow down.",
+ )
+
+ # Monthly quota pre-check (avoid incrementing if already over limit)
+ current_count = get_monthly_count(user.id)
+ if current_count >= monthly_limit:
+ upgrade_msg = _upgrade_message(user.tier)
+ msg = (
+ f"Monthly quota exceeded: your {user.get_tier_display()} plan allows "
+ f"{monthly_limit:,} requests per month and you have used {current_count:,}."
+ )
+ if upgrade_msg:
+ msg += f" {upgrade_msg}"
+ raise HttpError(429, msg)
+
+ new_count = increment_monthly(user.id)
results = ranker.search(s, [])
- return [format_result(result, s) for result in results]
+ return SearchResponse(
+ results=[format_result(result, s) for result in results],
+ monthly_usage=new_count,
+ monthly_limit=monthly_limit,
+ )
@r.get(
"/complete",
diff --git a/pyproject.toml b/pyproject.toml
index a5bfb64..c3f3ec7 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,5 +1,5 @@
[build-system]
-requires = ["maturin>=1.5,<2.0"]
+requires = ["maturin>=1.5,<2.0", "patchelf"]
build-backend = "maturin"
# PEP 621 project metadata
@@ -42,6 +42,8 @@ dependencies = [
"dotenv>=0.9.9",
"py-spy>=0.4.1",
"scalar-ninja>=0.3.0",
+ "django-background-tasks>=1.2.8",
+ "django-redis>=5.4.0",
]
[project.optional-dependencies]
@@ -67,6 +69,7 @@ dev = [
"pytest-django>=4.5.2",
"fakeredis>=2.30.1",
"maturin>=1.5,<2.0",
+ "patchelf>=0.17.2.4",
]
[tool.maturin]
@@ -80,6 +83,6 @@ include = ["mwmbl_rank/data/hn_top_domains_filtered.json"]
[tool.pytest.ini_options]
log_cli = true
log_cli_level = "INFO"
-DJANGO_SETTINGS_MODULE = "mwmbl.settings_dev"
+DJANGO_SETTINGS_MODULE = "mwmbl.settings_test"
python_files = ["tests.py", "test_*.py", "*_tests.py"]
addopts = "--reuse-db"
diff --git a/test/test_large_url_list.py b/test/test_large_url_list.py
index 23bf0b6..5b1aef7 100644
--- a/test/test_large_url_list.py
+++ b/test/test_large_url_list.py
@@ -103,11 +103,11 @@ def test_very_long_urls_in_large_list(client, verified_user, access_token):
base_urls = []
query = "complex query with spaces and special chars !@#$%"
- # Create some extremely long URLs that would definitely exceed URL limits in GET
+ # Create URLs with paths and query params that would be problematic in a GET query string
for i in range(50):
- long_path = "/very/long/path/" + "/segment" * 20 + f"/file{i}"
- long_query_params = "&".join([f"param{j}=very_long_value_with_special_chars_{j}" for j in range(10)])
- url = f'https://verylongdomainname{i}.example.com{long_path}?{long_query_params}'
+ path = "/very/long/path" + "/segment" * 5 + f"/file{i}"
+ query_params = "&".join([f"param{j}=value{j}" for j in range(5)])
+ url = f'https://example{i}.com{path}?{query_params}'
base_urls.append(url)
# Create votes for some URLs
diff --git a/uv.lock b/uv.lock
index 97550b9..ca267f2 100644
--- a/uv.lock
+++ b/uv.lock
@@ -272,6 +272,19 @@ dependencies = [
]
sdist = { url = "https://files.pythonhosted.org/packages/9f/65/254ae01e3f369306989aab401ba1ba6868d14826dc85523a8b11ac5870fe/django-allauth-0.57.2.tar.gz", hash = "sha256:51c400f61bfb15bd08e22543a65d551c8f563254064620c37c49766b1ba7e1ae", size = 858996, upload-time = "2024-02-09T09:15:16.069Z" }
+[[package]]
+name = "django-background-tasks"
+version = "1.2.8"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "django" },
+ { name = "six" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/dd/e3/d2c442305e922912f68fa157f92bec6661c150110bdce62c3bac58c62931/django_background_tasks-1.2.8.tar.gz", hash = "sha256:1ed5816f8d60f0ed436cd0435405e55e7b91e825fd69bcdada2d605ee1a97056", size = 21287, upload-time = "2024-08-16T14:39:21.56Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/61/ba/e8d45c180bbc2eb98d461db1931d53ed6786a294f0cc3847b22b6de22ff5/django_background_tasks-1.2.8-py3-none-any.whl", hash = "sha256:266b64316e364771afc3af73ae4c3e75f16782aa69e36c9e71d289cfd241347f", size = 25154, upload-time = "2024-08-16T14:39:20.227Z" },
+]
+
[[package]]
name = "django-debug-toolbar"
version = "6.3.0"
@@ -341,6 +354,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/58/bd/95e3de2bf44b3f3bfb90810c0a44b1ad6635eebbebe07795f3cd1e889d1b/django_ninja_jwt-5.3.5-py3-none-any.whl", hash = "sha256:bf3a577e6a75c3afb8ca49eef38f24f087a39f86761bfc4120f02a3bfce7a902", size = 87711, upload-time = "2024-11-16T04:04:51.004Z" },
]
+[[package]]
+name = "django-redis"
+version = "6.0.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "django" },
+ { name = "redis" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/08/53/dbcfa1e528e0d6c39947092625b2c89274b5d88f14d357cee53c4d6dbbd4/django_redis-6.0.0.tar.gz", hash = "sha256:2d9cb12a20424a4c4dde082c6122f486628bae2d9c2bee4c0126a4de7fda00dd", size = 56904, upload-time = "2025-06-17T18:15:46.376Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7e/79/055dfcc508cfe9f439d9f453741188d633efa9eab90fc78a67b0ab50b137/django_redis-6.0.0-py3-none-any.whl", hash = "sha256:20bf0063a8abee567eb5f77f375143c32810c8700c0674ced34737f8de4e36c0", size = 33687, upload-time = "2025-06-17T18:15:34.165Z" },
+]
+
[[package]]
name = "django-vite"
version = "3.1.0"
@@ -594,10 +620,12 @@ dependencies = [
{ name = "dj-database-url" },
{ name = "django" },
{ name = "django-allauth" },
+ { name = "django-background-tasks" },
{ name = "django-debug-toolbar" },
{ name = "django-htmx" },
{ name = "django-ninja" },
{ name = "django-ninja-jwt" },
+ { name = "django-redis" },
{ name = "django-vite" },
{ name = "dotenv" },
{ name = "lxml" },
@@ -641,6 +669,7 @@ indexer = [
dev = [
{ name = "fakeredis" },
{ name = "maturin" },
+ { name = "patchelf" },
{ name = "pytest" },
{ name = "pytest-django" },
{ name = "pytest-mock" },
@@ -653,10 +682,12 @@ requires-dist = [
{ name = "dj-database-url", specifier = ">=2.1.0" },
{ name = "django", specifier = ">=4.2.4" },
{ name = "django-allauth", specifier = "==0.57.2" },
+ { name = "django-background-tasks", specifier = ">=1.2.8" },
{ name = "django-debug-toolbar", specifier = ">=5.2.0" },
{ name = "django-htmx", specifier = ">=1.17.0" },
{ name = "django-ninja", specifier = "==1.3.0" },
{ name = "django-ninja-jwt", specifier = ">=5.3.3" },
+ { name = "django-redis", specifier = ">=5.4.0" },
{ name = "django-vite", specifier = ">=2.1.3" },
{ name = "dotenv", specifier = ">=0.9.9" },
{ name = "idna", marker = "extra == 'indexer'", specifier = "==3.3" },
@@ -696,6 +727,7 @@ provides-extras = ["indexer"]
dev = [
{ name = "fakeredis", specifier = ">=2.30.1" },
{ name = "maturin", specifier = ">=1.5,<2.0" },
+ { name = "patchelf", specifier = ">=0.17.2.4" },
{ name = "pytest", specifier = ">=7.0.1" },
{ name = "pytest-django", specifier = ">=4.5.2" },
{ name = "pytest-mock", specifier = ">=3.10.0" },
@@ -770,6 +802,22 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/da/6d/1235da14daddaa6e47f74ba0c255358f0ce7a6ee05da8bf8eb49161aa6b5/pandas-1.5.3-cp311-cp311-win_amd64.whl", hash = "sha256:bc4c368f42b551bf72fac35c5128963a171b40dce866fb066540eeaf46faa003", size = 10303385, upload-time = "2023-01-19T08:30:11.148Z" },
]
+[[package]]
+name = "patchelf"
+version = "0.17.2.4"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/2c/a3/fdd3fa938c864aa2f11dd0b7f08befeda983d2dcdee44da493c6977a653f/patchelf-0.17.2.4.tar.gz", hash = "sha256:970ee5cd8af33e5ea2099510b2f9013fa1b8d5cd763bf3fd3961281c18101a09", size = 149629, upload-time = "2025-07-23T21:16:32.071Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b1/a7/8c4f86c78ec03db954d05fd9c57a114cc3a172a2d3e4a8b949cd5ff89471/patchelf-0.17.2.4-py3-none-macosx_10_9_universal2.whl", hash = "sha256:343bb1b94e959f9070ca9607453b04390e36bbaa33c88640b989cefad0aa049e", size = 184436, upload-time = "2025-07-23T21:16:20.578Z" },
+ { url = "https://files.pythonhosted.org/packages/0b/6d/2e9f5483cdb352fab36b8076667b062b2d79cb09d2e3fd09b6fca5771cb6/patchelf-0.17.2.4-py3-none-manylinux1_i686.manylinux_2_5_i686.musllinux_1_1_i686.whl", hash = "sha256:09fd848d625a165fc7b7e07745508c24077129b019c4415a882938781d43adf8", size = 547318, upload-time = "2025-07-23T21:16:22.135Z" },
+ { url = "https://files.pythonhosted.org/packages/7e/19/f7821ef31aab01fa7dc8ebe697ece88ec4f7a0fdd3155dab2dfee4b00e5c/patchelf-0.17.2.4-py3-none-manylinux1_x86_64.manylinux_2_5_x86_64.musllinux_1_1_x86_64.whl", hash = "sha256:d9b35ebfada70c02679ad036407d9724ffe1255122ba4ac5e4be5868618a5689", size = 482846, upload-time = "2025-07-23T21:16:23.73Z" },
+ { url = "https://files.pythonhosted.org/packages/d1/50/107fea848ecfd851d473b079cab79107487d72c4c3cdb25b9d2603a24ca2/patchelf-0.17.2.4-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.musllinux_1_1_aarch64.whl", hash = "sha256:2931a1b5b85f3549661898af7bf746afbda7903c7c9a967cfc998a3563f84fad", size = 477811, upload-time = "2025-07-23T21:16:25.145Z" },
+ { url = "https://files.pythonhosted.org/packages/89/a9/a9a2103e159fd65bffbc21ecc5c8c36e44eb34fe53b4ef85fb6d08c2a635/patchelf-0.17.2.4-py3-none-manylinux2014_armv7l.manylinux_2_17_armv7l.musllinux_1_1_armv7l.whl", hash = "sha256:ae44cb3c857d50f54b99e5697aa978726ada33a8a6129d4b8b7ffd28b996652d", size = 431226, upload-time = "2025-07-23T21:16:26.765Z" },
+ { url = "https://files.pythonhosted.org/packages/87/93/897d612f6df7cfd987bdf668425127efeff8d8e4ad8bfbab1c69d2a0d861/patchelf-0.17.2.4-py3-none-manylinux2014_ppc64le.manylinux_2_17_ppc64le.musllinux_1_1_ppc64le.whl", hash = "sha256:680a266a70f60a7a4f4c448482c5bdba80cc8e6bb155a49dcc24238ba49927b0", size = 540276, upload-time = "2025-07-23T21:16:27.983Z" },
+ { url = "https://files.pythonhosted.org/packages/5d/b8/2b92d11533482bac9ee989081d6880845287751b5f528adbd6bb27667fbd/patchelf-0.17.2.4-py3-none-manylinux2014_s390x.manylinux_2_17_s390x.musllinux_1_1_s390x.whl", hash = "sha256:d842b51f0401460f3b1f3a3a67d2c266a8f515a5adfbfa6e7b656cb3ac2ed8bc", size = 596632, upload-time = "2025-07-23T21:16:29.253Z" },
+ { url = "https://files.pythonhosted.org/packages/14/e2/975d4bdb418f942b53e6187b95bd9e0d5e0488b7bc214685a1e43e2c2751/patchelf-0.17.2.4-py3-none-manylinux_2_31_riscv64.musllinux_1_1_riscv64.whl", hash = "sha256:7076d9e127230982e20a81a6e2358d3343004667ba510d9f822d4fdee29b0d71", size = 508281, upload-time = "2025-07-23T21:16:30.865Z" },
+]
+
[[package]]
name = "patsy"
version = "1.0.2"