An open source, non-profit web search engine
Revert behaviour for /search endpoint in v1 and introduce v2 with new behaviour
Daoud Clarke6d5375b1d1fa
diff --git a/mwmbl/api.py b/mwmbl/api.pyindex b56fafe..f4ca633 100644--- a/mwmbl/api.py+++ b/mwmbl/api.py@@ -1,16 +1,18 @@"""-Unified Mwmbl API (v1).+Unified Mwmbl API (v1 and v2).-All v1 endpoints are mounted here under a single NinjaExtraAPI instance so that-a single Swagger/OpenAPI docs page is available at /api/v1/docs.+v1 endpoints are mounted under /api/v1/ — search returns a plain list of results.+v2 endpoints are mounted under /api/v2/ — search returns an object with quota metadata.-Sub-routers:- /api/v1/search/ — full-text search and autocomplete+Sub-routers (v1):+ /api/v1/search/ — full-text search and autocomplete (returns list)/api/v1/crawler/ — crawler batch submission and retrieval/api/v1/platform/ — user accounts, domain submissions, voting- /api/v1/evaluate/ — WASM ranking function evaluation-JWT token endpoints (from NinjaJWTDefaultController) are also registered here,+Sub-routers (v2):+ /api/v2/search/ — full-text search with optional API-key auth and quota info++JWT token endpoints (from NinjaJWTDefaultController) are registered on v1,typically at /api/v1/platform/token/pair, /api/v1/platform/token/refresh, etc."""@@ -97,11 +99,39 @@ def invalid_request_handler(request, exc: InvalidRequest):)-# Routers are imported after the api instance is created to avoid circular imports,+v2_api = NinjaExtraAPI(+ title="Mwmbl API v2",+ version="2.0.0",+ description=(+ "Mwmbl search API v2. "+ "The search endpoint returns an object with `results`, `monthly_usage`, and "+ "`monthly_limit` fields. Pass a search-scoped API key in the `X-API-Key` header "+ "to enable quota tracking. Obtain a key via `POST /api/v1/platform/api-keys/`."+ ),+ urls_namespace="api-v2",+ docs=ScalarViewer(openapi_url="/api/v2/openapi.json", agent=AgentConfig(disabled=True)),+ openapi_extra={+ "tags": [+ {"name": "Search"},+ ]+ },+)+++@v2_api.exception_handler(InvalidRequest)+def v2_invalid_request_handler(request, exc: InvalidRequest):+ return v2_api.create_response(+ request,+ {"status": "error", "message": exc.message},+ status=exc.status,+ )+++# Routers are imported after the api instances are created to avoid circular imports,# and after init functions have been called from urls.py.def register_routers(ranker, batch_cache, queued_batches):"""- Initialise and register all sub-routers on the unified API.+ Initialise and register all sub-routers on the v1 and v2 APIs.This is called from urls.py after Django app setup is complete, so thatdependencies (ranker, batch_cache, queued_batches) are available.@@ -109,15 +139,14 @@ def register_routers(ranker, batch_cache, queued_batches):import mwmbl.tinysearchengine.search as search_moduleimport mwmbl.crawler.app as crawler_modulefrom mwmbl.platform.api import router as platform_router- from mwmbl.evaluation.api import router as evaluation_router# Initialise routers that depend on runtime objectssearch_module.init_router(ranker)+ search_module.init_v2_router(ranker)crawler_module.init_router(batch_cache, queued_batches)api.add_router("/search/", search_module.router, tags=["Search"])api.add_router("/crawler/", crawler_module.router, tags=["Crawler"])api.add_router("/platform/", platform_router, tags=["Platform"])- # This API is a work in progress, disabled for now- # api.add_router("/evaluate/", evaluation_router, tags=["Evaluation"])+ v2_api.add_router("/search/", search_module.v2_router, tags=["Search"])diff --git a/mwmbl/tinysearchengine/search.py b/mwmbl/tinysearchengine/search.pyindex 26c99a6..e6ea11f 100644--- a/mwmbl/tinysearchengine/search.py+++ b/mwmbl/tinysearchengine/search.py@@ -17,8 +17,9 @@ logger = getLogger(__name__)SCORE_THRESHOLD = 0.25-# Module-level router used by the unified v1 API-router = Router(tags=["Search"])+# Module-level routers+router = Router(tags=["Search"]) # v1+v2_router = Router(tags=["Search"]) # v2# ---------------------------------------------------------------------------@@ -202,11 +203,49 @@ def _upgrade_message(tier: str) -> str:# ----------------------------------------------------------------------------# Route registration+# Route registration helpers# ----------------------------------------------------------------------------def _register_routes(r: Router | NinjaAPI, ranker: HeuristicRanker):- """Register search routes on the given router or API instance."""+def _register_search_v1(r: Router | NinjaAPI, ranker: HeuristicRanker):+ """Register the v1 search endpoint: returns a plain list of SearchResult."""++ @r.get(+ "",+ response=list[SearchResult],+ auth=None,+ summary="Search",+ description=(+ "Search the Mwmbl index and return formatted results.\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 "+ "where matching query terms are flagged with `is_bold: true` for easy "+ "client-side highlighting.\n\n"+ "The `source` field indicates where the result originated:\n"+ "- `mwmbl` — organically crawled by the Mwmbl crawler\n"+ "- `wikipedia` — sourced from Wikipedia\n"+ "- `google` — originally suggested via Google\n"+ "- `user` — submitted directly by a user\n\n"+ "**Query parameter:** `s` — the search query string (required)."+ ),+ openapi_extra={+ "parameters": [+ {+ "name": "s",+ "in": "query",+ "required": True,+ "schema": {"type": "string", "example": "python tutorial"},+ }+ ]+ },+ )+ def search(request, s: str):+ results = ranker.search(s, [])+ return [format_result(result, s) for result in results]+++def _register_search_v2(r: Router | NinjaAPI, ranker: HeuristicRanker):+ """Register the v2 search endpoint: returns SearchResponse with optional quota info."""@r.get("",@@ -286,6 +325,10 @@ def _register_routes(r: Router | NinjaAPI, ranker: HeuristicRanker):monthly_limit=monthly_limit,)++def _register_common_routes(r: Router | NinjaAPI, ranker: HeuristicRanker):+ """Register the /complete and /raw endpoints (shared between v1 and v2)."""+@r.get("/complete",summary="Autocomplete",@@ -391,10 +434,18 @@ def _register_routes(r: Router | NinjaAPI, ranker: HeuristicRanker):def create_router(ranker: HeuristicRanker, version: str) -> NinjaAPI:"""Create a standalone NinjaAPI for a specific version (used for legacy routes)."""api = NinjaAPI(urls_namespace=f"search-{version}")- _register_routes(api, ranker)+ _register_search_v1(api, ranker)+ _register_common_routes(api, ranker)return apidef init_router(ranker: HeuristicRanker):- """Initialise the module-level router with the given ranker (called from urls.py)."""- _register_routes(router, ranker)+ """Initialise the v1 module-level router (called from urls.py)."""+ _register_search_v1(router, ranker)+ _register_common_routes(router, ranker)+++def init_v2_router(ranker: HeuristicRanker):+ """Initialise the v2 module-level router (called from urls.py)."""+ _register_search_v2(v2_router, ranker)+ _register_common_routes(v2_router, ranker)diff --git a/mwmbl/urls.py b/mwmbl/urls.pyindex b602f4d..4008b36 100644--- a/mwmbl/urls.py+++ b/mwmbl/urls.py@@ -20,7 +20,7 @@ from django.views.generic import RedirectViewfrom debug_toolbar.toolbar import debug_toolbar_urlsimport mwmbl.crawler.app as crawler-from mwmbl.api import api as v1_api, register_routers+from mwmbl.api import api as v1_api, v2_api, register_routersfrom mwmbl.search_setup import queued_batches, ranker, batch_cachefrom mwmbl.tinysearchengine import searchfrom mwmbl.views import home_fragment, add_url, index, approve, revert_current_curation, CurationDetailView, \@@ -59,9 +59,12 @@ urlpatterns = [path("search/", search.create_router(ranker, "0.1").urls),path("crawler/", crawler.create_router(batch_cache=batch_cache, queued_batches=queued_batches, version="0.1").urls),- # New unified API — all v1 endpoints, single docs page at /api/v1/docs+ # Unified v1 API — search returns plain list; single docs page at /api/v1/docspath("api/v1/", v1_api.urls),+ # v2 API — search returns object with quota metadata; docs at /api/v2/docs+ path("api/v2/", v2_api.urls),+# Redirects from old per-router docs URLs to the unified docs pagepath("api/v1/search/docs", RedirectView.as_view(url="/api/v1/docs", permanent=True)),path("api/v1/crawler/docs", RedirectView.as_view(url="/api/v1/docs", permanent=True)),diff --git a/test/test_search_api_key.py b/test/test_search_api_key.pyindex e4e3de8..c340344 100644--- a/test/test_search_api_key.py+++ b/test/test_search_api_key.py@@ -3,7 +3,7 @@ Tests for search API key management and quota enforcement.Covers:- POST/GET/DELETE /api/v1/platform/api-keys/-- GET /api/v1/search/ with valid/invalid/wrong-scope keys+- GET /api/v2/search/ with valid/invalid/wrong-scope keys- Monthly quota and per-second rate-limit enforcement- POST /api/v1/crawler/results with header vs body key and scope checks- flush_search_counts background task@@ -249,7 +249,7 @@ def test_delete_nonexistent_key_returns_404(api_client, access_token):@pytest.mark.django_dbdef test_search_missing_key_returns_results_with_null_usage(api_client):"""Unauthenticated requests are allowed; usage fields are null."""- response = api_client.get("/api/v1/search/?s=python")+ response = api_client.get("/api/v2/search/?s=python")assert response.status_code == 200data = response.json()assert data["monthly_usage"] is None@@ -258,7 +258,7 @@ def test_search_missing_key_returns_results_with_null_usage(api_client):@pytest.mark.django_dbdef test_search_invalid_key(api_client):- response = api_client.get("/api/v1/search/?s=python", **api_key_header("invalid-key"))+ response = api_client.get("/api/v2/search/?s=python", **api_key_header("invalid-key"))assert response.status_code == 401@@ -266,7 +266,7 @@ def test_search_invalid_key(api_client):def test_search_crawl_scoped_key_rejected(api_client, crawl_api_key):"""A crawl-scoped key must not grant access to the search endpoint."""response = api_client.get(- "/api/v1/search/?s=python",+ "/api/v2/search/?s=python",**api_key_header(crawl_api_key.raw_key),)assert response.status_code == 401@@ -282,7 +282,7 @@ def test_search_with_valid_key(api_client, search_api_key):patch("mwmbl.tinysearchengine.search.get_monthly_count", return_value=0), \patch("mwmbl.tinysearchengine.search.increment_monthly", return_value=1):response = api_client.get(- "/api/v1/search/?s=python",+ "/api/v2/search/?s=python",**api_key_header(search_api_key.raw_key),)assert response.status_code == 200@@ -296,7 +296,7 @@ def test_search_response_includes_usage_fields(api_client, search_api_key):patch("mwmbl.tinysearchengine.search.increment_monthly", return_value=6), \patch("mwmbl.tinysearchengine.rank.HeuristicRanker.search", return_value=[]):response = api_client.get(- "/api/v1/search/?s=python",+ "/api/v2/search/?s=python",**api_key_header(search_api_key.raw_key),)assert response.status_code == 200@@ -314,7 +314,7 @@ def test_search_response_includes_usage_fields(api_client, search_api_key):def test_search_rate_limit_exceeded(api_client, search_api_key):with patch("mwmbl.tinysearchengine.search.check_rate_limit", return_value=False):response = api_client.get(- "/api/v1/search/?s=python",+ "/api/v2/search/?s=python",**api_key_header(search_api_key.raw_key),)assert response.status_code == 429@@ -327,7 +327,7 @@ def test_search_monthly_quota_exceeded(api_client, search_api_key):with patch("mwmbl.tinysearchengine.search.check_rate_limit", return_value=True), \patch("mwmbl.tinysearchengine.search.get_monthly_count", return_value=limit):response = api_client.get(- "/api/v1/search/?s=python",+ "/api/v2/search/?s=python",**api_key_header(search_api_key.raw_key),)assert response.status_code == 429@@ -346,7 +346,7 @@ def test_search_monthly_quota_exceeded_pro_no_upgrade_message(api_client, searchwith patch("mwmbl.tinysearchengine.search.check_rate_limit", return_value=True), \patch("mwmbl.tinysearchengine.search.get_monthly_count", return_value=limit):response = api_client.get(- "/api/v1/search/?s=python",+ "/api/v2/search/?s=python",**api_key_header(search_api_key.raw_key),)assert response.status_code == 429@@ -558,7 +558,7 @@ def test_subscription_usage_matches_search_response(api_client, access_token, ve)cache.delete(_monthly_key(verified_user.id))- search_resp = api_client.get("/api/v1/search/?s=python", **api_key_header(raw_key))+ search_resp = api_client.get("/api/v2/search/?s=python", **api_key_header(raw_key))assert search_resp.status_code == 200search_usage = search_resp.json()["monthly_usage"]assert search_usage == 1