Skip to content

fix: Reuse filter endpoints for deployment resource drawer#239

Merged
adityachoudhari26 merged 1 commit intomainfrom
fix--Use-filter-endpoints-in-deployment-resource-drawer
Nov 28, 2024
Merged

fix: Reuse filter endpoints for deployment resource drawer#239
adityachoudhari26 merged 1 commit intomainfrom
fix--Use-filter-endpoints-in-deployment-resource-drawer

Conversation

@adityachoudhari26
Copy link
Copy Markdown
Member

@adityachoudhari26 adityachoudhari26 commented Nov 28, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced filtering logic for job conditions and release data retrieval based on deployment environments.
    • Added optional job filter parameter in the release listing procedure for more granular control over job triggers.
  • Bug Fixes

    • Streamlined invalidation process for release lists across various dialog components.
  • Refactor

    • Updated data structures in components to align with new release data types, ensuring consistent rendering.
  • Chores

    • Removed outdated procedures to simplify API functionality.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Nov 28, 2024

Walkthrough

This pull request introduces significant changes across several components and API routes related to deployment resources and job filtering. Key modifications include updates to the DeploymentResourceDrawer, ReleaseTable, and TableRow components to enhance job filtering logic and data structure alignment with releases. The API routes have been adjusted to remove outdated procedures and incorporate new filtering capabilities for job conditions. Overall, the changes streamline data retrieval and improve the handling of job and release relationships.

Changes

File Change Summary
apps/webservice/src/app/[workspaceSlug]/(app)/_components/deployment-resource-drawer/DeploymentResourceDrawer.tsx Added imports for new types and updated job filter logic, creating a releaseFilter based on releaseChannels. Modified the query for releaseWithTriggersData to use the new filters.
apps/webservice/src/app/[workspaceSlug]/(app)/_components/deployment-resource-drawer/ReleaseTable.tsx Changed the ReleaseWithTriggers type definition to derive from release items instead of job configurations, affecting data structure while keeping component props and rendering logic intact.
apps/webservice/src/app/[workspaceSlug]/(app)/_components/deployment-resource-drawer/TableRow.tsx Updated the Release type definition to reflect the new data structure for releases. Adjusted ReleaseJobTriggerParentRow and ReleaseJobTriggerChildRow components to utilize the updated type while maintaining existing rendering logic.
apps/webservice/src/app/[workspaceSlug]/(app)/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/JobDropdownMenu.tsx Modified mutation handling to invalidate the release list instead of job configurations, ensuring consistency across components.
packages/api/src/router/job.ts Removed the byDeploymentEnvAndResource procedure and related imports. Retained existing procedures while updating byReleaseId to include additional joins for enhanced data retrieval.
packages/api/src/router/release.ts Added an optional jobFilter parameter to the list procedure's input schema, updating the query logic to filter job triggers based on this new parameter. Maintained existing procedures without structural changes.

Possibly related PRs

  • fix: Remove semver and regex release filter #160: The changes in the main PR enhance the filtering logic for job conditions, which is directly related to the modifications made in this PR that also focus on simplifying the release filter handling.
  • fix: Select release channel filter on deployment page #214: The main PR's updates to the DeploymentResourceDrawer component and the introduction of new filtering logic are related to the changes in this PR that enhance the handling of release channels and their filters.
  • fix: Deployment resource drawer #237: The main PR introduces a new component for managing deployment resources, which aligns with the changes in this PR that focus on updating the DeploymentNode to handle deployment environment resources.

Suggested reviewers

  • jsbroks

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 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.

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
Copy Markdown
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: 0

🧹 Outside diff range and nitpick comments (7)
apps/webservice/src/app/[workspaceSlug]/(app)/_components/deployment-resource-drawer/ReleaseTable.tsx (1)

15-15: Add JSDoc documentation for the ReleaseWithTriggers type.

Consider adding JSDoc documentation to explain the type's purpose and structure for better maintainability.

+/**
+ * Represents a release with its associated triggers from the API response.
+ * @typedef {RouterOutputs["release"]["list"]["items"][number]} ReleaseWithTriggers
+ */
 type ReleaseWithTriggers = RouterOutputs["release"]["list"]["items"][number];
packages/api/src/router/release.ts (1)

124-125: Fix formatting: Remove unnecessary newline before orderBy.

The orderBy clause should be on the same line as the previous chain for consistent formatting.

            ),
-          )
-          .orderBy(desc(releaseJobTrigger.createdAt));
+          ).orderBy(desc(releaseJobTrigger.createdAt));
apps/webservice/src/app/[workspaceSlug]/(app)/_components/deployment-resource-drawer/TableRow.tsx (1)

Line range hint 89-157: Enhance accessibility for the links hover card

While the hover card implementation for additional links is visually appealing, consider enhancing keyboard accessibility:

  • Add keyboard navigation support for the hover card
  • Include ARIA labels for better screen reader support
  • Consider adding a tooltip to indicate that more links are available
 <HoverCard>
   <HoverCardTrigger asChild>
-    <Button variant="secondary" size="sm" className="h-6">
+    <Button 
+      variant="secondary" 
+      size="sm" 
+      className="h-6"
+      aria-label={`Show ${remainingLinks.length} more links`}
+      role="button"
+      tabIndex={0}
+    >
       +{remainingLinks.length} more
     </Button>
   </HoverCardTrigger>
   <HoverCardContent
     className="flex max-w-40 flex-col gap-1 p-2"
     align="start"
+    role="menu"
   >
     {remainingLinks.map(([label, url]) => (
       <Link
         key={label}
         href={url}
         target="_blank"
         rel="noopener noreferrer"
-        className="truncate text-sm underline-offset-1 hover:underline"
+        className="truncate text-sm underline-offset-1 hover:underline focus:outline-none focus:ring-2"
+        role="menuitem"
+        tabIndex={0}
       >
         {label}
       </Link>
     ))}
   </HoverCardContent>
 </HoverCard>
apps/webservice/src/app/[workspaceSlug]/(app)/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/JobDropdownMenu.tsx (2)

274-277: Consider adding error handling for failed redeployments.

While the success path is well-handled, there's no error handling for failed redeployments. Consider adding:

  1. Error state UI feedback
  2. Error message display
  3. Error recovery options

Example implementation:

 redeploy
   .mutateAsync({
     environmentId,
     resourceId: target.id,
     releaseId: release.id,
   })
   .then(() => utils.release.list.invalidate())
   .then(() => router.refresh())
   .then(() => setIsOpen(false))
+  .catch((error) => {
+    // Show error message to user
+    console.error('Redeployment failed:', error);
+    // Optionally add a toast notification or error state
+  });

Line range hint 1-394: Well-structured component architecture with consistent patterns.

The file demonstrates good architectural decisions:

  1. Consistent mutation handling patterns across all dialogs
  2. Clear separation of concerns between UI components
  3. Proper state management with controlled dialogs
  4. Thoughtful UX with appropriate confirmations for destructive actions

Consider documenting these patterns in your team's style guide to maintain consistency across the codebase.

apps/webservice/src/app/[workspaceSlug]/(app)/_components/deployment-resource-drawer/DeploymentResourceDrawer.tsx (2)

57-77: Avoid defaulting IDs to empty strings in 'jobFilter'

Since resourceId, environmentId, and deploymentId are guaranteed to be non-null when isOpen is true, defaulting them to empty strings using ?? "" is unnecessary. Using empty strings may lead to unintended API behavior if empty strings are considered valid IDs. Consider using the IDs directly without default values to ensure accurate filtering.

Apply this diff to remove unnecessary default values:

-        value: resourceId ?? "",
+        value: resourceId,

Repeat this change for environmentId and deploymentId:

-        value: environmentId ?? "",
+        value: environmentId,
-        value: deploymentId ?? "",
+        value: deploymentId,

79-86: Avoid defaulting 'deploymentId' to empty string in API query

Since deploymentId is guaranteed to be non-null when isOpen is true, defaulting it to an empty string using ?? "" is unnecessary. Passing an empty string could lead to unintended results or API errors. Use deploymentId directly without defaulting to an empty string.

Apply this diff to update the API query:

-      deploymentId: deploymentId ?? "",
+      deploymentId,
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1ddf9ee and 3d22633.

📒 Files selected for processing (6)
  • apps/webservice/src/app/[workspaceSlug]/(app)/_components/deployment-resource-drawer/DeploymentResourceDrawer.tsx (3 hunks)
  • apps/webservice/src/app/[workspaceSlug]/(app)/_components/deployment-resource-drawer/ReleaseTable.tsx (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/(app)/_components/deployment-resource-drawer/TableRow.tsx (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/(app)/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/JobDropdownMenu.tsx (3 hunks)
  • packages/api/src/router/job.ts (0 hunks)
  • packages/api/src/router/release.ts (4 hunks)
💤 Files with no reviewable changes (1)
  • packages/api/src/router/job.ts
🧰 Additional context used
📓 Learnings (1)
packages/api/src/router/release.ts (1)
Learnt from: adityachoudhari26
PR: ctrlplanedev/ctrlplane#237
File: packages/api/src/router/job.ts:362-365
Timestamp: 2024-11-27T23:18:42.055Z
Learning: In the file `packages/api/src/router/job.ts`, the function `releaseMatchesCondition` returns undefined if the `filter` parameter is null. This behavior ensures that when constructing the query with `and(...)`, the condition is omitted, allowing the query to function correctly even if there is no release channel associated with the environment.
🔇 Additional comments (12)
apps/webservice/src/app/[workspaceSlug]/(app)/_components/deployment-resource-drawer/ReleaseTable.tsx (1)

15-15: Verify the type change impact across the codebase.

The type change from job-based to release-based structure looks good and aligns with the PR objective. However, let's ensure all consumers are updated accordingly.

✅ Verification successful

Type change is isolated and properly contained

The type ReleaseWithTriggers is only used within the ReleaseTable.tsx component and its props, with no other components depending on this type. Additionally, there are no traces of the old job-based type structure in the codebase, suggesting the migration is complete and consistent.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all components that might be affected by the ReleaseWithTriggers type change

# Search for components using ReleaseWithTriggers type
echo "Components using ReleaseWithTriggers type:"
rg -t typescript -t tsx "ReleaseWithTriggers" ./apps/webservice/src

# Search for potential job config usage that might need updating
echo -e "\nPotential outdated job config usage:"
rg -t typescript -t tsx "RouterOutputs\[\"job\"\]\[\"config\"\]\[\"byDeploymentEnvAndResource\"\]" ./apps/webservice/src

Length of output: 438


Script:

#!/bin/bash
# Let's try without file type filters since they're not recognized
# Search for components using ReleaseWithTriggers type
echo "Components using ReleaseWithTriggers type:"
rg "ReleaseWithTriggers" ./apps/webservice/src

# Search for potential job config usage that might need updating
echo -e "\nPotential outdated job config usage:"
rg "RouterOutputs\[\"job\"\]\[\"config\"\]\[\"byDeploymentEnvAndResource\"\]" ./apps/webservice/src

# Also search for simpler patterns that might indicate usage
echo -e "\nSimpler job config pattern search:"
rg "\"job\"\]\[\"config\"\]\[\"byDeploymentEnvAndResource\"" ./apps/webservice/src

Length of output: 823

packages/api/src/router/release.ts (4)

24-24: LGTM: Import additions are appropriate.

The new imports for job filtering functionality are correctly placed and follow the existing import pattern.

Also applies to: 42-42


61-61: LGTM: Input schema extension is well-structured.

The addition of the optional jobFilter parameter maintains type safety and aligns with the PR objective to reuse filter endpoints.


116-116: LGTM: Job filtering logic is correctly implemented.

The jobMatchesCondition is properly integrated into the resource join conditions, maintaining consistent behavior with other filters.


61-61: Verify consistent filter implementation across endpoints.

Let's verify if there are other endpoints that might benefit from the same job filtering capability for consistency.

Also applies to: 116-116

✅ Verification successful

Filter implementation is consistent across endpoints

The verification shows that the job filtering implementation is consistent with the existing patterns in the codebase:

  • The jobFilter is properly implemented in release.ts using jobCondition.optional()
  • Similar filter patterns are already present in other routers:
    • job.ts uses filter: jobCondition.optional()
    • resources.ts uses filter: resourceCondition.optional()
    • All filters follow the same optional condition pattern with consistent pagination parameters
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find similar router endpoints that might need job filtering

# Look for similar list procedures in router files
echo "Looking for similar list procedures in router files..."
rg -A 5 "list:\s+.*procedure" "packages/api/src/router"

# Look for jobFilter usage in other files
echo "Checking jobFilter usage across the codebase..."
rg "jobFilter" --type typescript

Length of output: 347


Script:

#!/bin/bash
# Let's try a different approach to find similar endpoints and job filter usage

# Look for similar list procedures in router files without file type restriction
echo "Looking for similar list procedures in router files..."
rg -A 5 "list:\s+.*procedure" packages/api/src/router/

# Search for jobFilter usage without file type restriction
echo "Checking jobFilter usage..."
rg "jobFilter" packages/api/src/

# Look for similar filter patterns in router files
echo "Looking for similar filter patterns..."
rg -A 3 "filter.*optional\(\)" packages/api/src/

Length of output: 1896

apps/webservice/src/app/[workspaceSlug]/(app)/_components/deployment-resource-drawer/TableRow.tsx (2)

Line range hint 358-391: Well-structured implementation of collapsible release rows

The ReleaseRows component effectively manages the display of multiple job triggers with a clean parent-child pattern. The implementation:

  • Handles all states gracefully (no triggers, single trigger, multiple triggers)
  • Uses proper React patterns for state management
  • Maintains clear separation of concerns

352-352: Verify type compatibility with the new Release structure

The change from job config to release list output type is a significant architectural shift. While the implementation looks correct, we should verify that all properties accessed from the Release type are available in the new structure.

✅ Verification successful

Type compatibility verified - no issues found

The verification shows that the properties accessed from the Release type (id, name) are basic properties that are commonly available in API responses. All usages are consistent and focus on fundamental properties that would be present in any release entity. The migration from job config to release list output appears to be safe as the accessed properties are standard identifiers and naming fields.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all properties accessed from Release type exist in the new structure
# Look for any potential type mismatches or missing properties

# Search for all properties accessed from release objects
echo "Properties accessed from release:"
rg -A 1 'release\.' apps/webservice/src/app/[workspaceSlug]/(app)/_components/deployment-resource-drawer/

# Search for the type definition to compare
echo "Release type definition:"
rg 'type.*Release.*=.*RouterOutputs' apps/webservice/src/app/[workspaceSlug]/(app)/_components/deployment-resource-drawer/

Length of output: 365


Script:

#!/bin/bash
# Let's try a different approach by escaping the special characters in the path
# and using more specific patterns to find release property access

# Search for all properties accessed from release objects
echo "Properties accessed from release:"
rg -A 1 'release\.' "apps/webservice/src/app/\[workspaceSlug\]/\(app\)/_components/deployment-resource-drawer/TableRow.tsx"

# Search for the type definition
echo "Release type definition:"
rg 'type.*Release.*=.*RouterOutputs' "apps/webservice/src/app/\[workspaceSlug\]/\(app\)/_components/deployment-resource-drawer/TableRow.tsx"

# Let's also try to find any usage of Release type
echo "Usage of Release type:"
rg ':\s*Release[\[\]\s{},]' "apps/webservice/src/app/\[workspaceSlug\]/\(app\)/_components/deployment-resource-drawer/TableRow.tsx"

Length of output: 1019


Script:

#!/bin/bash
# Let's try using fd to find the correct path first, then use it for our searches

# Find the correct path for TableRow.tsx
echo "Finding TableRow.tsx:"
fd "TableRow.tsx" --type f

# Once we find the file, we'll use its path to search for release properties
# and type definitions using a variable to store the path
FILE_PATH=$(fd "TableRow.tsx" --type f)
if [ ! -z "$FILE_PATH" ]; then
    echo -e "\nProperties accessed from release:"
    rg -A 1 'release\.' "$FILE_PATH"
    
    echo -e "\nRelease type definition:"
    rg 'type.*Release.*=.*RouterOutputs' "$FILE_PATH"
    
    echo -e "\nUsage of Release type:"
    rg ':\s*Release[\[\]\s{},]' "$FILE_PATH"
fi

Length of output: 1927

apps/webservice/src/app/[workspaceSlug]/(app)/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/JobDropdownMenu.tsx (2)

94-94: LGTM: Appropriate cache invalidation sequence.

The addition of release list invalidation maintains data consistency after job status changes. The sequence of invalidations is logical, ensuring both job-specific and release-level caches are properly updated.


223-226: LGTM: Well-structured mutation handling with good UX.

The promise chain appropriately updates the UI state after force release:

  1. Invalidates the release list to reflect changes
  2. Refreshes the router for navigation updates
  3. Closes dialogs for a clean user experience
apps/webservice/src/app/[workspaceSlug]/(app)/_components/deployment-resource-drawer/DeploymentResourceDrawer.tsx (3)

3-3: Approved: Imported 'JobCondition' from '@ctrlplane/validators/jobs'

The import of JobCondition is necessary for defining the jobFilter used in the component.


12-17: Approved: Imported necessary filter types and operators

The imports of ColumnOperator, ComparisonOperator, FilterType, and JobFilterType are essential for constructing the filtering logic.


49-56: Handle potential null values when constructing 'releaseFilter'

The current logic for releaseFilter might return undefined if no matching release channel is found. Ensure that the API can handle an undefined filter gracefully. Consider adding a default or fallback filter if necessary to prevent unexpected behavior.

@adityachoudhari26 adityachoudhari26 merged commit b136e7d into main Nov 28, 2024
@adityachoudhari26 adityachoudhari26 deleted the fix--Use-filter-endpoints-in-deployment-resource-drawer branch November 28, 2024 00:59
This was referenced Mar 25, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants