Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

⚡️(api) add cache to prevent excessive drain from /stats endpoint #660

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/backend/core/api/client/viewsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
from django.conf import settings
from django.db.models import OuterRef, Q, Subquery, Value
from django.db.models.functions import Coalesce
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page

from rest_framework import (
decorators,
Expand Down Expand Up @@ -596,6 +598,7 @@ class StatView(views.APIView):

permission_classes = [AllowAny]

@method_decorator(cache_page(3600))
def get(self, request):
"""
GET /api/v1.0/stats/
Expand Down
16 changes: 16 additions & 0 deletions src/backend/core/tests/test_api_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
Test stats endpoint
"""

from django.core.cache import cache

import pytest
from rest_framework import status
from rest_framework.test import APIClient
Expand Down Expand Up @@ -43,6 +45,7 @@ def test_api_stats__expected_count():
10, domain=domains_models.MailDomain.objects.all()[1]
)

cache.clear() # clear cache to avoid interferences from previous tests
response = APIClient().get("/api/v1.0/stats/")
assert response.status_code == status.HTTP_200_OK
assert response.json() == {
Expand All @@ -52,3 +55,16 @@ def test_api_stats__expected_count():
"mailboxes": 10,
"teams": 3,
}


def test_api_stats__cache_as_expected():
"""Cache should prevent excessive calls."""
cache.clear() # clear cache to avoid interferences from previous tests

core_factories.UserFactory.create_batch(2)
APIClient().get("/api/v1.0/stats/")

core_factories.UserFactory() # There is now a total of 3 users

new_response = APIClient().get("/api/v1.0/stats/")
assert new_response.json()["total_users"] == 2
Loading