throttle hot read endpoints and cap unbounded list responses

progress/views.py
  - GuestAwareReadThrottle (same guest-by-IP pattern as the other apps);
    throttle_scope='read' on UserSummaryView, StreakCalendarView,
    LeaderboardView.
notifications/views.py
  - GuestAwareReadThrottle + throttle_scope='read' on NotificationListView.
  - list capped at NOTIFICATIONS_MAX=100 newest (Meta.ordering already
    newest-first); unreadCount still counted over the full set.
notifications/tests.py
  - 150 rows -> 100 returned newest-first, unreadCount = 75.
rag/views.py
  - ChunkListView: explicit order_by('-id') before the existing [:200] cap.
ai_tutor/views.py
  - ConversationMessagesView: return the newest 200 messages in
    chronological order instead of the whole conversation.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-30 08:45:43 +03:30
parent 35218bf6a1
commit ff57adbc5f
5 changed files with 78 additions and 4 deletions

View File

@@ -80,3 +80,31 @@ class NotifyInvalidChannelTests(TestCase):
with self.assertRaises(ValueError):
notify(user_id=3, type='order_paid', title='t', channel='email')
self.assertEqual(Notification.objects.count(), 0)
from django.core.cache import cache
from rest_framework.test import APIClient
from accounts.authentication import issue_access_token
from accounts.models import User
class NotificationListCapTests(TestCase):
def setUp(self):
cache.clear()
self.client = APIClient()
self.user = User.objects.create(device_id='dev-notif-cap', is_guest=True, name='n')
self.token = issue_access_token(self.user.id)
def test_returns_at_most_100_newest_with_correct_unread_count(self):
Notification.objects.bulk_create([
Notification(user_id=self.user.id, type='xp_earned', title=f't{i}', is_read=(i % 2 == 0))
for i in range(150)
])
r = self.client.get('/api/notifications', HTTP_AUTHORIZATION=f'Bearer {self.token}')
self.assertEqual(r.status_code, 200)
self.assertEqual(len(r.data['items']), 100)
self.assertEqual(r.data['unreadCount'], 75) # از کلِ ۱۵۰، نه از ۱۰۰ برگشتی
# جدیدترین اول (Meta.ordering = -created_at؛ اینجا هم‌زمان → -id غالب)
ids = [it['id'] if isinstance(it, dict) else it.id for it in r.data['items']]
self.assertEqual(ids, sorted(ids, reverse=True))