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

chore: webhook, comments migration #6523

Open
wants to merge 1 commit into
base: preview
Choose a base branch
from

Conversation

NarayanBavisetti
Copy link
Collaborator

@NarayanBavisetti NarayanBavisetti commented Jan 30, 2025

Description

this pull request contains new field changes for webhook, comment, profile and user visits.

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • Feature (non-breaking change which adds functionality)
  • Improvement (change that would cause existing functionality to not work as expected)
  • Code refactoring
  • Performance improvements
  • Documentation update

Summary by CodeRabbit

Release Notes

  • New Features

    • Added edited_at timestamp for issue comments
    • Introduced is_smooth_cursor_enabled user profile setting
  • Database Changes

    • Modified webhook log storage mechanism
    • Updated account uniqueness constraints
    • Expanded entity name field flexibility
  • Improvements

    • Enhanced tracking of comment edit history
    • Refined user account association rules

Copy link
Contributor

coderabbitai bot commented Jan 30, 2025

Walkthrough

This pull request introduces several database model modifications across multiple files in the Plane application. The changes primarily involve updating field types and constraints in models related to webhooks, user profiles, issue comments, and recent visits. Key modifications include changing the webhook field in WebhookLog from a foreign key to a UUID, adding an edited_at field to IssueComment, introducing a is_smooth_cursor_enabled flag in Profile, and adjusting unique constraints for the Account model.

Changes

File Change Summary
apiserver/plane/app/views/webhook/base.py Modified get method filtering for webhook_logs to use webhook instead of webhook_id
apiserver/plane/bgtasks/webhook_task.py Updated WebhookLog.objects.create() to use webhook parameter instead of webhook_id
apiserver/plane/db/models/webhook.py Changed webhook field from ForeignKey to UUIDField in WebhookLog model
apiserver/plane/db/models/issue.py Added edited_at field to IssueComment model
apiserver/plane/db/models/user.py Added is_smooth_cursor_enabled to Profile model and updated Account unique constraint
apiserver/plane/db/models/recent_visit.py Removed choices constraint from entity_name field in UserRecentVisit model

Possibly related PRs

Suggested Reviewers

  • pablohashescobar
  • sriramveeraghanta
  • pushya22

Poem

🐰 A rabbit's tale of code's new trail,
Webhooks dancing, models prevail!
UUIDs spin, constraints align,
Comments edited, features shine bright,
In Plane's digital garden, code takes flight! 🚀

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
apiserver/plane/db/migrations/0091_issuecomment_edited_at_and_more.py (1)

13-22: Determine the best usage for new fields.

  • edited_at: Consider setting auto_now=True if you want to automatically track the latest edit time.
  • is_smooth_cursor_enabled: Defaulting to False is reasonable, but verify if environment-based toggling is required.
apiserver/plane/db/models/issue.py (1)

470-470: LGTM! Consider auto-updating edited_at in the save method.

The edited_at field is properly added to track comment edits.

Consider updating the edited_at field automatically in the save method when the comment content changes:

 def save(self, *args, **kwargs):
     self.comment_stripped = (
         strip_tags(self.comment_html) if self.comment_html != "" else ""
     )
+    if not self._state.adding and (
+        self.tracker.has_changed('comment_html') or
+        self.tracker.has_changed('comment_json')
+    ):
+        self.edited_at = timezone.now()
     return super(IssueComment, self).save(*args, **kwargs)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6a37a2c and d190a85.

📒 Files selected for processing (7)
  • apiserver/plane/app/views/webhook/base.py (1 hunks)
  • apiserver/plane/bgtasks/webhook_task.py (4 hunks)
  • apiserver/plane/db/migrations/0091_issuecomment_edited_at_and_more.py (1 hunks)
  • apiserver/plane/db/models/issue.py (1 hunks)
  • apiserver/plane/db/models/recent_visit.py (1 hunks)
  • apiserver/plane/db/models/user.py (2 hunks)
  • apiserver/plane/db/models/webhook.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (python)
🔇 Additional comments (12)
apiserver/plane/db/models/recent_visit.py (1)

20-20: Verify if removing choices is intentional.

By removing choices and allowing any string in entity_name, you risk inconsistent or unvalidated data. If broader entity names are needed, consider adding a custom validator or a new enumeration to maintain consistency.

apiserver/plane/db/migrations/0091_issuecomment_edited_at_and_more.py (7)

1-2: Auto-generated migration header.

No further action needed; this is a standard Django migration boilerplate.


3-4: Import statements.

All necessary Django modules are properly imported.


6-7: Migration class definition.

Straightforward Django migration class with no issues.


8-10: Dependency declaration.

Dependencies are correctly listed to maintain proper migration order.


23-27: Consistency with model changes for entity_name.

Matches the removal of choices in UserRecentVisit. Make sure the broader input range is intentional.


28-32: WebhookLog field alteration already noted.

This confirms the change from ForeignKey to UUIDField. See previous comment about referencing self.webhook.url.


33-37: New unique constraint for account.

Enforcing uniqueness on ('user', 'provider', 'provider_account_id') strengthens data integrity. Looks good.

apiserver/plane/app/views/webhook/base.py (1)

123-123: LGTM! Field name aligned with model changes.

The filter condition now correctly uses webhook instead of webhook_id, consistent with the WebhookLog model changes.

Let's verify the model relationship:

✅ Verification successful

Field name alignment verified across model, view, and serializer

The webhook field is consistently defined as a UUIDField in the model and correctly used in the filter conditions, with proper read-only configuration in the serializer.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the WebhookLog model field definition
ast-grep --pattern 'class WebhookLog {
  $$$
  webhook = models.$_($$$)
  $$$
}'

Length of output: 82


Script:

#!/bin/bash
# Find the WebhookLog model definition
rg "class WebhookLog" -A 10

Length of output: 2015

apiserver/plane/db/models/user.py (2)

189-190: LGTM! New feature flag added.

The is_smooth_cursor_enabled boolean field is properly added with a default value of False.


229-229: Verify data integrity before applying the unique constraint.

The unique constraint has been strengthened by including the 'user' field. While this improves data integrity by ensuring one account per user per provider, it could cause migration issues if duplicate records exist.

Run this script to check for potential conflicts:

✅ Verification successful

Constraint change is safe and improves data integrity

The unique constraint enhancement is safe and beneficial because:

  • Social auth providers ensure account IDs are unique per user
  • The constraint prevents security issues by ensuring one provider account can't be linked to multiple users
  • The change is a logical strengthening of the existing constraint
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for duplicate provider accounts that would violate the new constraint

# Use Python to analyze the data
python3 << 'EOF'
from django.db import connection

with connection.cursor() as cursor:
    cursor.execute("""
        SELECT user_id, provider, provider_account_id, COUNT(*)
        FROM accounts
        WHERE deleted_at IS NULL
        GROUP BY user_id, provider, provider_account_id
        HAVING COUNT(*) > 1
    """)
    duplicates = cursor.fetchall()
    
    if duplicates:
        print("WARNING: Found duplicate records that would violate the new constraint:")
        for dup in duplicates:
            print(f"user_id: {dup[0]}, provider: {dup[1]}, provider_account_id: {dup[2]}, count: {dup[3]}")
    else:
        print("No duplicate records found. Safe to apply the constraint.")
EOF

Length of output: 128


Script:

#!/bin/bash
# Check the model history and migrations
echo "=== Checking model definition ==="
rg -A 5 -B 5 "class Meta:" apiserver/plane/db/models/user.py

echo -e "\n=== Checking migrations ==="
fd -e py . apiserver/plane/db/migrations/ -x cat {} | rg -A 5 -B 5 "unique_together"

Length of output: 38007


Script:

#!/bin/bash
# Check for data migration code and related changes
echo "=== Checking for migration handling code ==="
rg -B 5 -A 5 "migrate.*account" apiserver/plane/db/migrations/
rg -l "provider.*account.*id" apiserver/plane/db/

echo -e "\n=== Checking Account model implementation ==="
rg -B 10 -A 10 "class Account" apiserver/plane/db/models/

Length of output: 1798

apiserver/plane/bgtasks/webhook_task.py (1)

139-139: LGTM! Consistent field name updates across webhook logging.

The field name has been consistently updated from webhook_id to webhook in all WebhookLog creation calls, aligning with the model changes.

Also applies to: 156-156, 307-307, 322-322

@@ -66,7 +66,7 @@ class WebhookLog(BaseModel):
"db.Workspace", on_delete=models.CASCADE, related_name="webhook_logs"
)
# Associated webhook
webhook = models.ForeignKey(Webhook, on_delete=models.CASCADE, related_name="logs")
webhook = models.UUIDField()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix broken reference in the __str__ method.

Switching webhook from a ForeignKey to a UUIDField invalidates calls to self.webhook.url. This will throw an error since self.webhook is now a UUID, not an object. Update the __str__ method to reference just the UUID or store the URL separately if needed.

- return f"{self.event_type} {str(self.webhook.url)}"
+ return f"{self.event_type} {str(self.webhook)}"

Committable suggestion skipped: line range outside the PR's diff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
⚙️backend 🔄migrations Contains Migration changes
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant