Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Add unauthenticated search/page/{n} endpoint returning a raw index page

Claudee35c6356407f
diff --git a/mwmbl/api.py b/mwmbl/api.py
index d2dc55a..f9c4ffa 100644
--- a/mwmbl/api.py
+++ b/mwmbl/api.py
@@ -162,12 +162,12 @@ def v2_invalid_request_handler(request, exc: InvalidRequest):
# 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, combined_ranker):
+def register_routers(ranker, combined_ranker, tiny_index):
"""
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 that
- dependencies (the rankers) are available.
+ dependencies (the rankers and the index) are available.
"""
import mwmbl.crawler.app as crawler_module
import mwmbl.tinysearchengine.combined_search as combined_search_module
@@ -176,8 +176,8 @@ def register_routers(ranker, combined_ranker):
from mwmbl.platform.api import router as platform_router
# Initialise routers that depend on runtime objects
- search_module.init_router(ranker)
- search_module.init_v2_router(ranker)
+ search_module.init_router(ranker, tiny_index)
+ search_module.init_v2_router(ranker, tiny_index)
super_search_module.init_router()
combined_search_module.init_router(combined_ranker)
crawler_module.init_router()
diff --git a/mwmbl/tinysearchengine/search.py b/mwmbl/tinysearchengine/search.py
index 9fb4dfb..aeb43b6 100644
--- a/mwmbl/tinysearchengine/search.py
+++ b/mwmbl/tinysearchengine/search.py
@@ -10,6 +10,7 @@ from mwmbl.format import format_result, format_result_v2
from mwmbl.models import MwmblUser
from mwmbl.quota import check_rate_limit, get_monthly_count, increment_monthly
from mwmbl.search_auth import SearchApiKeyAuth
+from mwmbl.tinysearchengine.indexer import TinyIndex
from mwmbl.tinysearchengine.rank import HeuristicRanker
logger = getLogger(__name__)
@@ -441,6 +442,28 @@ def _register_common_routes(r: Router | NinjaAPI, ranker: HeuristicRanker):
return {"query": s, "results": [dataclasses.asdict(result) for result in results]}
+def _register_page_route(r: Router | NinjaAPI, tiny_index: TinyIndex):
+ """Register the /page/{n} endpoint that exposes the index one page at a time."""
+
+ @r.get(
+ "/page/{n}",
+ response=list[list],
+ auth=None,
+ summary="Raw index page",
+ description=(
+ "Return the decompressed contents of page `n` of the index.\n\n"
+ "Each page is a list of documents, and each document is the tuple it is stored "
+ "as: `[title, url, extract, score, term, state, ...]`. Pages are numbered from 0; "
+ "`GET /page/{n}` for every `n` below the index's page count retrieves the whole "
+ "index. Useful for analysing how well the index is packed, or for taking a copy."
+ ),
+ )
+ def page(request, n: int):
+ if not 0 <= n < tiny_index.num_pages:
+ raise HttpError(404, f"Page {n} is not in an index of {tiny_index.num_pages} pages")
+ return tiny_index._get_page_tuples(n)
+
+
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}")
@@ -449,13 +472,15 @@ def create_router(ranker: HeuristicRanker, version: str) -> NinjaAPI:
return api
-def init_router(ranker: HeuristicRanker):
+def init_router(ranker: HeuristicRanker, tiny_index: TinyIndex):
"""Initialise the v1 module-level router (called from urls.py)."""
_register_search_v1(router, ranker)
_register_common_routes(router, ranker)
+ _register_page_route(router, tiny_index)
-def init_v2_router(ranker: HeuristicRanker):
+def init_v2_router(ranker: HeuristicRanker, tiny_index: TinyIndex):
"""Initialise the v2 module-level router (called from urls.py)."""
_register_search_v2(v2_router, ranker)
_register_common_routes(v2_router, ranker)
+ _register_page_route(v2_router, tiny_index)
diff --git a/mwmbl/urls.py b/mwmbl/urls.py
index 8dca731..96e14eb 100644
--- a/mwmbl/urls.py
+++ b/mwmbl/urls.py
@@ -24,7 +24,7 @@ import mwmbl.crawler.app as crawler
from mwmbl.admin_views import blacklist_status_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
+from mwmbl.search_setup import combined_ranker, ranker, tiny_index
from mwmbl.tinysearchengine import search
from mwmbl.views import (
CurationDetailView,
@@ -45,7 +45,7 @@ from mwmbl.views import (
# Initialise the unified v1 API by registering all sub-routers with their runtime dependencies.
# This must be called before urlpatterns is evaluated.
-register_routers(ranker=ranker, combined_ranker=combined_ranker)
+register_routers(ranker=ranker, combined_ranker=combined_ranker, tiny_index=tiny_index)
def trigger_error(request):
diff --git a/test/test_index_page_api.py b/test/test_index_page_api.py
new file mode 100644
index 0000000..0f78be2
--- /dev/null
+++ b/test/test_index_page_api.py
@@ -0,0 +1,39 @@
+"""GET /api/v{1,2}/search/page/{n}: the raw, decompressed contents of one index page."""
+
+import pytest
+from django.test import Client
+
+from mwmbl.search_setup import tiny_index
+from mwmbl.tinysearchengine.indexer import Document, TinyIndex
+
+PAGE_DOCUMENTS = [
+ Document(title="Python", url="https://python.org/", extract="The Python language", score=1.5, term="python"),
+ Document(title="Rust", url="https://rust-lang.org/", extract="The Rust language", score=0.5, term="rust"),
+]
+
+
+def stored_page():
+ """Put known documents on page 0, putting back whatever was there afterwards."""
+ page_index = 0
+ with TinyIndex(Document, tiny_index.index_path, mode="w") as writer:
+ original = writer.get_page(page_index)
+ writer.store_in_page(page_index, PAGE_DOCUMENTS)
+ yield page_index
+ writer.store_in_page(page_index, original)
+
+
[email protected]("version", ["v1", "v2"])
+def test_page_returns_stored_tuples(stored_page, version):
+ response = Client().get(f"/api/{version}/search/page/{stored_page}")
+
+ assert response.status_code == 200
+ expected_tuples = [list(document.as_tuple()) for document in PAGE_DOCUMENTS]
+ assert response.json() == expected_tuples
+
+
[email protected]("page_index", [-1, tiny_index.num_pages])
+def test_page_out_of_range_is_404(page_index):
+ response = Client().get(f"/api/v1/search/page/{page_index}")
+
+ assert response.status_code == 404
diff --git a/test/test_openapi.py b/test/test_openapi.py
index 524aac0..5c51f75 100644
--- a/test/test_openapi.py
+++ b/test/test_openapi.py
@@ -206,6 +206,7 @@ def test_v2_openapi_spec_generation():
"/api/v2/search/",
"/api/v2/search/complete",
"/api/v2/search/raw",
+ "/api/v2/search/page/{n}",
"/api/v2/super-search/",
"/api/v2/combined-search/",
}