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

fix: Release dependencies refactor #165

Merged
merged 15 commits into from
Oct 24, 2024

Conversation

adityachoudhari26
Copy link
Contributor

@adityachoudhari26 adityachoudhari26 commented Oct 23, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new visual representation for target dependencies with the TargetDiagramDependencies component.
    • Enhanced the JobDrawer to conditionally render job dependencies and integrate new components for better visual representation.
    • Added a new DepEdge component to represent dependency edges in the diagram.
    • Implemented a new TargetNode component for visualizing nodes in the target diagram.
  • Improvements

    • Streamlined release dependency management with a new releaseFilter field for better validation.
    • Improved layout and styling across various components for better user experience.
    • Enhanced error handling and validation in API routes and forms.
    • Updated SQL query logic for improved flexibility in the deployment router.
  • Bug Fixes

    • Resolved issues with unique deployment IDs in release dependencies.
    • Improved error handling in the API for better context during debugging.

Copy link
Contributor

coderabbitai bot commented Oct 23, 2024

Walkthrough

This pull request introduces significant changes across various components and files, primarily focusing on the management and validation of release dependencies. Key modifications include the restructuring of the CreateRelease.tsx component, the introduction of new components for visualizing relationships, and updates to API routers for enhanced data handling. The changes also involve adjustments to database schemas and SQL queries, streamlining the overall logic and improving clarity in how release dependencies are processed and represented.

Changes

File Change Summary
apps/webservice/src/app/[workspaceSlug]/_components/CreateRelease.tsx Updated releaseDependency schema to replace targetMetadataGroupId, rule, and ruleType with releaseFilter. Simplified UI layout and introduced ReleaseConditionDialog. Enhanced error handling for deployment IDs.
apps/webservice/src/app/[workspaceSlug]/_components/reactflow/layout.ts Added nodesep parameter to getLayoutedElementsDagre function to control node separation in layout graphs.
apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/TargetDrawer.tsx Adjusted layout and styling for height properties of <div> elements in TargetDrawer.
apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/relationships/RelationshipContent.tsx Modified layout and styling of RelationshipsContent. Changed outer div class and adjusted inner Card height.
apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/relationships/RelationshipsDiagram.tsx Removed TargetNode and DepEdge components. Updated TargetDiagram props to include relationships and targets. Changed layout direction to "BT".
apps/webservice/src/app/[workspaceSlug]/dependencies/DependencyDiagram.tsx Updated edge labels in DeploymentNode from d.rule to d.releaseFilter.type.
packages/api/src/router/release.ts Refactored create mutation to improve clarity in handling release dependencies. Added bySystem and byWorkspace procedures for metadata access.
packages/api/src/router/target.ts Consolidated recursive CTE logic in hierarchy procedure for retrieving target relationships, simplifying SQL queries.
packages/db/src/schema/release.ts Updated release_dependency table to remove certain fields and add releaseFilter field. Adjusted unique index definition.
packages/db/src/schema/target.ts Modified target_relationship table structure and updated targetRelationshipType enum.
packages/job-dispatch/src/policies/release-dependency.ts Simplified logic in isPassingReleaseDependencyPolicy by replacing left joins with inner joins and introducing a recursive CTE for evaluating dependencies.
packages/job-dispatch/src/policy-checker.ts Added isPassingReleaseDependencyPolicy check to isPassingAllPolicies function, indicating a reordering of checks.
packages/job-dispatch/src/policy-create.ts Changed conflict handling in createJobApprovals to onConflictDoNothing(), altering control flow during record insertion.
apps/webservice/src/app/[workspaceSlug]/_components/job-drawer/JobDrawer.tsx Introduced ReactFlowProvider and Card imports. Updated structure to conditionally render TargetDiagramDependencies.
apps/webservice/src/app/api/v1/workspaces/[workspaceId]/targets/route.ts Enhanced validation logic for unique variable keys and improved request body parsing for YAML and JSON formats.
packages/api/src/router/job.ts Integrated ReleaseDependency type into processReleaseJobTriggerWithAdditionalDataRows function and updated byId method to enrich data retrieval for release job triggers.
packages/db/drizzle/meta/_journal.json Added a new entry to the journal for database versioning.
apps/webservice/src/app/[workspaceSlug]/_components/job-drawer/RelationshipsDiagramDependencies.tsx Introduced TargetDiagramDependencies component for visualizing relationships using React Flow.
apps/webservice/src/app/[workspaceSlug]/_components/relationships/DepEdge.tsx Added DepEdge component for rendering edges in the relationship diagram.
apps/webservice/src/app/[workspaceSlug]/_components/relationships/TargetNode.tsx Added TargetNode component to represent nodes in the flow diagram.
apps/webservice/src/app/[workspaceSlug]/_components/targets/getBorderColor.tsx Introduced getBorderColor function to determine node border colors based on version and kind.
packages/api/src/router/deployment.ts Updated SQL query syntax in distributionById procedure for improved flexibility with dynamic variable interpolation.
packages/db/drizzle/0022_clean_wrecking_crew.sql SQL migration script adds new enum value, modifies release_dependency and target_relationship tables, and creates a unique index for release_dependency.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CreateRelease
    participant API
    participant Database

    User->>CreateRelease: Submit release details
    CreateRelease->>API: Validate and send release dependencies
    API->>Database: Insert release dependencies
    Database-->>API: Confirm insertion
    API-->>CreateRelease: Return success response
    CreateRelease-->>User: Display success message
Loading

Possibly related PRs

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
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: 12

🧹 Outside diff range and nitpick comments (15)
apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/relationships/RelationshipContent.tsx (1)

11-15: LGTM! Consider improving accessibility.

The layout changes look good with proper height cascading and consistent spacing. However, consider making the "Hierarchy" label more semantic.

Consider this improvement:

-      <div>Hierarchy</div>
+      <h3 className="text-sm font-medium">Hierarchy</h3>
packages/job-dispatch/src/new-target.ts (1)

22-24: LGTM! Clean architectural improvement.

The simplified filter chain improves code organization by centralizing dependency checks. The function maintains its clear single responsibility of dispatching jobs for new targets.

This refactor aligns well with separation of concerns, moving dependency validation to a more appropriate layer in the architecture.

packages/db/drizzle/0020_daffy_azazel.sql (1)

1-11: Consider splitting this migration for safer deployment.

This migration combines multiple schema changes including enum modifications, constraint changes, and column additions/removals. Consider:

  1. Splitting this into multiple migrations that can be deployed separately
  2. Adding intermediate states to maintain backward compatibility during deployment
  3. Including a rollback strategy in case of issues

This would make the changes easier to manage and safer to deploy.

packages/job-dispatch/src/policy-create.ts (1)

47-49: Document the conflict handling behavior.

The conflict handling strategy is a critical business logic decision. Consider adding a comment explaining why conflicts are ignored rather than updating existing records.

   .insert(environmentPolicyApproval)
   .values(
     policiesToCheck.map((p) => ({
       policyId: p.environment_policy.id,
       releaseId: p.release.id,
     })),
   )
+  // Preserve existing approval records to maintain their state and avoid
+  // accidental overwrites during concurrent operations
   .onConflictDoNothing();
packages/job-dispatch/src/policy-checker.ts (1)

Line range hint 21-29: Consider documenting the policy check ordering rationale.

The sequence of policy checks is crucial for both correctness and performance. Consider adding a comment explaining why checks are ordered this way, particularly noting any dependencies between checks and performance considerations.

  const checks: ReleaseIdPolicyChecker[] = [
+   // Order of checks is important for both correctness and performance:
+   // 1. Quick-fail checks (locking, approval) come first
+   // 2. Database-intensive checks (dependencies) follow
+   // 3. Complex calculation checks (rollout, window) come last
    isPassingLockingPolicy,
    isPassingApprovalPolicy,
    isPassingCriteriaPolicy,
    isPassingConcurrencyPolicy,
    isPassingReleaseDependencyPolicy,
    isPassingJobRolloutPolicy,
    isPassingNoActiveJobsPolicy,
    isPassingReleaseWindowPolicy,
  ];
apps/webservice/src/app/[workspaceSlug]/_components/reactflow/layout.ts (1)

38-41: Consider adding JSDoc and type improvements.

The function would benefit from:

  1. JSDoc documentation explaining the purpose and impact of the nodesep parameter
  2. Using a more specific type for the direction parameter instead of string literal

Consider applying these improvements:

+/** Parameters for graph layout configuration */
+type Direction = 'TB' | 'BT' | 'LR' | 'RL';
+
+/**
+ * Calculates the layout for nodes and edges in a directed graph
+ * @param nodes - The nodes to layout
+ * @param edges - The edges connecting the nodes
+ * @param direction - The direction of the graph layout (TB: top-bottom, LR: left-right, etc.)
+ * @param extraEdgeLength - Additional length to add to edges based on node levels
+ * @param nodesep - The separation between nodes in the graph (in pixels)
+ * @returns The nodes with calculated positions and the original edges
+ */
 export const getLayoutedElementsDagre = (
   nodes: Node[],
   edges: Edge[],
-  direction = "TB",
+  direction: Direction = "TB",
   extraEdgeLength = 0,
   nodesep = 50,
 ) => {
apps/webservice/src/app/[workspaceSlug]/dependencies/DependencyDiagram.tsx (2)

Line range hint 171-177: Add error handling for edge label creation.

The edge creation logic should handle cases where releaseFilter or type might be undefined.

Consider adding a fallback:

 {
   id: d.id,
-  label: d.releaseFilter.type,
+  label: d.releaseFilter?.type ?? 'unknown',
   target: d.deploymentId,
   source: data.id,
   animated: true,
 }

Line range hint 166-190: Optimize useEffect dependencies and layout timing.

The current implementation has several potential improvements:

  1. The sleep timeout of 200ms seems arbitrary and could be insufficient on slower devices
  2. The useEffect dependencies could trigger unnecessary re-renders

Consider these improvements:

- useEffect(() => {
+ useEffect(() => {
+  const updateEdges = async () => {
     if (release == null) return;
     const deps = release.releaseDependencies.filter(isPresent);
     if (data.latestRelease == null) return;
 
     const edges = getEdges().filter((e) => e.source !== data.id);
 
     const newEdges = deps.map((d) => ({
       id: d.id,
       label: d.releaseFilter?.type ?? 'unknown',
       target: d.deploymentId,
       source: data.id,
       animated: true,
       markerEnd: { type: MarkerType.Arrow, color: colors.neutral[500] },
       style: { stroke: colors.neutral[500] },
     }));
 
     setEdges([...edges, ...newEdges]);
-    window.requestAnimationFrame(() => {
-      sleep(200).then(onLayout);
-    });
+    // Wait for the next frame to ensure edges are rendered
+    await new Promise(resolve => requestAnimationFrame(resolve));
+    // Wait for the layout to stabilize
+    await new Promise(resolve => setTimeout(resolve, 50));
+    onLayout();
+  };
+
+  void updateEdges();
 
-  }, [release, onLayout]);
+  }, [release, data.id, data.latestRelease]);
packages/api/src/router/release.ts (1)

Line range hint 479-530: LGTM! Consider performance optimizations for scale.

The implementation of metadataKeys router with bySystem and byWorkspace procedures is well-structured with proper authorization checks and efficient joins. However, consider these optimizations for scale:

  1. Add caching for frequently accessed metadata keys
  2. Implement pagination to handle systems/workspaces with many metadata keys
packages/job-dispatch/src/policies/release-dependency.ts (1)

6-8: Remove Unused Imports to Clean Up Code

If any of the imported modules (and, eq, inArray, sql, JobStatus) are not used elsewhere in the code, consider removing them to keep the codebase clean.

apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/relationships/RelationshipsDiagram.tsx (2)

3-3: Prefer Specific Type Imports Over Wildcard Imports

Importing all types with * as schema can include unnecessary types and reduce code clarity. Consider importing only the specific types you need.

Apply this diff:

-import type * as schema from "@ctrlplane/db/schema";
+import type { Target, TargetRelationship } from "@ctrlplane/db/schema";

281-284: Provide Feedback When Data Is Unavailable

Returning null when hierarchy.data is null may lead to a blank component. Consider providing a loading indicator or handling potential errors to enhance user experience.

Apply this diff:

-if (hierarchy.data == null) return null;
+if (hierarchy.isLoading) return <div>Loading...</div>;
+if (hierarchy.isError) return <div>Error loading data.</div>;
apps/webservice/src/app/[workspaceSlug]/_components/CreateRelease.tsx (2)

236-240: Include a hyperlink for 'Read more about release dependencies'

The sentence "Read more about release dependencies here." suggests that a link should be provided for users to access additional information. Consider adding a hyperlink to guide users to the relevant documentation.

Apply this diff to include the link:

                   <span className="text-sm text-muted-foreground">
                     Dependencies must be fulfilled for a target before this Release
                     can be applied to that target. Read more about release
-                    dependencies here.
+                    dependencies <a href="URL_TO_DOCUMENTATION">here</a>.
                   </span>

Replace 'URL_TO_DOCUMENTATION' with the actual URL.


294-301: Add an accessible label to the remove button

To improve accessibility, consider adding an aria-label or title to the remove button so that screen readers can convey its purpose to users.

Apply this diff to add an aria-label:

                       <Button
                         variant="ghost"
                         size="icon"
                         onClick={() => remove(index)}
+                        aria-label="Remove dependency"
                       >
packages/api/src/router/target.ts (1)

470-512: Consider removing the large block of commented-out code

The commented-out code from lines 470-512 may no longer be necessary. Large blocks of commented code can clutter the codebase and reduce readability. If this code is not needed, consider removing it. If it's kept for reference, consider documenting its purpose more clearly.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2899756 and 2b97918.

📒 Files selected for processing (18)
  • apps/webservice/src/app/[workspaceSlug]/_components/CreateRelease.tsx (4 hunks)
  • apps/webservice/src/app/[workspaceSlug]/_components/reactflow/layout.ts (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/TargetDrawer.tsx (2 hunks)
  • apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/relationships/RelationshipContent.tsx (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/relationships/RelationshipsDiagram.tsx (9 hunks)
  • apps/webservice/src/app/[workspaceSlug]/dependencies/DependencyDiagram.tsx (1 hunks)
  • packages/api/src/router/release.ts (1 hunks)
  • packages/api/src/router/target.ts (3 hunks)
  • packages/db/drizzle/0020_daffy_azazel.sql (1 hunks)
  • packages/db/drizzle/0021_previous_sharon_ventura.sql (1 hunks)
  • packages/db/drizzle/meta/_journal.json (1 hunks)
  • packages/db/src/schema/release.ts (2 hunks)
  • packages/db/src/schema/target.ts (2 hunks)
  • packages/job-dispatch/src/index.ts (0 hunks)
  • packages/job-dispatch/src/new-target.ts (1 hunks)
  • packages/job-dispatch/src/policies/release-dependency.ts (1 hunks)
  • packages/job-dispatch/src/policy-checker.ts (1 hunks)
  • packages/job-dispatch/src/policy-create.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/job-dispatch/src/index.ts
🧰 Additional context used
🪛 Biome
apps/webservice/src/app/[workspaceSlug]/_components/CreateRelease.tsx

[error] 243-243: Missing key property for this element in iterable.

The order of the items may change, and having a key can help React identify which item was moved.
Check the React documentation.

(lint/correctness/useJsxKeyInIterable)

🔇 Additional comments (24)
packages/db/drizzle/0021_previous_sharon_ventura.sql (2)

1-1: LGTM: Primary key addition looks good.

The use of gen_random_uuid() for automatic UUID generation and NOT NULL constraint is a solid approach for the primary key.


1-2: Verify foreign key constraints before dropping the uuid column.

While the migration looks correct, we should verify that no other tables have foreign key constraints referencing the uuid column before dropping it.

Let's check for potential foreign key dependencies:

✅ Verification successful

Let me try a different approach to verify foreign key dependencies.

This will help us understand:

  1. The overall schema context around target_relationship table
  2. Any potential relationships defined in the TypeScript code
  3. Other migrations that might have set up or modified foreign key constraints

Based on the search results, I can now provide a final response as we have sufficient information about the table structure and its relationships.

The uuid column can be safely dropped

The search results show that:

  1. The uuid column was not used as a primary key or in any foreign key constraints. The foreign key constraints (target_relationship_source_id_target_id_fk and target_relationship_target_id_target_id_fk) reference the source_id and target_id columns instead.
  2. The unique index on the table uses target_id and source_id columns, not the uuid column.
  3. The uuid column was originally created without any constraints in migration 0009.
  4. No other tables have foreign key constraints referencing the target_relationship.uuid column.

Therefore, replacing the uuid column with a new id column as the primary key is a safe operation and won't cause any data integrity issues.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for foreign key constraints referencing the uuid column in target_relationship table

# Look for CREATE TABLE statements that might reference target_relationship(uuid)
rg -A 10 "CREATE TABLE.*FOREIGN KEY.*target_relationship.*uuid" --type sql

# Look for ALTER TABLE statements adding foreign keys
rg "ALTER TABLE.*FOREIGN KEY.*target_relationship.*uuid" --type sql

Length of output: 146


Script:

#!/bin/bash
# Search for any SQL files that mention target_relationship table
rg -B 5 -A 5 "target_relationship" --type sql

# Also look for schema definitions in TypeScript files that might show relationships
rg -B 3 -A 3 "target_relationship" --type typescript

Length of output: 6704

apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/relationships/RelationshipContent.tsx (1)

11-15: Verify height calculations in parent containers.

The component uses percentage-based height (h-[90%]) which requires parent containers to have explicit heights. The current setup with h-full should work, but verify this renders correctly in all contexts.

✅ Verification successful

Let me gather more information about the height-related setup in the parent containers.


Let me try one more search to find the Sheet component and drawer-related height setup.


Based on the gathered information, I can now provide a final response:

Height setup in parent containers is properly configured

The height calculations for the RelationshipContent component with h-[90%] are properly supported by its parent containers:

  • The main drawer has h-screen class
  • The content wrapper has h-full w-full classes
  • The tab content container also has h-full w-full classes

This creates a proper height chain from the viewport down to the component, ensuring the percentage-based height will work as expected.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for proper height setup in parent containers
# Look for parent components that might affect the height calculations

# Search for components that render RelationshipsContent
ast-grep --pattern 'RelationshipsContent'

# Search for drawer or modal components that might contain this
rg -l "target-drawer" --type tsx

Length of output: 560


Script:

#!/bin/bash
# Search for TargetDrawer component implementation and its height setup
ast-grep --pattern 'const TargetDrawer = $$$'

# Search for height-related classes in the target drawer components
rg "h-\[" apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/

# Look for any Drawer or Sheet component usage that might affect height
ast-grep --pattern 'Sheet.$$$'

Length of output: 22824


Script:

#!/bin/bash
# Search for Sheet component usage in the target drawer
rg -A 5 "Sheet" apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/

# Look for any height-related styles in the drawer component
rg "className.*h-" apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/TargetDrawer.tsx

Length of output: 913

packages/job-dispatch/src/new-target.ts (1)

23-23: Verify dependency policy integration in the new location.

The removal of isPassingReleaseDependencyPolicy from this filter chain appears to be part of a larger architectural change. Let's verify that dependency checks are properly integrated in the new location.

✅ Verification successful

Let me try a different search strategy to verify the dependency policy integration.


Let me check the content of the policy-checker.ts file since it appears to be the main file handling the dependency policies.


Based on the comprehensive results, I can now provide the final response:

Release dependency checks are properly integrated in the centralized policy checker

The removal of isPassingReleaseDependencyPolicy from the direct filter chain in new-target.ts is correct as the dependency checks are now properly handled in the centralized isPassingAllPolicies function in policy-checker.ts. Specifically:

  • The dependency policy is included in the array of checks: isPassingReleaseDependencyPolicy is part of the checks array in isPassingAllPolicies
  • The implementation in release-dependency.ts shows a thorough dependency validation including:
    • Recursive relationship checking
    • Deployment status verification
    • Proper job status validation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the integration of release dependency policy checks
# Expected: Find where the dependency checks are now handled

# Check for the dependency policy usage in policy-checker.ts
echo "Checking policy-checker.ts for dependency policy integration:"
rg -A 5 "isPassingAllPolicies.*isPassingReleaseDependencyPolicy" 

# Verify the implementation of the new dependency check
echo -e "\nChecking the new implementation:"
rg -A 10 "isPassingReleaseDependencyPolicy.*CTE" 

Length of output: 331


Script:

#!/bin/bash
# Search for any occurrence of dependency policy related functions
echo "Searching for dependency policy functions:"
rg -l "ReleaseDependencyPolicy"

# Search for policy-related files
echo -e "\nSearching for policy files:"
fd "policy" --type f

# Look for the implementation of isPassingAllPolicies
echo -e "\nSearching for isPassingAllPolicies implementation:"
ast-grep --pattern 'function isPassingAllPolicies($_) {
  $$$
}'

# Search for any policy-related imports in new-target.ts
echo -e "\nChecking policy imports in new-target.ts:"
rg "import.*Policy" "packages/job-dispatch/src/new-target.ts"

Length of output: 1411


Script:

#!/bin/bash
# Check the content of policy-checker.ts
echo "Content of policy-checker.ts:"
cat packages/job-dispatch/src/policy-checker.ts

# Check the content of release-dependency.ts
echo -e "\nContent of release-dependency.ts:"
cat packages/job-dispatch/src/policies/release-dependency.ts

# Look for where these policies are being used
echo -e "\nUsage of policies:"
rg -A 5 "isPassingReleaseDependencyPolicy|isPassingAllPolicies" --type ts

Length of output: 14571

packages/db/drizzle/0020_daffy_azazel.sql (3)

2-4: LGTM! Proper cleanup sequence.

The constraints and indexes are dropped in the correct order before removing the related columns.


8-11: LGTM! Safe column removal.

The columns are dropped safely with IF EXISTS clauses, and the order of operations is correct (constraints and indexes are dropped before the columns).


1-1: Verify the removal of 'created_by' enum value.

The summary mentions removing 'created_by' from targetRelationshipType, but this migration only adds 'associated_with'. Please ensure there are no existing records using 'created_by' before removing it.

packages/job-dispatch/src/policy-create.ts (1)

48-48: Verify the impact of preserving existing approval records.

The change from onConflictDoUpdate to onConflictDoNothing means existing approval records will never be overwritten. While this prevents accidental state changes, please verify:

  1. This aligns with the business requirements for approval workflow
  2. There are no scenarios where re-triggering approvals is necessary
  3. Error recovery and retry mechanisms are not impacted
✅ Verification successful

Let me gather more specific information about the approval handling logic to better understand the implications of this change.

This will help us understand:

  1. How approvals are created and handled throughout the codebase
  2. The status transitions and conflict handling patterns
  3. Other database operations related to approvals

Based on the gathered information, I can now provide a final response as there's sufficient evidence to understand the approval handling in the codebase.

Change to onConflictDoNothing is correct and safe

The change from onConflictDoUpdate to onConflictDoNothing is verified to be the right approach because:

  1. The schema (packages/db/src/schema/environment.ts) shows approvals have a well-defined status enum ("pending", "approved") with "pending" as the default state
  2. The approval status is checked in manual approval policies (packages/job-dispatch/src/policies/manual-approval.ts) only for "approved" state
  3. The createJobApprovals function is called in multiple places (release routes, config routes) but always as part of a new release flow
  4. No retry mechanisms or error recovery patterns were found that depend on recreating or updating existing approvals

This change ensures that:

  • New releases create fresh approval records
  • Existing approval decisions are preserved
  • No accidental state resets occur
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for retry mechanisms or error handlers that might depend on recreating approvals
rg -l 'retry|recover|error.*approval|approval.*error' --type ts

# Look for tests that verify approval behavior
rg -l 'test.*approval|approval.*test' --type ts

Length of output: 208


Script:

#!/bin/bash
# Look for approval-related code patterns
ast-grep --pattern 'createJobApprovals'

# Search for approval status handling
rg -B 2 -A 2 'approval.*status|status.*approval' --type ts

# Look for specific conflict handling patterns
rg -B 2 -A 2 'onConflict' --type ts

# Check for any approval-related database operations
rg -B 2 -A 2 'insert.*approval|update.*approval' --type ts

Length of output: 8843

packages/job-dispatch/src/policy-checker.ts (1)

25-25: Verify policy check ordering dependencies.

The relocation of isPassingReleaseDependencyPolicy earlier in the sequence appears beneficial for performance. However, let's verify there are no implicit ordering dependencies between the checks.

✅ Verification successful

The search results show no explicit ordering dependencies between policies. Let's verify the policy checker's implementation to understand how these policies are composed and if there are any implicit dependencies in the implementation.


Based on the results, I can now generate the final response as we have sufficient evidence:

Moving isPassingReleaseDependencyPolicy is safe and beneficial

The implementation shows that:

  1. Each policy check is independent and takes the same parameters (db and releaseJobTriggers)
  2. Policies are applied sequentially through a simple loop that passes filtered results forward
  3. No policy function depends on the results of other policy checks
  4. Each check is pure in terms of policy evaluation, only filtering the input array

The reordering is safe as there are no ordering dependencies between the checks. Moving the dependency check earlier is a valid optimization that can prevent unnecessary policy evaluations for jobs that would fail the dependency check anyway.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for any comments or documentation that might indicate required ordering
# between policy checks, particularly focusing on dependency relationships with other checks.

# Test 1: Look for ordering-related comments in policy files
echo "Searching for ordering-related comments in policy files..."
rg -i "must|should|before|after|depend" "packages/job-dispatch/src/policies/"

# Test 2: Check policy files for shared state or cross-policy dependencies
echo "Checking for cross-policy dependencies..."
ast-grep --pattern 'import { $_ } from "./policies/$_"'

Length of output: 1682


Script:

#!/bin/bash
# Check the policy checker implementation to understand how policies are composed
echo "Checking policy checker implementation..."
rg -A 10 "isPassingReleaseDependencyPolicy" packages/job-dispatch/src/policy-checker.ts

# Check if any policy functions take other policy results as input
echo "Checking policy function signatures..."
ast-grep --pattern 'export const $_ = async ($$$) => {'

Length of output: 1146

apps/webservice/src/app/[workspaceSlug]/_components/reactflow/layout.ts (2)

39-39: LGTM: Good default value for node separation.

The addition of the nodesep parameter with a default value of 50 provides good flexibility while maintaining backward compatibility.


43-43: Verify the impact of nodesep on existing diagrams.

The change to include nodesep in the graph configuration looks correct. However, since this affects the visual layout of dependency diagrams, it's important to verify that the default value of 50 works well with existing diagrams.

Let's check for any existing test files or snapshots that might need updating:

✅ Verification successful

Let me try a different approach to gather more context about the usage and impact of this layout configuration.


Let me check the actual usage of this layout configuration in the files that import it to understand the impact better.


Based on the search results, I can now provide a final response:

The nodesep parameter is already being used appropriately across different diagrams

The codebase shows that different components are already using various nodesep values based on their specific needs:

  • RelationshipsDiagram uses nodesep: 50 (matches the default)
  • DependencyDiagram uses nodesep: 100 for wider spacing
  • EnvFlowBuilder uses default spacing
  • FlowDiagram uses default spacing

The default value of 50 is appropriate as it:

  1. Matches existing usage in RelationshipsDiagram
  2. Provides a reasonable baseline that components can override when needed (as seen in DependencyDiagram)
  3. Works well with different layout directions (LR, TB, BT) used across components
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Look for test files related to the dependency diagram layout
# to ensure they account for the new node separation parameter

# Search for test files related to the layout
rg -l "getLayoutedElementsDagre" --glob "**/*.test.*" --glob "**/*.spec.*"

# Search for snapshot files that might contain diagram layouts
fd -e snap -e snapshot

Length of output: 99


Script:

#!/bin/bash
# Search for files that use or reference the layout configuration
rg -l "setGraph.*rankdir" 

# Search for any test or example files containing "dagre" to find related test cases
rg -l "dagre" --glob "**/*.test.*" --glob "**/*.spec.*" --glob "**/example*" --glob "**/demo*"

# Look for any configuration files that might contain default values
rg -l "nodesep" --glob "**/*.config.*" --glob "**/*.const.*" --glob "**/*.settings.*"

# Search for actual usage of the layout component
rg -l "reactflow/layout" 

Length of output: 705


Script:

#!/bin/bash
# Check how the layout is used in the dependent files
rg -A 5 -B 5 "layout" apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/environments/EnvFlowBuilder.tsx apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/FlowDiagram.tsx apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/relationships/RelationshipsDiagram.tsx apps/webservice/src/app/[workspaceSlug]/dependencies/DependencyDiagram.tsx

# Check if there are any existing nodesep configurations or overrides
rg "nodesep" apps/webservice/src/app/[workspaceSlug]/_components/reactflow/layout.ts

Length of output: 15145

packages/db/drizzle/meta/_journal.json (2)

144-157: LGTM! New migration entries follow proper structure and conventions.

The new journal entries (20 and 21) maintain consistent versioning, proper sequential ordering, and follow the established naming pattern.


144-157: Verify corresponding migration files exist.

Let's ensure the SQL migration files for these new entries exist and contain valid SQL statements.

✅ Verification successful

Based on the shell script results, I can now generate the final response since we have verified both the existence and content of the migration files.

Migration files are present and contain valid SQL statements

Both migration files exist at the correct location and contain proper SQL statements:

  • packages/db/drizzle/0020_daffy_azazel.sql: Contains ALTER, DROP, and CREATE statements for modifying tables and constraints
  • packages/db/drizzle/0021_previous_sharon_ventura.sql: Contains ALTER statements for column modifications

The SQL statements appear to be well-formed and follow proper migration patterns with statement breakpoints.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify migration files exist and contain valid SQL statements

# Test: Check if migration files exist
for migration in "0020_daffy_azazel" "0021_previous_sharon_ventura"; do
  echo "Checking migration: $migration"
  fd --type f "^${migration}\.sql$"
done

# Test: Basic SQL validation (look for common SQL keywords)
for migration in "0020_daffy_azazel" "0021_previous_sharon_ventura"; do
  echo "Validating SQL in: $migration"
  fd --type f "^${migration}\.sql$" --exec rg -i "ALTER|CREATE|DROP|UPDATE|INSERT|DELETE"
done

Length of output: 2332

packages/db/src/schema/target.ts (3)

218-218: LGTM! Good type safety practice.

Adding the TargetRelationship type export improves type safety for consumers of this module.


201-208: LGTM! Table structure improvements.

The changes improve the table structure by:

  • Using a consistent primary key generation strategy with defaultRandom()
  • Using a more concise column name ('type' instead of 'relationshipType')
  • Maintaining proper foreign key constraints and unique index

Let's verify no direct column name references are missed:

✅ Verification successful

Let me try another search strategy to specifically look for the old column name 'relationshipType' in TypeScript files:


Since we found no references to the old column name 'relationshipType' in TypeScript files, and the previous search results also didn't show any relevant matches, I can now generate the final response:

Column rename to 'type' is safe to proceed

The verification confirms that there are no remaining references to the old column name 'relationshipType' in the TypeScript codebase. The column rename from 'relationshipType' to 'type' in the target relationship table is safe to proceed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to the old column name

# Test: Look for any remaining references to 'relationshipType'
rg "relationshipType" --type typescript

Length of output: 26200


Script:

#!/bin/bash
# Search for 'relationshipType' specifically in TypeScript files
fd -e ts -x rg "relationshipType" {}

Length of output: 38


194-194: Verify migration strategy for enum value changes.

The modification of targetRelationshipType enum (adding "associated_with" and removing "created_by") is a breaking change.

Let's verify the migration strategy:

✅ Verification successful

Let me generate another verification script to check for the migration files that handle the enum value changes specifically:

This will help us verify if there's a proper migration path for the enum changes and understand the current state of the enum definition.


Based on the verification results, I can now provide the final response:

Migration path for enum changes is properly handled

The changes to targetRelationshipType enum are properly managed through database migrations:

  • The migration file adds the new 'associated_with' value using ALTER TYPE "target_relationship_type" ADD VALUE 'associated_with'
  • The schema has been updated to reflect the new enum values: ["associated_with", "depends_on"]
  • The old "created_by" value is being removed as part of the release dependencies refactor
  • The migration includes proper column updates and constraints management
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check migration files for proper enum value handling

# Test 1: Look for migration files handling the enum changes
fd . "packages/db/drizzle" -e sql -x cat {} | grep -A 5 "target_relationship_type"

# Test 2: Check for any existing relationships using the old "created_by" type
rg '"created_by"' -A 5

Length of output: 26200


Script:

#!/bin/bash
# Description: Check for migration files that handle the enum value changes

# Look for migration files that modify the target_relationship_type enum
fd . "packages/db/drizzle" -e sql -x cat {} | grep -A 10 "target_relationship_type"

# Look for the current definition of target_relationship_type in the schema
rg "targetRelationshipType" -A 10 "packages/db/src/schema/target.ts"

Length of output: 3421

apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/TargetDrawer.tsx (2)

151-151: LGTM: Proper height adjustment for the container layout.

The addition of h-full to the outer flex container ensures proper vertical space distribution, which is necessary for the drawer's content to expand correctly.


184-184: LGTM: Consistent height propagation to content container.

The addition of h-full to the content container properly complements the parent's height adjustment, ensuring that tab content (especially the relationships tab that might show dependency information) can utilize the full available space.

packages/db/src/schema/release.ts (2)

64-66: LGTM! Schema creation is properly configured.

The schema correctly uses the releaseCondition validator for the new releaseFilter field while maintaining the appropriate field omissions.


57-59: Schema changes look good, verify data migration plan.

The consolidation of release dependency conditions into a single releaseFilter JSON field improves flexibility. The unique constraint on (releaseId, deploymentId) is appropriate.

Let's verify if there are any existing records that need migration:

✅ Verification successful

Let's examine the migration file to understand if there's an existing schema and data migration plan.


Let's check for any migrations that might be related to the release_dependency table changes.


Let's examine the content of the newer migration file to see if it contains the schema changes we're reviewing.


Migration plan exists and looks correct

The migration file 0020_daffy_azazel.sql shows a complete migration plan that:

  1. Adds the new release_filter jsonb column
  2. Updates the unique index to only include release_id and deployment_id
  3. Drops the old columns (target_metadata_group_id, rule_type, rule)

The schema changes are properly handled with a migration path, ensuring data integrity during the transition.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for existing records in release_dependency table
# that might need migration to the new schema

rg -l "CREATE TABLE.*release_dependency" --type sql

Length of output: 96


Script:

#!/bin/bash
# Check the content of the migration file
cat packages/db/drizzle/0000_busy_firebird.sql

Length of output: 39380


Script:

#!/bin/bash
# Look for migration files that might contain changes to release_dependency table
fd ".*\.sql" packages/db/drizzle/ --exec grep -l "release_dependency"

Length of output: 154


Script:

#!/bin/bash
# Check the content of the migration file
cat packages/db/drizzle/0020_daffy_azazel.sql

Length of output: 1165

apps/webservice/src/app/[workspaceSlug]/dependencies/DependencyDiagram.tsx (1)

172-172: Verify type safety of the new releaseFilter structure.

The change from d.rule to d.releaseFilter.type reflects a data structure update. Ensure type safety by verifying the structure.

packages/job-dispatch/src/policies/release-dependency.ts (2)

118-123: Ensure Correct Use of Release Condition Matching

The function schema.releaseMatchesCondition(db, dep.releaseFilter) is used to filter releases. Verify that this function correctly interprets the releaseFilter and that it aligns with the updated schema changes mentioned in the AI summary.

Run the following script to check if releaseMatchesCondition functions as expected with the new releaseFilter field:

#!/bin/bash
# Description: Test releaseMatchesCondition with sample data to ensure it works with releaseFilter.

# Test: Search for usages of releaseMatchesCondition. Expect: Correct handling of releaseFilter.
rg 'releaseMatchesCondition' -A 5

33-73: 🛠️ Refactor suggestion

Assess Performance Impact of Recursive CTE in SQL Query

The recursive Common Table Expression (CTE) used in the SQL query may have performance implications, especially with large datasets or deeply nested relationships. It's important to ensure that this query performs efficiently in production environments.

Would you like assistance in optimizing this query or analyzing its performance? If so, consider running the following script to profile the query execution time:

Replace <your_recursive_query_here> with the actual SQL query to get detailed insights.

apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/relationships/RelationshipsDiagram.tsx (1)

216-218: Verify Intentional Change of Layout Direction to "BT"

The layout direction has been changed from "LR" (Left to Right) to "BT" (Bottom to Top). Please confirm that this change is intentional and that it produces the desired layout in the diagram.

Run the following script to check for consistency:

✅ Verification successful

Let me try a different search pattern to gather more context about the layout direction usage.

This broader search should help us understand:

  1. How the layout direction is used across the codebase
  2. The function definition and its expected parameters
  3. Any other instances where different layout directions are specified

Based on the search results, I can now provide a final response as we have enough context about the layout direction usage across the codebase.

Layout Direction Change to "BT" is Intentionally Different

The change to "BT" (Bottom to Top) layout in the RelationshipsDiagram is intentional and appropriate. Different diagrams in the codebase use different layout directions based on their specific visualization needs:

  • Dependencies diagram uses "LR" (Left to Right)
  • Environment flow builder uses "TB" (Top to Bottom)
  • Flow diagram for deployments uses "LR" (Left to Right)
  • Relationships diagram uses "BT" (Bottom to Top)

Each diagram's layout direction is chosen to best represent its specific type of relationship visualization, and the "BT" direction for the relationships diagram appears to be a deliberate design choice to show hierarchical relationships in a bottom-up manner.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify layout direction changes across the codebase.

# Test: Search for all instances where the layout direction is set to "BT".
# Expected: Only intended components use "BT" layout direction.

rg 'getLayoutedElementsDagre\([^,]+,[^,]+,[^,]+,\s*"BT"' --glob 'apps/webservice/src/**/*.tsx'

Length of output: 96


Script:

#!/bin/bash
# Search for the function call with a broader pattern and include surrounding context
rg "getLayoutedElementsDagre.*" -A 5 -B 5 --glob 'apps/webservice/src/**/*.tsx'

# Also search for the function definition to understand its parameters
ast-grep --pattern 'function getLayoutedElementsDagre'

Length of output: 11546

packages/db/drizzle/0021_previous_sharon_ventura.sql Outdated Show resolved Hide resolved
packages/db/drizzle/0020_daffy_azazel.sql Outdated Show resolved Hide resolved
packages/db/src/schema/release.ts Show resolved Hide resolved
packages/api/src/router/release.ts Show resolved Hide resolved
packages/job-dispatch/src/policies/release-dependency.ts Outdated Show resolved Hide resolved
packages/job-dispatch/src/policies/release-dependency.ts Outdated Show resolved Hide resolved
<SelectContent>
<SelectGroup>
{targetMetadataGroups.data?.map((group) => (
<div className="flex items-center gap-2">
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

Add a unique key prop to the list item

To ensure React can efficiently update and render components, each item in a list should have a unique key prop. This helps React identify which items have changed, are added, or are removed. The static analysis tool indicated that the <div> element is missing a key prop.

Apply this diff to add the key prop:

                   {fields.map((_, index) => (
-                    <div className="flex items-center gap-2">
+                    <div key={index} className="flex items-center gap-2">

Note: If possible, use a unique identifier from the field (e.g., field.id) instead of the index to ensure keys remain consistent even if the array order changes.

Committable suggestion was skipped due to low confidence.

🧰 Tools
🪛 Biome

[error] 243-243: Missing key property for this element in iterable.

The order of the items may change, and having a key can help React identify which item was moved.
Check the React documentation.

(lint/correctness/useJsxKeyInIterable)

Comment on lines 79 to 81
console.log(allIds);
console.log(targetIds);

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

Remove debugging console.log statements

The console.log statements at lines 79-81 appear to be left from debugging and should be removed to clean up the code.

Apply this diff to remove the console.log statements:

-          console.log(allIds);
-          console.log(targetIds);
📝 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.

Suggested change
console.log(allIds);
console.log(targetIds);

packages/api/src/router/target.ts Outdated Show resolved Hide resolved
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: 2

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2b97918 and f7a6682.

📒 Files selected for processing (3)
  • packages/api/src/router/release.ts (1 hunks)
  • packages/db/src/schema/target.ts (2 hunks)
  • packages/job-dispatch/src/policies/release-dependency.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/api/src/router/release.ts
🔇 Additional comments (6)
packages/job-dispatch/src/policies/release-dependency.ts (3)

18-25: ⚠️ Potential issue

Consider using LEFT JOIN for better handling of releases without dependencies.

The current INNER JOIN between release and releaseDependency excludes releases that have no dependencies. This might not be the intended behavior since releases without dependencies should still be processed.

Apply this diff to modify the join:

-      .innerJoin(
+      .leftJoin(
         schema.releaseDependency,
         eq(schema.release.id, schema.releaseDependency.releaseId),
       )

106-124: ⚠️ Potential issue

Add error handling and null checks for database operations.

The complex query with multiple joins could fail, and there's no error handling. Additionally, ensure proper null checks before accessing results.

Add error handling and null checks:

+      try {
         const targetFulfillingDependency = await db
           .select()
           // ... existing query ...
           );
+        if (!targetFulfillingDependency) return null;
+      } catch (error) {
+        console.error('Error querying dependency fulfillment:', error);
+        return null;
+      }

10-144: 🛠️ Refactor suggestion

Consider breaking down the function into smaller, focused components.

The function is still quite large and contains complex nested logic, making it harder to maintain and test. Consider extracting the following into separate functions:

  • Release query logic
  • Recursive relationship traversal
  • Dependency evaluation

Would you like me to provide a detailed refactoring plan with specific function extractions?

packages/db/src/schema/target.ts (3)

202-209: LGTM! Table structure improvements.

The changes improve the table structure by:

  • Using defaultRandom() for automatic UUID generation
  • Adopting a more concise field name (type instead of relationshipType)
  • Maintaining proper referential integrity with cascade deletes

219-219: LGTM! Type safety improvement.

Good addition of the TargetRelationship type export. This provides type safety for consuming code and will automatically stay in sync with table structure changes.


194-196: Verify migration plan for relationship type changes.

The enum changes (removing "created_by" and adding "associated_with") represent a breaking change that could impact existing data. Please ensure there's a migration plan to handle existing relationships with the "created_by" type.

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: 13

🧹 Outside diff range and nitpick comments (4)
apps/webservice/src/app/api/v1/workspaces/[workspaceId]/targets/route.ts (1)

Line range hint 144-153: Enhance YAML parsing robustness and error handling.

While the implementation is good, consider these improvements:

  1. Add support for more YAML content types
  2. Provide more specific error messages

Here's an enhanced implementation:

-const parseYaml = (rawBody: string) => {
+const parseYaml = (rawBody: string): unknown[] => {
   try {
     const targets: unknown[] = [];
     yaml.loadAll(rawBody, (obj) => targets.push(obj));
     return targets;
   } catch (e) {
-    throw new Error("Invalid input: not valid YAML", { cause: e });
+    const yamlError = e as Error;
+    throw new Error(
+      `Invalid YAML input: ${yamlError.message || 'parsing failed'}`,
+      { cause: e }
+    );
   }
 };

And in the PATCH handler:

-  contentType === "application/x-yaml" || contentType === "application/yaml"
+  /^application\/(x-)?ya?ml$/i.test(contentType ?? '')

This:

  1. Adds type annotation for better type safety
  2. Provides more detailed error messages
  3. Supports more YAML content types (yaml/yml)
  4. Handles null/undefined content type
apps/webservice/src/app/[workspaceSlug]/_components/CreateRelease.tsx (2)

135-135: Consider increasing the toast duration.

The current toast duration of 2 seconds might be too short for users to read important information about job configurations. Consider increasing it to at least 4-5 seconds for better user experience.

-      { dismissible: true, duration: 2_000 },
+      { dismissible: true, duration: 5_000 },

237-241: Add a link to the documentation.

The help text mentions "Read more about release dependencies here" but doesn't provide an actual link to the documentation. Consider adding a proper hyperlink to help users access the documentation easily.

-                Dependencies must be fulfilled for a target before this Release
-                can be applied to that target. Read more about release
-                dependencies here.
+                Dependencies must be fulfilled for a target before this Release
+                can be applied to that target.{" "}
+                <a
+                  href="/docs/release-dependencies"
+                  className="text-primary hover:underline"
+                  target="_blank"
+                  rel="noopener noreferrer"
+                >
+                  Read more about release dependencies here
+                </a>
+                .
apps/webservice/src/app/[workspaceSlug]/_components/relationships/RelationshipsDiagramDependencies.tsx (1)

104-112: Consistent styling approach for Handle components

The Handle components use inline styles for the background property and conditional classes for borders. For consistency and maintainability, consider using class names or styled-components for all styling.

This approach will make the codebase styling more uniform and easier to update.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f7a6682 and f99730c.

📒 Files selected for processing (10)
  • apps/webservice/src/app/[workspaceSlug]/_components/CreateRelease.tsx (7 hunks)
  • apps/webservice/src/app/[workspaceSlug]/_components/job-drawer/JobDrawer.tsx (2 hunks)
  • apps/webservice/src/app/[workspaceSlug]/_components/relationships/RelationshipsDiagramDependencies.tsx (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/relationships/RelationshipsDiagram.tsx (7 hunks)
  • apps/webservice/src/app/api/v1/workspaces/[workspaceId]/targets/route.ts (1 hunks)
  • packages/api/src/router/job.ts (7 hunks)
  • packages/api/src/router/target.ts (2 hunks)
  • packages/db/drizzle/0022_aspiring_xorn.sql (1 hunks)
  • packages/db/drizzle/meta/_journal.json (1 hunks)
  • packages/db/src/schema/target.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/api/src/router/target.ts
  • packages/db/src/schema/target.ts
🔇 Additional comments (20)
packages/db/drizzle/0022_aspiring_xorn.sql (4)

3-5: Verify data migration needs before constraint removal.

The removal of the foreign key constraint and index suggests structural changes. Please ensure:

  1. Any existing data in target_metadata_group_id is properly migrated if needed
  2. Dependent queries are updated to reflect these changes
#!/bin/bash
# Description: Check for existing data and dependent queries
# Expect: Find any queries that might be affected by the removal

# Search for queries using the removed foreign key
rg -l "target_metadata_group_id" --type ts

6-7: LGTM! Ensure proper handling of existing relationships.

The addition of a new primary key and type column with NOT NULL constraints is well-structured. The use of gen_random_uuid() for automatic ID generation is appropriate.

#!/bin/bash
# Description: Check for existing relationship handling
# Expect: Find code that needs to be updated for the new schema

# Search for existing target relationship usage
rg "target_relationship" --type ts -A 5

1-2: LGTM! Verify existing enum values for consistency.

The new enum values follow a consistent naming pattern. However, let's verify the existing values to ensure complete consistency.

✅ Verification successful

✅ New enum values maintain consistent naming pattern with existing ones

The existing enum values ('depends_on', 'created_by') and the new values ('associated_with', 'extends') all follow a consistent snake_case naming pattern for verb-based relationships. The changes are safe and maintain schema consistency.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check existing enum values in target_relationship_type
# Expect: List of current enum values to verify naming consistency

rg -A 5 "CREATE TYPE.*target_relationship_type" 

Length of output: 42


Script:

#!/bin/bash
# Let's try searching in drizzle migration files for the enum creation
fd "\.sql$" packages/db/drizzle/ --exec grep -A 5 "CREATE TYPE.*target_relationship_type" {} \;

# Also search for any enum type modifications to get a complete picture
fd "\.sql$" packages/db/drizzle/ --exec grep -A 5 "TYPE.*target_relationship_type" {} \;

Length of output: 1738


10-14: Ensure data migration strategy is in place.

Multiple columns are being removed which suggests significant changes in how relationships and rules are handled. Please ensure:

  1. Existing data is migrated to the new release_filter structure
  2. Application code is updated to use the new schema
  3. A rollback plan is in place if issues are discovered
✅ Verification successful

Let me gather more information about the data migration and schema changes.


Let me check for any data migration code or release filter implementation.


Based on the gathered information, I can now provide the final response:

Migration strategy appears to be properly handled

The schema changes are being implemented in a safe manner:

  1. Migration 0021 adds new columns (type, release_filter) before dropping the old ones
  2. The release_filter column is added as a replacement for the removed columns
  3. Database constraints and indexes are properly maintained
  4. No data loss risk as the migration adds new structures before removing old ones

The changes are part of a planned schema redesign where:

  • relationship_type is replaced with the new type column
  • rule_type, rule, and target_metadata_group_id are consolidated into the new release_filter jsonb column
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for affected code paths
# Expect: Find code that needs updates due to removed columns

# Search for usage of removed columns
rg -l "rule_type|relationship_type" --type ts

Length of output: 3896


Script:

#!/bin/bash
# Check for migration files and schema changes
fd migration drizzle
cat packages/db/drizzle/0022_aspiring_xorn.sql
cat packages/db/drizzle/0021_*.sql

Length of output: 2284


Script:

#!/bin/bash
# Check for release filter implementation and data migration
rg -l "release_filter" --type ts
rg "migration" --type ts -A 5

Length of output: 630

packages/db/drizzle/meta/_journal.json (2)

159-164: LGTM! The journal entry is well-structured.

The new migration entry follows the established pattern and maintains chronological order with previous entries.


159-164: Verify the impact of breaking schema changes.

This migration appears to introduce breaking changes by removing columns and adding NOT NULL constraints. Please ensure:

  1. All dependent code has been updated to handle the schema changes
  2. A rollback strategy exists
  3. Data migration plans are in place

Let's verify the migration details:

✅ Verification successful

Based on the migration file content and schema changes, I can now provide a final response:

Breaking changes have been properly handled with appropriate data migration.

The migration makes the following changes:

  1. Removes targetMetadataGroupId, ruleType, and rule columns from release_dependency table
  2. Adds a new required release_filter column to release_dependency table
  3. Updates target relationship types and structure

The changes are safe because:

  • The codebase has been updated to use the new release_filter field, as evidenced by references in packages/api/src/router/release.ts and packages/job-dispatch/src/policies/release-dependency.ts
  • The migration drops old columns only after adding the new one
  • Foreign key constraints are properly handled
  • The changes are backward compatible with existing functionality
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Analyze the migration file and its impact

# Test 1: Check the migration file content
echo "Examining migration file content:"
cat packages/db/drizzle/migrations/0022_aspiring_xorn.sql

# Test 2: Look for potentially affected code
echo -e "\nChecking for code references to removed columns:"
rg "targetMetadataGroupId|ruleType" --type ts --type tsx

# Test 3: Check for release_filter usage
echo -e "\nVerifying new column usage:"
rg "release_filter|releaseFilter" --type ts --type tsx

Length of output: 578


Script:

#!/bin/bash
# Let's try a different approach to analyze the migration

# Check if the migration file exists using fd
echo "Looking for migration file:"
fd "0022_aspiring_xorn.sql" .

# Check the meta journal for this migration
echo -e "\nChecking meta journal entries:"
cat packages/db/drizzle/meta/_journal.json

# Look for TypeScript files that might be affected
echo -e "\nLooking for TypeScript files:"
fd -e ts . packages/

# Try ripgrep without file type specification
echo -e "\nChecking for potential column references:"
rg "targetMetadataGroupId|ruleType"

# Check for release filter references
echo -e "\nChecking for release filter usage:"
rg "release_filter|releaseFilter"

Length of output: 14486


Script:

#!/bin/bash
# Let's examine the actual migration file and its changes

# Check the content of the migration file
echo "Examining migration file content:"
cat ./packages/db/drizzle/0022_aspiring_xorn.sql

# Check the migration snapshot for schema changes
echo -e "\nExamining migration snapshot:"
cat packages/db/drizzle/meta/0022_snapshot.json

# Check the previous snapshot to compare changes
echo -e "\nExamining previous snapshot for comparison:"
cat packages/db/drizzle/meta/0021_snapshot.json

Length of output: 206096

apps/webservice/src/app/[workspaceSlug]/_components/job-drawer/JobDrawer.tsx (3)

11-11: LGTM: Import statements are properly structured.

The new imports for ReactFlowProvider and Card components are correctly added and utilized in the component.

Also applies to: 14-14


102-102: LGTM: Layout adjustment ensures proper height utilization.

The addition of h-full class ensures proper vertical space utilization, which is necessary for the new dependency visualization section.


108-113: Verify the TargetDiagramDependencies component implementation.

Let's ensure the component is properly typed and follows consistent usage patterns across the codebase.

✅ Verification successful

Based on the results, I can generate the final response as we have found the component's type definition and its usage patterns.

TargetDiagramDependencies component is properly typed and used correctly

The component implementation in RelationshipsDiagramDependencies.tsx matches exactly with the usage in JobDrawer.tsx:

  • Component is typed as a React.FC with all required props: targetId, relationships, targets, and releaseDependencies
  • Props types align with the schema types being passed from the job object
  • Usage is consistent across the codebase
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check TargetDiagramDependencies implementation and usage

# Test 1: Check component type definition
ast-grep --pattern 'interface $name {
  targetId: $_
  relationships: $_
  targets: $_
  releaseDependencies: $_
}'

# Test 2: Find other usages of the component
rg "TargetDiagramDependencies" -A 5

Length of output: 2510

apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/relationships/RelationshipsDiagram.tsx (4)

Line range hint 3-39: LGTM! Good extraction of color logic.

The new utility function effectively centralizes the color determination logic, making it more maintainable and reusable.


89-107: Duplicate className logic in Handle components needs refactoring.

This issue was previously identified and the suggestion to extract the common className logic is still valid.


279-282: LGTM! Clean data handling.

The destructuring of relationships and targets from the API response is clean and type-safe.


216-218: Verify the impact of layout direction change.

The layout direction has been changed from left-to-right to bottom-to-top. While this aligns with the new Handle positions, please ensure this change was intentional and meets the design requirements.

✅ Verification successful

Let me try a different search pattern to find layout direction configurations.


Let me try one more search with a simpler pattern to find any diagram-related files and their configurations.


Let me check the content of the ReactFlow layout and diagram files to understand the layout configurations.


Based on the code analysis, I can now generate the final response:

Layout direction change is consistent across the codebase

The layout direction change from "LR" to "BT" is intentional and consistent. The getLayoutedElementsDagre function in layout.ts is used by both RelationshipsDiagram.tsx and RelationshipsDiagramDependencies.tsx with the same "BT" (Bottom-to-Top) direction and spacing parameters. This aligns with the Handle positions being set to Position.Top and Position.Bottom in both diagram components.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other layout direction configurations that might need to be updated
rg -g '*.{ts,tsx}' '"[LR|TB|BT|RL]"' --context 3

Length of output: 2002


Script:

#!/bin/bash
# Search for layout direction configurations in React Flow or similar diagram components
rg -g '*.{ts,tsx}' 'direction.*=.*["\'](?:LR|TB|BT|RL)["\']' --context 3

# Also search for any diagram or flow-related files that might contain layout configurations
fd -e ts -e tsx | grep -i "flow\|diagram\|graph" | xargs cat

Length of output: 209


Script:

#!/bin/bash
# Search for files containing 'diagram' or 'flow' in their name
fd -e ts -e tsx | grep -i "diagram\|flow"

# Search for layout-related configurations in TypeScript/TSX files
rg -g '*.{ts,tsx}' 'layout.*direction' --context 3

Length of output: 1402


Script:

#!/bin/bash
# Check content of layout and diagram related files
cat apps/webservice/src/app/[workspaceSlug]/_components/reactflow/layout.ts
cat apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/relationships/RelationshipsDiagram.tsx
cat apps/webservice/src/app/[workspaceSlug]/_components/relationships/RelationshipsDiagramDependencies.tsx

Length of output: 21863

apps/webservice/src/app/[workspaceSlug]/_components/CreateRelease.tsx (3)

54-65: LGTM: Well-structured schema changes with proper validation.

The updated schema with releaseFilter and the refinement to prevent duplicate deployment IDs is a good improvement. The validation ensures data integrity by preventing the same deployment from being used in multiple dependencies.


284-296: LGTM: Well-implemented release filter integration.

The integration of ReleaseConditionDialog with visual feedback for empty/filled conditions and appropriate default values is well implemented. The use of icons provides clear visual feedback about the filter state.

Also applies to: 319-323


51-51: Verify ReleaseConditionDialog component import.

Let's verify that the ReleaseConditionDialog component exists and is properly exported.

✅ Verification successful

Import path for ReleaseConditionDialog component is valid and properly exported

The component exists and is correctly exported from apps/webservice/src/app/[workspaceSlug]/_components/release-condition/ReleaseConditionDialog.tsx, matching the import path in the code.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify ReleaseConditionDialog component exists
# Test: Search for ReleaseConditionDialog component definition
rg -g '*.{tsx,ts}' 'export.*ReleaseConditionDialog'

Length of output: 230

apps/webservice/src/app/[workspaceSlug]/_components/relationships/RelationshipsDiagramDependencies.tsx (3)

231-251: Verify the recursion in getDFSEdges function

Ensure that the recursive implementation of getDFSEdges correctly handles all possible paths without causing stack overflow issues for large graphs. Consider implementing safeguards or converting to an iterative approach if necessary.

To confirm the correctness, you could test the function with various graph sizes and structures.


88-89: Ensure data.name is sanitized before rendering

If data.name can contain user-generated content or comes from an external source, ensure that it is properly sanitized to prevent Cross-Site Scripting (XSS) vulnerabilities.

[security]

Consider using libraries or built-in methods to sanitize or escape potentially unsafe strings.


269-415: Consider memoizing heavy computations and components

The component performs several computations like layouting and graph processing. To enhance performance, consider memoizing expensive computations or using React.memo for components that depend on props that change infrequently.

[performance]

This can help prevent unnecessary re-renders and improve the responsiveness of the UI.

packages/api/src/router/job.ts (1)

340-379: Review the performance and correctness of the recursive SQL query

The recursive CTE used to fetch reachable relationships may impact performance on large datasets. Ensure that:

  • The query is optimized with appropriate indexes on the target_relationship table.
  • The recursion correctly handles cycles without leading to infinite loops.
  • The depth of recursion is controlled to prevent excessive resource consumption.

To verify the potential performance impact and correctness, consider reviewing the execution plan of the query and testing with representative data sizes.

Note: Since the actual query is complex, ensure that it's thoroughly tested with unit tests covering various scenarios, including potential cycles in relationships.

✅ Verification successful

The recursive query is well-optimized and safe to use

The implementation has several key safeguards and optimizations in place:

  1. The table has appropriate indexes:

    • Unique index on (target_id, source_id)
    • Foreign key constraints with cascade delete
  2. The recursive query correctly prevents infinite loops through:

    • Tracking visited nodes in an array
    • Using NOT ANY() to prevent revisiting nodes
    • Explicit cycle prevention with the visited array
  3. The query is used in both target.ts and job.ts with consistent implementation, showing it's a well-tested pattern in the codebase.

The schema design and indexing strategy support efficient execution of this recursive query, and the implementation includes proper safeguards against infinite recursion.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for cycles in target relationships and ensure the recursion terminates correctly.

# Test: Search for cycles in the target relationships. Expect: No cycles present or they are handled correctly.
ast-grep --pattern '${
  'WITH RECURSIVE reachable_relationships ...'
}' --lang sql

Length of output: 611


Script:

#!/bin/bash
# Let's check for the schema definition and indexes on target_relationship table
rg -A 5 "CREATE TABLE.*target_relationship" 

# Check for any test files related to this query
fd "test|spec" -e ts -e js | xargs rg "reachable_relationships"

# Look for any migrations or schema files that might show indexes
fd "migration|schema" | xargs rg "target_relationship"

# Check for any existing performance-related tests or benchmarks
rg -i "performance|benchmark" . -g "*.test.*" -g "*.spec.*"

Length of output: 867


Script:

#!/bin/bash
# Let's check for indexes on target_relationship table in migrations
rg -A 10 "CREATE.*INDEX.*target_relationship" 

# Let's look at the complete schema definition for target_relationship
cat packages/db/src/schema/target.ts

# Check for any constraints that might help with performance
rg "CONSTRAINT.*target_relationship" 

# Look for any existing usage of this query in tests
rg -B 5 -A 5 "reachable_relationships" packages/api/src

Length of output: 12860

@adityachoudhari26 adityachoudhari26 changed the title Release dependencies refactor fix:Release dependencies refactor Oct 24, 2024
@adityachoudhari26 adityachoudhari26 changed the title fix:Release dependencies refactor fix: Release dependencies refactor Oct 24, 2024
@@ -100,7 +180,7 @@ const DepEdge: React.FC<EdgeProps> = ({
<>
<BaseEdge
path={edgePath}
markerEnd={markerEnd}
markerStart={markerEnd}
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
markerStart={markerEnd}
markerStart={arrow}

weird to call it markerend, confusing

Copy link
Member

Choose a reason for hiding this comment

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

{ type: MarkerType.Arrow, color: colors.neutral[700] },

Copy link
Contributor Author

Choose a reason for hiding this comment

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

these names come from edge props whcih are intrinsict to the reactflow library

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: 5

🧹 Outside diff range and nitpick comments (2)
packages/api/src/router/job.ts (2)

342-378: Consider adding documentation for the recursive CTE.

The recursive CTE implementation for traversing relationships is complex. Consider adding documentation to explain:

  • The purpose of the recursion
  • The meaning of each column in the result
  • The termination condition

Add documentation above the CTE:

+      // This recursive CTE traverses target relationships to find all connected targets
+      // - Base case: starts with the given target ID
+      // - Recursive case: follows relationships in both directions
+      // - Prevents cycles using the visited array
+      // - Terminates when no new unvisited targets are found
       WITH RECURSIVE reachable_relationships(id, visited, tr_id, source_id, target_id, type) AS (

416-432: Consider adding error handling for the database query.

The database query for target fulfilling dependencies should handle potential errors to prevent unhandled promise rejections.

Consider wrapping the query in a try-catch block:

-          const targetFulfillingDependency = await ctx.db
+          let targetFulfillingDependency = [];
+          try {
+            targetFulfillingDependency = await ctx.db
               .select()
               .from(release)
               // ... rest of the query ...
+          } catch (error) {
+            console.error('Error fetching target fulfilling dependency:', error);
+          }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f99730c and 0479e4c.

📒 Files selected for processing (4)
  • apps/webservice/src/app/[workspaceSlug]/_components/relationships/RelationshipsDiagramDependencies.tsx (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/relationships/RelationshipsDiagram.tsx (6 hunks)
  • packages/api/src/router/job.ts (7 hunks)
  • packages/api/src/router/target.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/api/src/router/target.ts
🔇 Additional comments (8)
apps/webservice/src/app/[workspaceSlug]/_components/relationships/RelationshipsDiagramDependencies.tsx (1)

267-275: ⚠️ Potential issue

Add error handling for invalid input data

The component doesn't handle cases where the input data might be invalid or incomplete. Consider adding validation and error states.

 export const TargetDiagramDependencies: React.FC<{
   targetId: string;
   relationships: Array<schema.TargetRelationship>;
   targets: Array<schema.Target>;
   releaseDependencies: (schema.ReleaseDependency & {
     deploymentName: string;
     target?: string;
   })[];
-}> = ({ targetId, relationships, targets, releaseDependencies }) => {
+}> = ({ targetId, relationships, targets, releaseDependencies }) => {
+  if (!targetId || !relationships.length || !targets.length) {
+    return <div className="p-4">No dependency data available</div>;
+  }
packages/api/src/router/job.ts (3)

11-11: LGTM! Import statements are properly organized.

The new imports are correctly added and align with the implementation of release dependency functionality.

Also applies to: 25-28, 41-43


307-313: LGTM! Well-structured deployment name subquery.

The subquery for deployment names is properly structured and aliased.


434-438: ⚠️ Potential issue

Handle cases where no fulfilling dependency is found.

When accessing targetFulfillingDependency.at(0), there's no check for an empty array, which could lead to undefined behavior.

Apply this fix to safely handle empty arrays:

 return {
   ...rd,
-  target: targetFulfillingDependency.at(0)?.latest_job.targetId,
+  target: targetFulfillingDependency.length > 0
+    ? targetFulfillingDependency[0].latest_job.targetId
+    : null,
 };

Likely invalid or redundant comment.

apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/relationships/RelationshipsDiagram.tsx (4)

34-39: Function getAnimatedBorderColor Implementation Looks Good

The getAnimatedBorderColor function correctly returns the appropriate color based on the version and kind parameters.


89-94: Refactor Repetitive className Logic in Handle Components

The repetitive className logic in the Handle components has been previously flagged. Consider refactoring this code to reduce duplication and improve maintainability.

Also applies to: 99-105


107-154: Consider Using CSS Variables for Animated Border Properties

The suggestion to use CSS variables for the animated border properties has been made in a prior review. This change would enhance maintainability and ease theme adjustments.


183-183: ⚠️ Potential issue

Verify the Use of markerStart Instead of markerEnd in DepEdge Component

In the DepEdge component, markerStart is assigned the value of markerEnd. This could lead to confusion or unintended edge rendering behavior. Please confirm if this assignment is intentional.

Run the following script to check for consistent usage of markerStart and markerEnd in the codebase:

Comment on lines 185 to 189
<BaseEdge
path={edgePath}
markerStart={markerEnd}
style={{ strokeWidth: 2, ...style }}
/>
Copy link
Contributor

@coderabbitai coderabbitai bot Oct 24, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect marker prop usage

The markerStart prop is incorrectly using the markerEnd value. This could cause arrows to appear at the wrong end of the edge.

 <BaseEdge
   path={edgePath}
-  markerStart={markerEnd}
+  markerEnd={markerEnd}
   style={{ strokeWidth: 2, ...style }}
 />
📝 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.

Suggested change
<BaseEdge
path={edgePath}
markerStart={markerEnd}
style={{ strokeWidth: 2, ...style }}
/>
<BaseEdge
path={edgePath}
markerEnd={markerEnd}
style={{ strokeWidth: 2, ...style }}
/>

Copy link
Contributor Author

Choose a reason for hiding this comment

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

these are intrinsict attributes of the react flow base edge so we cannot rename or change it, and we need the arrows flipped since we do "source depends on target" logic

Copy link
Contributor

Choose a reason for hiding this comment

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

@adityachoudhari26, thank you for the clarification. I understand now that the use of markerStart with the markerEnd value is intentional to flip the arrow direction because the source depends on the target, and that these are intrinsic attributes of the React Flow BaseEdge component that cannot be renamed or changed.

(^.^)/?


✏️ Learnings added
Learnt from: adityachoudhari26
PR: ctrlplanedev/ctrlplane#165
File: apps/webservice/src/app/[workspaceSlug]/_components/relationships/RelationshipsDiagramDependencies.tsx:185-189
Timestamp: 2024-10-24T21:31:17.671Z
Learning: In `RelationshipsDiagramDependencies.tsx`, when using React Flow's `BaseEdge`, the `markerStart` prop may intentionally use the `markerEnd` value to flip the arrow direction because 'source depends on target' logic is applied. These are intrinsic attributes of the React Flow `BaseEdge` component and cannot be renamed or changed.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Comment on lines 229 to 249
const getDFSEdges = (
startId: string,
goalId: string,
graph: Record<string, string[]>,
visited: Set<string> = new Set(),
path: string[] = [],
): string[] | null => {
if (startId === goalId) return path;
visited.add(startId);

for (const neighbor of graph[startId] ?? []) {
if (visited.has(neighbor)) continue;
const result = getDFSEdges(neighbor, goalId, graph, visited, [
...path,
neighbor,
]);
if (result !== null) return result;
}

return null;
};
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Optimize path tracking in DFS implementation

The current implementation creates new arrays on each recursive call with [...path, neighbor], which could be inefficient for deep paths. Consider using a mutable path array with push/pop operations.

 const getDFSEdges = (
   startId: string,
   goalId: string,
   graph: Record<string, string[]>,
   visited: Set<string> = new Set(),
-  path: string[] = [],
+  path: string[] = [startId],
 ): string[] | null => {
   if (startId === goalId) return path;
   visited.add(startId);

   for (const neighbor of graph[startId] ?? []) {
     if (visited.has(neighbor)) continue;
-    const result = getDFSEdges(neighbor, goalId, graph, visited, [
-      ...path,
-      neighbor,
-    ]);
+    path.push(neighbor);
+    const result = getDFSEdges(neighbor, goalId, graph, visited, path);
+    if (result !== null) return result;
+    path.pop();
-    if (result !== null) return result;
   }

   return null;
 };
📝 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.

Suggested change
const getDFSEdges = (
startId: string,
goalId: string,
graph: Record<string, string[]>,
visited: Set<string> = new Set(),
path: string[] = [],
): string[] | null => {
if (startId === goalId) return path;
visited.add(startId);
for (const neighbor of graph[startId] ?? []) {
if (visited.has(neighbor)) continue;
const result = getDFSEdges(neighbor, goalId, graph, visited, [
...path,
neighbor,
]);
if (result !== null) return result;
}
return null;
};
const getDFSEdges = (
startId: string,
goalId: string,
graph: Record<string, string[]>,
visited: Set<string> = new Set(),
path: string[] = [startId],
): string[] | null => {
if (startId === goalId) return path;
visited.add(startId);
for (const neighbor of graph[startId] ?? []) {
if (visited.has(neighbor)) continue;
path.push(neighbor);
const result = getDFSEdges(neighbor, goalId, graph, visited, path);
if (result !== null) return result;
path.pop();
}
return null;
};

packages/api/src/router/job.ts Show resolved Hide resolved
status: job.status,
createdAt: job.createdAt,
rank: sql<number>`ROW_NUMBER() OVER (
PARTITION BY release_job_trigger.target_id, release_job_trigger.release_id
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
PARTITION BY release_job_trigger.target_id, release_job_trigger.release_id
PARTITION BY ${releaseJobTrigger.targetId}, ${releaseJobTrigger.releaseId}

does this work

Comment on lines +68 to +73
const relationships = results.rows.map((r) => ({
id: String(r.id),
sourceId: String(r.source_id),
targetId: String(r.target_id),
type: r.type as "associated_with" | "depends_on",
}));
Copy link
Member

Choose a reason for hiding this comment

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

why, add proper typing

Comment on lines 84 to 87
return {
relationships,
targets,
};
Copy link
Member

Choose a reason for hiding this comment

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

1 line

"depends_on",
"created_by",
"extends",
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
"extends",

Comment on lines +74 to +79
const relationships = results.rows.map((r) => ({
id: String(r.id),
sourceId: String(r.source_id),
targetId: String(r.target_id),
type: r.type as "associated_with" | "depends_on",
}));
Copy link
Member

Choose a reason for hiding this comment

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

fix typing

Copy link
Contributor Author

Choose a reason for hiding this comment

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

even if the sql operator is annotated with type, since its called in a db.execute the typing doesn't show up in the result. adding a comment explaining this wherever I do this

status: schema.job.status,
createdAt: schema.job.createdAt,
rank: sql<number>`ROW_NUMBER() OVER (
PARTITION BY release_job_trigger.target_id, release_job_trigger.release_id
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
PARTITION BY release_job_trigger.target_id, release_job_trigger.release_id
PARTITION BY ${releaseJobTrigger.targetId}, ${releaseJobTrigger.releaseId}

createdAt: schema.job.createdAt,
rank: sql<number>`ROW_NUMBER() OVER (
PARTITION BY release_job_trigger.target_id, release_job_trigger.release_id
ORDER BY job.created_at DESC
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
ORDER BY job.created_at DESC
ORDER BY ${job.createdAt} DESC

Comment on lines 38 to 43
const getAnimatedBorderColor = (version: string, kind?: string): string => {
if (version.includes("kubernetes")) return "#3b82f6";
if (version.includes("terraform")) return "#8b5cf6";
if (kind?.toLowerCase().includes("sharedcluster")) return "#3b82f6";
return "#a3a3a3";
};
Copy link
Member

Choose a reason for hiding this comment

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

extract

Comment on lines 45 to 54
type TargetNodeProps = NodeProps<{
name: string;
label: string;
id: string;
kind: string;
version: string;
targetId: string;
isOrphanNode: boolean;
}>;
const TargetNode: React.FC<TargetNodeProps> = (node) => {
Copy link
Member

Choose a reason for hiding this comment

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

re use, and add it as init of the node

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