Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Add missing files

Daoud Clarke84d949165546
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..fb63e8e
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,79 @@
+# Mwmbl development Makefile
+#
+# Prerequisites:
+# - uv (https://github.com/astral-sh/uv)
+# - PostgreSQL running locally with peer auth for the current user
+# - Redis running locally on the default port (6379)
+#
+# Quick start:
+# createdb mwmbl # one-time setup for dev DB
+# createdb mwmbl_test # one-time setup for test DB
+# make migrate # apply all migrations
+# make test # run the full test suite
+# make run # start the dev server
+
+# ---------------------------------------------------------------------------
+# Configuration
+# ---------------------------------------------------------------------------
+
+# Override these via environment or make invocation, e.g.:
+# DATABASE_URL="postgres://user:pass@host/db" make test
+# These have no defaults — you must set them in your environment or on the command line.
+DATABASE_URL ?=
+REDIS_URL ?= redis://127.0.0.1:6379
+
+DJANGO_SETTINGS_MODULE ?= mwmbl.settings_dev
+TEST_SETTINGS := mwmbl.settings_test
+
+# ---------------------------------------------------------------------------
+# Targets
+# ---------------------------------------------------------------------------
+
+SODIR := .venv/lib/python3.11/site-packages/mwmbl_rank
+XGB_SO := mwmbl_rank/target/release/deps/libxgboost.so
+
+.PHONY: help install patch-xgboost migrate test test-file run run-background lint
+
+help:
+ @echo "Available targets:"
+ @echo " install Install all dependencies with uv"
+ @echo " migrate Apply Django migrations"
+ @echo " test Run the full test suite (set DATABASE_URL to your test DB)"
+ @echo " test-file FILE Run a specific test file, e.g. make test-file FILE=test/test_search_api_key.py"
+ @echo " run Start the Django development server"
+ @echo " run-background Start the background task processor"
+
+install:
+ uv sync
+ $(MAKE) patch-xgboost
+
+# Copy libxgboost.so into the mwmbl_rank package dir and set RPATH to $ORIGIN,
+# matching the Dockerfile post-build step so the extension is self-contained.
+patch-xgboost:
+ @if [ -f "$(XGB_SO)" ]; then \
+ cp "$(XGB_SO)" "$(SODIR)/"; \
+ .venv/bin/patchelf --set-rpath '$$ORIGIN' "$(SODIR)/mwmbl_rank.cpython-311-x86_64-linux-gnu.so"; \
+ echo "Patched RPATH and copied libxgboost.so to $(SODIR)"; \
+ else \
+ echo "$(XGB_SO) not found — run 'uv run maturin develop' first"; \
+ fi
+
+migrate:
+ DATABASE_URL="$(DATABASE_URL)" REDIS_URL="$(REDIS_URL)" \
+ uv run python manage.py migrate --settings=$(DJANGO_SETTINGS_MODULE)
+
+test:
+ DATABASE_URL="$(DATABASE_URL)" REDIS_URL="$(REDIS_URL)" \
+ uv run pytest $(PYTEST_ARGS)
+
+test-file:
+ DATABASE_URL="$(DATABASE_URL)" REDIS_URL="$(REDIS_URL)" \
+ uv run pytest $(FILE) -v $(PYTEST_ARGS)
+
+run:
+ DATABASE_URL="$(DATABASE_URL)" REDIS_URL="$(REDIS_URL)" \
+ uv run python manage.py runserver --settings=$(DJANGO_SETTINGS_MODULE)
+
+run-background:
+ DATABASE_URL="$(DATABASE_URL)" REDIS_URL="$(REDIS_URL)" \
+ uv run python manage.py process_tasks --settings=$(DJANGO_SETTINGS_MODULE)
diff --git a/mwmbl/migrations/0016_apikey_scopes_name_mwmbluser_tier.py b/mwmbl/migrations/0016_apikey_scopes_name_mwmbluser_tier.py
new file mode 100644
index 0000000..c06df4a
--- /dev/null
+++ b/mwmbl/migrations/0016_apikey_scopes_name_mwmbluser_tier.py
@@ -0,0 +1,55 @@
+from django.db import migrations, models
+import django.contrib.postgres.fields
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('mwmbl', '0015_alter_searchresultvote_vote_type'),
+ ]
+
+ operations = [
+ # ApiKey: add name field
+ migrations.AddField(
+ model_name='apikey',
+ name='name',
+ field=models.CharField(blank=True, default='', max_length=100),
+ ),
+ # ApiKey: add scopes ArrayField
+ migrations.AddField(
+ model_name='apikey',
+ name='scopes',
+ field=django.contrib.postgres.fields.ArrayField(
+ base_field=models.CharField(
+ choices=[('crawl', 'Crawl'), ('search', 'Search')],
+ max_length=20,
+ ),
+ default=list,
+ size=None,
+ ),
+ ),
+ # ApiKey: change created_on to auto_now_add
+ # We use AlterField; existing rows already have a value so this is safe.
+ migrations.AlterField(
+ model_name='apikey',
+ name='created_on',
+ field=models.DateTimeField(auto_now_add=True),
+ preserve_default=False,
+ ),
+ # MwmblUser: add tier field
+ migrations.AddField(
+ model_name='mwmbluser',
+ name='tier',
+ field=models.CharField(
+ choices=[('free', 'Free'), ('starter', 'Starter'), ('pro', 'Pro')],
+ default='free',
+ max_length=20,
+ ),
+ ),
+ # MwmblUser: add monthly_search_count field
+ migrations.AddField(
+ model_name='mwmbluser',
+ name='monthly_search_count',
+ field=models.IntegerField(default=0),
+ ),
+ ]
diff --git a/mwmbl/migrations/0017_backfill_apikey_scopes.py b/mwmbl/migrations/0017_backfill_apikey_scopes.py
new file mode 100644
index 0000000..0404295
--- /dev/null
+++ b/mwmbl/migrations/0017_backfill_apikey_scopes.py
@@ -0,0 +1,18 @@
+from django.db import migrations
+
+
+def set_crawl_scope(apps, schema_editor):
+ """Set scopes=["crawl"] on all existing ApiKey rows that have no scopes."""
+ ApiKey = apps.get_model("mwmbl", "ApiKey")
+ ApiKey.objects.filter(scopes=[]).update(scopes=["crawl"])
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('mwmbl', '0016_apikey_scopes_name_mwmbluser_tier'),
+ ]
+
+ operations = [
+ migrations.RunPython(set_crawl_scope, migrations.RunPython.noop),
+ ]
diff --git a/mwmbl/migrations/0018_usagebucket_remove_monthly_search_count.py b/mwmbl/migrations/0018_usagebucket_remove_monthly_search_count.py
new file mode 100644
index 0000000..3a8b3c7
--- /dev/null
+++ b/mwmbl/migrations/0018_usagebucket_remove_monthly_search_count.py
@@ -0,0 +1,30 @@
+from django.conf import settings
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('mwmbl', '0017_backfill_apikey_scopes'),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='UsageBucket',
+ fields=[
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+ ('year', models.IntegerField()),
+ ('month', models.IntegerField()),
+ ('count', models.IntegerField(default=0)),
+ ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
+ ],
+ options={
+ 'unique_together': {('user', 'year', 'month')},
+ },
+ ),
+ migrations.RemoveField(
+ model_name='mwmbluser',
+ name='monthly_search_count',
+ ),
+ ]
diff --git a/mwmbl/quota.py b/mwmbl/quota.py
new file mode 100644
index 0000000..ee377b1
--- /dev/null
+++ b/mwmbl/quota.py
@@ -0,0 +1,97 @@
+"""
+Quota and rate-limit helpers for the search API.
+
+All counters use the Django cache interface (django.core.cache.cache) so the
+backend can be swapped without changing this code. The only Redis-specific
+call is get_all_monthly_keys(), which uses SCAN via django-redis and is only
+called by the background flush/reset jobs.
+"""
+from datetime import datetime
+
+from django.core.cache import cache
+
+RATE_LIMIT = 5 # maximum requests per second (all tiers)
+MONTHLY_TTL = 60 * 60 * 24 * 35 # 35 days in seconds
+
+
+# ---------------------------------------------------------------------------
+# Key helpers
+# ---------------------------------------------------------------------------
+
+def _monthly_key(user_id: int, year: int | None = None, month: int | None = None) -> str:
+ now = datetime.utcnow()
+ y = year if year is not None else now.year
+ m = month if month is not None else now.month
+ return f"search:monthly:{user_id}:{y}:{m:02d}"
+
+
+def _rate_key(user_id: int) -> str:
+ return f"search:rate:{user_id}"
+
+
+# ---------------------------------------------------------------------------
+# Rate limiting (fixed-window, 5 req/s)
+# ---------------------------------------------------------------------------
+
+def check_rate_limit(user_id: int) -> bool:
+ """
+ Fixed-window rate limit: at most RATE_LIMIT requests per second.
+ Returns True if the request is allowed, False if the limit is exceeded.
+ """
+ key = _rate_key(user_id)
+ # add() sets the key only if it doesn't exist (atomic in Redis)
+ added = cache.add(key, 0, timeout=1)
+ if added:
+ # Key was just created; this is the first request in this window
+ cache.incr(key)
+ return True
+ count = cache.incr(key)
+ return count <= RATE_LIMIT
+
+
+# ---------------------------------------------------------------------------
+# Monthly quota
+# ---------------------------------------------------------------------------
+
+def get_monthly_count(user_id: int) -> int:
+ """Return the current monthly request count for a user (0 if not set)."""
+ return cache.get(_monthly_key(user_id), default=0)
+
+
+def increment_monthly(user_id: int) -> int:
+ """
+ Increment the monthly counter and return the new value.
+ Sets a 35-day TTL on first use so the key auto-expires.
+ """
+ key = _monthly_key(user_id)
+ # add() is atomic: sets key=1 with TTL only if it doesn't exist
+ if cache.add(key, 1, timeout=MONTHLY_TTL):
+ return 1
+ return cache.incr(key)
+
+
+# ---------------------------------------------------------------------------
+# Key scanning (used by background jobs only — requires django-redis)
+# ---------------------------------------------------------------------------
+
+def get_all_monthly_keys() -> list[str]:
+ """
+ Return all active monthly counter keys for the current month.
+ Uses the underlying Redis SCAN command via django-redis.
+ Only call this from background tasks, not from request handlers.
+ """
+ now = datetime.utcnow()
+ pattern = f"search:monthly:*:{now.year}:{now.month:02d}"
+ from django_redis import get_redis_connection
+ conn = get_redis_connection("default")
+ return [k.decode() if isinstance(k, bytes) else k for k in conn.scan_iter(pattern)]
+
+
+def delete_all_monthly_keys() -> None:
+ """
+ Delete all monthly counter keys for the current month.
+ Used by the monthly reset job.
+ """
+ keys = get_all_monthly_keys()
+ if keys:
+ cache.delete_many(keys)
diff --git a/mwmbl/search_auth.py b/mwmbl/search_auth.py
new file mode 100644
index 0000000..d2c1e12
--- /dev/null
+++ b/mwmbl/search_auth.py
@@ -0,0 +1,28 @@
+"""
+Authentication for the search API using the X-API-Key header.
+"""
+from ninja.security import APIKeyHeader
+
+from mwmbl.models import ApiKey
+
+
+class SearchApiKeyAuth(APIKeyHeader):
+ """
+ Ninja authentication class that reads the X-API-Key request header and
+ validates it against ApiKey rows that have the 'search' scope.
+
+ On success, request.auth is set to the ApiKey instance (giving access to
+ request.auth.user and request.auth.user.tier).
+ On failure, returns None which causes Ninja to respond with 401.
+ """
+
+ param_name = "X-API-Key"
+
+ def authenticate(self, request, key: str):
+ try:
+ return ApiKey.objects.select_related("user").get(
+ key=key,
+ scopes__contains=[ApiKey.Scope.SEARCH],
+ )
+ except ApiKey.DoesNotExist:
+ return None