-
Notifications
You must be signed in to change notification settings - Fork 1.9k
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
minor improvements for workspace management #6099
Conversation
WalkthroughThe changes in this pull request focus on improving the handling of workspace slugs across various components. Key modifications include the use of template literals and Changes
Possibly related PRs
Suggested labels
Suggested reviewers
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
🧹 Outside diff range and nitpick comments (7)
apiserver/plane/license/api/serializers/workspace.py (2)
21-23
: Consider adding a database index for performance.The
__iexact
lookup might not efficiently use the default index. Consider adding a functional index for case-insensitive lookups if you expect a large number of workspaces.Example migration:
from django.contrib.postgres.operations import CreateIndex from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('your_app', 'previous_migration'), ] operations = [ migrations.AddIndex( model_name='workspace', index=models.Index( Lower('slug'), name='workspace_slug_lower_idx' ), ), ]
21-23
: Consider adding transaction-level protection.There's a potential race condition between validation and creation. Consider using
select_for_update()
or unique constraints at the database level.Example implementation:
def validate_slug(self, value): if value in RESTRICTED_WORKSPACE_SLUGS: raise serializers.ValidationError("Slug is not valid") - if Workspace.objects.filter(slug__iexact=value).exists(): + # Use select_for_update() to prevent race conditions + with transaction.atomic(): + if Workspace.objects.select_for_update().filter(slug__iexact=value).exists(): raise serializers.ValidationError("Slug is already in use") return valueadmin/core/components/workspace/list-item.tsx (1)
25-25
: Consider extracting workspace URL construction to a helper functionSince workspace URL construction might be needed in multiple places, consider extracting this logic into a reusable helper function:
// helpers/workspace.helper.ts export const getWorkspaceUrl = (slug: string): string => `${WEB_BASE_URL}/${encodeURIComponent(slug)}`; // Usage in component: href={getWorkspaceUrl(workspace.slug)}This would ensure consistent URL construction across the application and make it easier to modify the pattern if needed.
apiserver/plane/license/api/views/workspace.py (3)
Line range hint
89-91
: Enhance error handling specificity for IntegrityError.The current error message doesn't distinguish between different types of uniqueness violations. Consider extracting the specific field from the IntegrityError for more precise error messaging.
except IntegrityError as e: - if "already exists" in str(e): + error_message = str(e) + if "slug" in error_message and "already exists" in error_message: return Response( {"slug": "The workspace with the slug already exists"}, status=status.HTTP_410_GONE, ) + return Response( + {"error": "An error occurred while creating the workspace"}, + status=status.HTTP_400_BAD_REQUEST, + )
Line range hint
82-86
: Consider using database transaction for atomic operations.The workspace creation and member creation should be wrapped in a transaction to ensure both operations succeed or fail together.
+from django.db import transaction if serializer.is_valid(raise_exception=True): + with transaction.atomic(): serializer.save(owner=request.user) # Create Workspace member _ = WorkspaceMember.objects.create(
Add validation for company_role field
The company_role field is defined as a TextField in the model with no constraints and is accepted without validation in the serializer. To maintain data quality, you should:
- Add max_length validation in the model to prevent excessively long inputs
- Add validation in the serializer using either CharField with max_length or custom validation method
- Consider adding format validation if there's an expected structure for company roles
Example locations that need changes:
apiserver/plane/db/models/workspace.py
: Update TextField definition with max_lengthapiserver/plane/license/api/serializers/workspace.py
: Add validation rules for company_role🔗 Analysis chain
Line range hint
84-86
: Validate company_role field.The company_role field is accepted without validation. Consider adding length and format validation to prevent potential issues.
Let me check the serializer to see if there are any validations defined there.
Let me check the complete serializer definition to see all fields and their validations.
Let me check the model definition to understand the field constraints at the database level.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check for any existing validation on company_role field rg -A 5 'company_role' --type pyLength of output: 2313
Script:
#!/bin/bash # Check for workspace serializer definitions rg -l "WorkspaceSerializer" --type py | xargs rg -A 10 "class WorkspaceSerializer"Length of output: 1171
Script:
#!/bin/bash # Get the complete workspace serializer definition rg -A 30 "class WorkspaceSerializer" apiserver/plane/license/api/serializers/workspace.pyLength of output: 1032
Script:
#!/bin/bash # Get the complete workspace model definition rg -B 5 -A 10 "company_role = models\." apiserver/plane/db/models/workspace.pyLength of output: 756
admin/core/store/workspace.store.ts (1)
62-65
: Consider adding input validation for better runtime safety.While the type safety improvement is great, consider adding runtime validation since the data might come from external sources (API/storage). This would help catch malformed data early.
Here's a suggested implementation:
hydrate = (data: Record<string, IWorkspace>) => { - if (data) this.workspaces = data; + if (!data) return; + + // Validate the structure of incoming data + Object.entries(data).forEach(([key, workspace]) => { + if (typeof key !== 'string' || !workspace?.id) { + console.warn('Invalid workspace data structure detected:', { key, workspace }); + return; + } + this.workspaces[key] = workspace; + }); };
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (6)
admin/core/components/workspace/list-item.tsx
(1 hunks)admin/core/services/workspace.service.ts
(1 hunks)admin/core/store/workspace.store.ts
(2 hunks)apiserver/plane/license/api/serializers/workspace.py
(1 hunks)apiserver/plane/license/api/views/workspace.py
(1 hunks)packages/ui/src/icons/workspace-icon.tsx
(1 hunks)
🔇 Additional comments (6)
apiserver/plane/license/api/serializers/workspace.py (2)
21-23
: LGTM! Case-insensitive validation is a good addition.
This change prevents confusion and potential conflicts with similarly-cased workspace slugs.
21-23
: Verify existing data for case-insensitive conflicts.
Let's check if there are any existing workspaces that might conflict with the new case-insensitive validation.
✅ Verification successful
Based on the model definition, I can now generate the final response:
Case-insensitive validation is safe to implement
The workspace model already has a unique constraint on the slug
field (unique=True
), and the migration history shows no conflicting constraints. The new case-insensitive validation in the serializer adds an extra layer of validation without risking data integrity since:
- The database-level constraint prevents any duplicates (case-sensitive)
- The new serializer validation prevents case-insensitive duplicates before reaching the database
- The
slug_validator
only checks for restricted slugs, not case sensitivity
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check for existing case-insensitive workspace slug conflicts
# Expected results: No output means no conflicts
# Search for workspace model definition to confirm the fields
rg -l "class Workspace\("
# Search for existing migrations to understand the current schema
fd -e py -p ".*migrations.*workspace.*"
Length of output: 586
Script:
#!/bin/bash
# Let's examine the workspace model and migrations to understand the current schema and constraints
# Check the workspace model definition
cat apiserver/plane/db/models/workspace.py
# Check the migration that alters workspace unique constraints
cat apiserver/plane/db/migrations/0017_alter_workspace_unique_together.py
Length of output: 11742
admin/core/services/workspace.service.ts (1)
33-34
: LGTM! Good improvement using URLSearchParams
The switch to URLSearchParams is a better approach as it:
- Handles URL encoding automatically and safely
- Makes the code more maintainable
- Follows modern JavaScript/TypeScript practices
Let's verify that workspace slugs are properly encoded throughout the codebase:
✅ Verification successful
URLSearchParams is correctly used, no other instances need updating
The codebase scan shows that URL parameter handling is done safely throughout the codebase. The instances found are either:
- Reading parameters from URLs using
params.get()
which is safe - Using template literals in route definitions which don't require encoding
- Using URLSearchParams in API calls where needed
The original review comment's concern about workspace slug encoding has been properly addressed in the changed code, and no other unsafe URL parameter concatenation patterns were found.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check for potential direct string concatenation with workspace slugs
# that might need similar URLSearchParams treatment
# Look for potential unencoded workspace slug usage in URL construction
rg -g '*.{ts,tsx,js,jsx}' -A 3 'workspace.*slug.*\?' --ignore-case
# Look for direct string concatenation in URL construction
ast-grep --pattern 'url + "?" + param'
Length of output: 101337
packages/ui/src/icons/workspace-icon.tsx (1)
6-13
: Great addition of accessibility attributes!
The addition of role="img"
and aria-label improves the accessibility of the icon for screen readers. The new formatting also enhances code readability.
apiserver/plane/license/api/views/workspace.py (1)
Line range hint 13-13
: Verify InstanceAdminPermission implementation.
The endpoint is protected with InstanceAdminPermission. Let's verify its implementation to ensure proper access control.
✅ Verification successful
InstanceAdminPermission implementation is secure and properly configured
The permission class implements proper access control with the following security measures:
- Blocks anonymous users
- Validates against a single instance admin role (20 = "Admin")
- Requires role >= 15 which ensures only admin users can access
- Uses proper model relationships and existence checks
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check the implementation of InstanceAdminPermission
rg -A 10 'class InstanceAdminPermission' --type py
Length of output: 847
Script:
#!/bin/bash
# Check the role field definition and possible values
rg -A 5 'class InstanceAdmin' --type py
Length of output: 4691
Script:
#!/bin/bash
# Check for role field definition and constants
rg -A 5 'role = models\.' --type py
Length of output: 3208
Script:
#!/bin/bash
# Check for ROLE_CHOICES definition in instance related files
rg 'ROLE_CHOICES.*=' apiserver/plane/license/models/instance.py -A 5
Length of output: 407
admin/core/store/workspace.store.ts (1)
17-17
: LGTM! Great type safety improvement.
The change from any
to Record<string, IWorkspace>
enhances type safety by explicitly defining the expected data structure, which matches the store's workspaces
property type.
xmlns="http://www.w3.org/2000/svg" | ||
className={className} | ||
role="img" | ||
aria-abel="Workspace icon" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix typo in aria-label attribute
There's a typo in the accessibility attribute: aria-abel
should be aria-label
.
- aria-abel="Workspace icon"
+ aria-label="Workspace icon"
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
aria-abel="Workspace icon" | |
aria-label="Workspace icon" |
Summary by CodeRabbit
Release Notes
New Features
Bug Fixes
Refactor
Style