-
Notifications
You must be signed in to change notification settings - Fork 580
✨(backend) add limit on distinct reactions per comment #1978
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2625,6 +2625,7 @@ def get(self, request): | |
| "POSTHOG_KEY", | ||
| "LANGUAGES", | ||
| "LANGUAGE_CODE", | ||
| "REACTIONS_MAX_PER_COMMENT", | ||
| "SENTRY_DSN", | ||
| "TRASHBIN_CUTOFF_DAYS", | ||
| ] | ||
|
|
@@ -2742,7 +2743,11 @@ class CommentViewSet( | |
| permission_classes = [permissions.CommentPermission] | ||
| pagination_class = Pagination | ||
| serializer_class = serializers.CommentSerializer | ||
| queryset = models.Comment.objects.select_related("user").all() | ||
| queryset = ( | ||
| models.Comment.objects.select_related("user") | ||
| .prefetch_related("reactions__users") | ||
| .all() | ||
| ) | ||
|
|
||
| def get_queryset(self): | ||
| """Override to filter on related resource.""" | ||
|
|
@@ -2776,9 +2781,29 @@ def reactions(self, request, *args, **kwargs): | |
| serializer.is_valid(raise_exception=True) | ||
|
|
||
| if request.method == "POST": | ||
| emoji = serializer.validated_data["emoji"] | ||
|
|
||
| if ( | ||
| not models.Reaction.objects.filter( | ||
| comment=comment, emoji=emoji | ||
| ).exists() | ||
| and comment.reactions.count() >= settings.REACTIONS_MAX_PER_COMMENT | ||
|
lunika marked this conversation as resolved.
|
||
| ): | ||
| return drf.response.Response( | ||
| { | ||
| "emoji": [ | ||
| _( | ||
| "A comment can have a maximum of %(max)d distinct reactions." | ||
| ) | ||
| % {"max": settings.REACTIONS_MAX_PER_COMMENT} | ||
| ] | ||
| }, | ||
| status=status.HTTP_400_BAD_REQUEST, | ||
| ) | ||
|
|
||
| reaction, created = models.Reaction.objects.get_or_create( | ||
| comment=comment, | ||
| emoji=serializer.validated_data["emoji"], | ||
| emoji=emoji, | ||
| ) | ||
|
Comment on lines
2783
to
2807
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Serialize the limit check with the create step. This is still a TOCTOU race: two concurrent POSTs with different new emojis can both observe Suggested fix if request.method == "POST":
emoji = serializer.validated_data["emoji"]
-
- if (
- not models.Reaction.objects.filter(
- comment=comment, emoji=emoji
- ).exists()
- and comment.reactions.count() >= settings.REACTIONS_MAX_PER_COMMENT
- ):
- return drf.response.Response(
- {
- "emoji": [
- _(
- "A comment can have a maximum of %(max)d distinct reactions."
- )
- % {"max": settings.REACTIONS_MAX_PER_COMMENT}
- ]
- },
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- reaction, created = models.Reaction.objects.get_or_create(
- comment=comment,
- emoji=emoji,
- )
+ with transaction.atomic():
+ comment = models.Comment.objects.select_for_update().get(pk=comment.pk)
+ reactions = models.Reaction.objects.filter(comment=comment)
+
+ if (
+ not reactions.filter(emoji=emoji).exists()
+ and reactions.count() >= settings.REACTIONS_MAX_PER_COMMENT
+ ):
+ return drf.response.Response(
+ {
+ "emoji": [
+ _(
+ "A comment can have a maximum of %(max)d distinct reactions."
+ )
+ % {"max": settings.REACTIONS_MAX_PER_COMMENT}
+ ]
+ },
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ reaction, created = models.Reaction.objects.get_or_create(
+ comment=comment,
+ emoji=emoji,
+ )🤖 Prompt for AI Agents
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @lunika, this is prone to race condition, a user can create a MAX+1 emoji if he spams emojis, is it worth fixing or it's an overkill ? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think it's overkill and I'm not ok to add a lock on the table. |
||
| if not created and reaction.users.filter(id=request.user.id).exists(): | ||
| return drf.response.Response( | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -876,3 +876,56 @@ def test_delete_reaction_owned_by_the_current_user(): | |
|
|
||
| reaction.refresh_from_db() | ||
| assert reaction.users.exists() | ||
|
|
||
|
|
||
| def test_create_reaction_exceeds_maximum(settings): | ||
| """ | ||
| Users should not be able to add more than REACTIONS_MAX_PER_COMMENT | ||
| (here we set it to 10) distinct emoji reactions to a comment. | ||
|
lunika marked this conversation as resolved.
|
||
| They should, however, be able to add themselves to an existing reaction. | ||
| """ | ||
| user1 = factories.UserFactory() | ||
| user2 = factories.UserFactory() | ||
| document = factories.DocumentFactory( | ||
| link_reach="restricted", | ||
| users=[(user1, models.RoleChoices.ADMIN), (user2, models.RoleChoices.ADMIN)], | ||
| ) | ||
| thread = factories.ThreadFactory(document=document) | ||
| comment = factories.CommentFactory(thread=thread) | ||
|
|
||
| client = APIClient() | ||
| client.force_login(user1) | ||
|
|
||
| # Add max distinct reactions | ||
| max_reactions = settings.REACTIONS_MAX_PER_COMMENT | ||
|
Comment on lines
+881
to
+900
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Docstring/behavior mismatch: test doesn't actually set the limit to 10. The docstring says 🛠️ Proposed fix def test_create_reaction_exceeds_maximum(settings):
"""
Users should not be able to add more than REACTIONS_MAX_PER_COMMENT
(here we set it to 10) distinct emoji reactions to a comment.
They should, however, be able to add themselves to an existing reaction.
"""
+ settings.REACTIONS_MAX_PER_COMMENT = 10
user1 = factories.UserFactory()🤖 Prompt for AI Agents |
||
| emojis = factories.ReactionFactory.generate_emojis(max_reactions + 1) | ||
| for emoji in emojis[:max_reactions]: | ||
| response = client.post( | ||
| f"/api/v1.0/documents/{document.id!s}/threads/{thread.id!s}/" | ||
| f"comments/{comment.id!s}/reactions/", | ||
| {"emoji": emoji}, | ||
| ) | ||
| assert response.status_code == 201 | ||
|
|
||
| # Attempt to add another distinct reaction | ||
| response = client.post( | ||
| f"/api/v1.0/documents/{document.id!s}/threads/{thread.id!s}/" | ||
| f"comments/{comment.id!s}/reactions/", | ||
| {"emoji": emojis[max_reactions]}, | ||
| ) | ||
| assert response.status_code == 400 | ||
| expected_message = ( | ||
| f"A comment can have a maximum of {max_reactions} distinct reactions." | ||
| ) | ||
| assert response.json() == {"emoji": [expected_message]} | ||
|
|
||
| # Attempt to add user2 to one of the existing reactions (should succeed) | ||
| client.force_login(user2) | ||
| response = client.post( | ||
| f"/api/v1.0/documents/{document.id!s}/threads/{thread.id!s}/" | ||
| f"comments/{comment.id!s}/reactions/", | ||
| {"emoji": emojis[0]}, | ||
| ) | ||
| assert response.status_code == 201 | ||
| reaction = models.Reaction.objects.get(comment=comment, emoji=emojis[0]) | ||
| assert reaction.users.count() == 2 | ||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next'; | |||||
| import { useCunninghamTheme } from '@/cunningham'; | ||||||
| import { User, avatarUrlFromName } from '@/features/auth'; | ||||||
| import { Doc, useProviderStore } from '@/features/docs/doc-management'; | ||||||
| import { useConfig } from '@/core'; | ||||||
|
|
||||||
| import { DocsThreadStore } from './DocsThreadStore'; | ||||||
| import { DocsThreadStoreAuth } from './DocsThreadStoreAuth'; | ||||||
|
|
@@ -16,6 +17,7 @@ export function useComments( | |||||
| const { provider } = useProviderStore(); | ||||||
| const { t } = useTranslation(); | ||||||
| const { themeTokens } = useCunninghamTheme(); | ||||||
| const { data: config } = useConfig(); | ||||||
|
|
||||||
| const threadStore = useMemo(() => { | ||||||
| return new DocsThreadStore( | ||||||
|
|
@@ -24,9 +26,16 @@ export function useComments( | |||||
| new DocsThreadStoreAuth( | ||||||
| encodeURIComponent(user?.full_name || ''), | ||||||
| canComment, | ||||||
| config?.REACTIONS_MAX_PER_COMMENT ?? 0, | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Minor: When Consider using the backend's documented default (15) as the fallback, or rendering the picker as loading until 💡 Optional refactor- config?.REACTIONS_MAX_PER_COMMENT ?? 0,
+ config?.REACTIONS_MAX_PER_COMMENT ?? 15,📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||
| ), | ||||||
| ); | ||||||
| }, [docId, canComment, provider?.awareness, user?.full_name]); | ||||||
| }, [ | ||||||
| docId, | ||||||
| canComment, | ||||||
| provider?.awareness, | ||||||
| user?.full_name, | ||||||
| config?.REACTIONS_MAX_PER_COMMENT, | ||||||
| ]); | ||||||
|
|
||||||
| useEffect(() => { | ||||||
| return () => { | ||||||
|
|
||||||
Uh oh!
There was an error while loading. Please reload this page.