-
Notifications
You must be signed in to change notification settings - Fork 582
✨(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 |
|---|---|---|
|
|
@@ -2838,6 +2838,7 @@ def get(self, request): | |
| "POSTHOG_KEY", | ||
| "LANGUAGES", | ||
| "LANGUAGE_CODE", | ||
| "REACTIONS_MAX_PER_COMMENT", | ||
| "SENTRY_DSN", | ||
| "TRASHBIN_CUTOFF_DAYS", | ||
| ] | ||
|
|
@@ -2955,7 +2956,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.""" | ||
|
|
@@ -2989,9 +2994,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 | ||
| ): | ||
| 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
2996
to
3020
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 | ||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -236,6 +236,11 @@ class Meta: | |||||||||||||||||||
| comment = factory.SubFactory(CommentFactory) | ||||||||||||||||||||
| emoji = factory.Faker("emoji") | ||||||||||||||||||||
|
|
||||||||||||||||||||
| @classmethod | ||||||||||||||||||||
| def generate_emojis(cls, n=10): | ||||||||||||||||||||
| """Generate a list of n unique emojis.""" | ||||||||||||||||||||
| return [fake.unique.emoji() for _ in range(n)] | ||||||||||||||||||||
|
Comment on lines
+239
to
+242
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. 🧹 Nitpick | 🔵 Trivial Avoid shared Line 242 relies on a module-level unique registry, which can leak state between tests and make failures order-dependent. ♻️ Suggested refactor `@classmethod`
def generate_emojis(cls, n=10):
"""Generate a list of n unique emojis."""
- return [fake.unique.emoji() for _ in range(n)]
+ faker = Faker()
+ return [faker.unique.emoji() for _ in range(n)]📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||
|
|
||||||||||||||||||||
| @factory.post_generation | ||||||||||||||||||||
| def users(self, create, extracted, **kwargs): | ||||||||||||||||||||
| """Add users to reaction from a given list of users or create one if not provided.""" | ||||||||||||||||||||
|
|
||||||||||||||||||||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -5,6 +5,7 @@ import { useCunninghamTheme } from '@/cunningham'; | |||||
| import { User, avatarUrlFromName } from '@/features/auth'; | ||||||
| import { useEditorStore } from '@/features/docs/doc-editor/stores'; | ||||||
| import { Doc, useProviderStore } from '@/features/docs/doc-management'; | ||||||
| import { useConfig } from '@/core'; | ||||||
|
coderabbitai[bot] marked this conversation as resolved.
|
||||||
|
|
||||||
| import { DocsThreadStore } from './DocsThreadStore'; | ||||||
| import { DocsThreadStoreAuth } from './DocsThreadStoreAuth'; | ||||||
|
|
@@ -18,6 +19,7 @@ export function useComments( | |||||
| const { t } = useTranslation(); | ||||||
| const { themeTokens } = useCunninghamTheme(); | ||||||
| const { setThreadStore } = useEditorStore(); | ||||||
| const { data: config } = useConfig(); | ||||||
|
|
||||||
| const threadStore = useMemo(() => { | ||||||
| return new DocsThreadStore( | ||||||
|
|
@@ -26,9 +28,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(() => { | ||||||
| if (canComment) { | ||||||
|
|
||||||
Uh oh!
There was an error while loading. Please reload this page.