Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Cache DB requests on search endpoint

Daoud Clarke5c10d4e91cb1
diff --git a/mwmbl/platform/api.py b/mwmbl/platform/api.py
index 6265a75..ebb8bc1 100644
--- a/mwmbl/platform/api.py
+++ b/mwmbl/platform/api.py
@@ -10,6 +10,7 @@ from polar_sdk import Polar
from polar_sdk.webhooks import validate_event, WebhookVerificationError
from mwmbl.exceptions import InvalidRequest
+from mwmbl.search_auth import invalidate_api_key_cache, invalidate_user_api_key_cache
from mwmbl.models import MwmblUser, DomainSubmission, SearchResultVote, ApiKey, UsageBucket, UserBilling, generate_username
from mwmbl.platform.schemas import (
Registration, ConfirmEmail, DomainSubmissionSchema, UpdateDomainSubmission,
@@ -121,6 +122,7 @@ def delete_user(request, username: str):
if user != request.user:
raise InvalidRequest("You can only delete your own account.")
+ invalidate_user_api_key_cache(user.id)
user.delete()
return {"status": "ok", "message": "User deleted."}
@@ -419,6 +421,7 @@ def delete_api_key(request, key_id: int):
).first()
if api_key is None:
raise InvalidRequest("API key not found.", status=404)
+ invalidate_api_key_cache(api_key.key)
api_key.delete()
return {"status": "ok", "message": "API key revoked."}
@@ -534,6 +537,7 @@ def polar_webhook(request):
tier = product_tier.get(event.data.product_id, MwmblUser.Tier.FREE)
user.tier = tier
user.save()
+ invalidate_user_api_key_cache(user.id)
billing, _ = UserBilling.objects.get_or_create(user=user)
billing.polar_customer_id = event.data.customer_id or billing.polar_customer_id
billing.polar_subscription_id = event.data.id or billing.polar_subscription_id
@@ -544,6 +548,7 @@ def polar_webhook(request):
if user:
user.tier = MwmblUser.Tier.FREE
user.save()
+ invalidate_user_api_key_cache(user.id)
return {"status": "ok"}
diff --git a/mwmbl/search_auth.py b/mwmbl/search_auth.py
index bc60e8d..60abe71 100644
--- a/mwmbl/search_auth.py
+++ b/mwmbl/search_auth.py
@@ -3,20 +3,48 @@ Authentication for the search API using the X-API-Key header.
"""
import hashlib
+from django.core.cache import cache
from ninja.security import APIKeyHeader
from mwmbl.models import ApiKey
+CACHE_TTL = 3600 # 1 hour; explicit invalidation handles all mutation paths
+
+
+def _cache_key(key_hash: str) -> str:
+ return f"search:apikey:{key_hash}"
+
+
+def invalidate_api_key_cache(key_hash: str) -> None:
+ cache.delete(_cache_key(key_hash))
+
+
+def invalidate_user_api_key_cache(user_id: int) -> None:
+ key_hashes = ApiKey.objects.filter(
+ user_id=user_id,
+ scopes__contains=[ApiKey.Scope.SEARCH],
+ ).values_list("key", flat=True)
+ cache.delete_many([_cache_key(h) for h in key_hashes])
+
class SearchApiKeyAuth(APIKeyHeader):
param_name = "X-API-Key"
def authenticate(self, request, key: str):
key_hash = hashlib.sha256(key.encode()).hexdigest()
+ cache_key = _cache_key(key_hash)
+
+ cached = cache.get(cache_key)
+ if cached is not None:
+ return cached
+
try:
- return ApiKey.objects.select_related("user").get(
+ api_key = ApiKey.objects.select_related("user").get(
key=key_hash,
scopes__contains=[ApiKey.Scope.SEARCH],
)
except ApiKey.DoesNotExist:
return None
+
+ cache.set(cache_key, api_key, CACHE_TTL)
+ return api_key