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: Optimize flow node query #190

Merged
merged 2 commits into from
Nov 1, 2024
Merged

fix: Optimize flow node query #190

merged 2 commits into from
Nov 1, 2024

Conversation

adityachoudhari26
Copy link
Contributor

@adityachoudhari26 adityachoudhari26 commented Nov 1, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced FlowDiagram component to include workspace-specific information.
    • Introduced granular job filtering capabilities in the ReleaseSequencingNode component.
    • Added new ReleaseCondition type for improved job condition evaluations.
  • Bug Fixes

    • Improved logic for determining job statuses and loading states in the WaitingOnActiveCheck component.
  • Documentation

    • Expanded validation schema to include ReleaseCondition for better type-checking.
  • Chores

    • New export for release-condition.js to enhance modularity in job conditions.

Copy link
Contributor

coderabbitai bot commented Nov 1, 2024

Walkthrough

The pull request introduces several modifications across multiple files, primarily enhancing the handling of workspace-specific data in the FlowDiagram and ReleaseSequencingNode components. A new Workspace type is added to the props of the FlowDiagram, and the ReleaseSequencingNode is updated to include a workspaceId. Additionally, new condition types for job filtering are introduced, enhancing the logic for job status checks. The changes also include the addition of a ReleaseCondition type, allowing for more flexible job condition evaluations.

Changes

File Change Summary
apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/FlowDiagram.tsx Added workspace prop of type Workspace to FlowDiagram component; updated data object for release-sequencing node to include workspaceId.
apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/ReleaseSequencingNode.tsx Enhanced job filtering logic with new condition types; refactored WaitingOnActiveCheck component to use multiple condition objects and updated loading state logic. Updated ReleaseSequencingNodeProps to include workspaceId.
apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/page.tsx Added workspace prop to FlowDiagram component, derived from API call; existing data-fetching logic and error handling remain unchanged.
packages/db/src/schema/job.ts Introduced new condition type JobFilterType.Release in buildCondition function for filtering jobs by release ID; existing logic for other condition types remains unchanged.
packages/validators/src/jobs/conditions/comparison-condition.ts Added ReleaseCondition type to comparisonCondition validation schema, enhancing flexibility of conditions.
packages/validators/src/jobs/conditions/index.ts Added export for release-condition.js module to include new functionalities.
packages/validators/src/jobs/conditions/job-condition.ts Integrated ReleaseCondition into JobCondition type union and Zod schema; updated JobFilterType enum to include Release.
packages/validators/src/jobs/conditions/release-condition.ts Introduced new file defining a validation schema for ReleaseCondition using Zod, including properties for type, operator, and value.

Possibly related PRs

  • fix: Redeploy to target button #157: Modifications to the TargetDropdownMenu component, including updates to the release prop structure, related to the FlowDiagram component's props.
  • fix: Release dependencies refactor #165: Refactor of release dependencies with the introduction of a releaseFilter field, relevant to enhancements in release-related data structures.
  • Fix: Approval Usability #172: Updates to the PolicyApprovalRow component to include a user property, enhancing the approval process in the context of releases.
  • fix user id #184: Simplification of the ApprovalDialog component by removing the userId prop, related to modifications in approval handling.
  • fix: Release channel ui cleanup #188: Significant modifications to the EnvironmentDrawer and ReleaseChannelDrawer components, enhancing the user interface for managing releases.

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

🧹 Outside diff range and nitpick comments (3)
packages/validators/src/jobs/conditions/release-condition.ts (1)

3-7: Add JSDoc documentation to explain the schema's purpose and usage.

The schema would benefit from documentation explaining its role in release condition validation and providing examples of valid conditions.

+/**
+ * Validates a release condition used in job filtering.
+ * 
+ * @example
+ * ```typescript
+ * const condition = {
+ *   type: "release",
+ *   operator: "equals",
+ *   value: "123e4567-e89b-12d3-a456-426614174000"
+ * };
+ * ```
+ */
 export const releaseCondition = z.object({
   type: z.literal("release"),
   operator: z.literal("equals"),
   value: z.string().uuid(),
 });
apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/page.tsx (1)

Line range hint 27-33: Consider parallelizing API calls for better performance.

The sequential API calls to fetch workspace, release, deployment, system, environments, and policies could be optimized using Promise.all() to reduce the total loading time.

Here's a suggested optimization:

-  const release = await api.release.byId(params.versionId);
-  const deployment = await api.deployment.bySlug(params);
-  const workspace = await api.workspace.bySlug(params.workspaceSlug);
-  if (workspace == null || release == null || deployment == null) notFound();
-
-  const system = await api.system.bySlug(params);
-  const environments = await api.environment.bySystemId(system.id);
-  const policies = await api.environment.policy.bySystemId(system.id);
-  const policyDeployments = await api.environment.policy.deployment.bySystemId(
-    system.id,
-  );
+  const [release, deployment, workspace] = await Promise.all([
+    api.release.byId(params.versionId),
+    api.deployment.bySlug(params),
+    api.workspace.bySlug(params.workspaceSlug),
+  ]);
+  
+  if (workspace == null || release == null || deployment == null) notFound();
+  
+  const system = await api.system.bySlug(params);
+  
+  const [environments, policies, policyDeployments] = await Promise.all([
+    api.environment.bySystemId(system.id),
+    api.environment.policy.bySystemId(system.id),
+    api.environment.policy.deployment.bySystemId(system.id),
+  ]);
apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/ReleaseSequencingNode.tsx (1)

126-132: Simplify conditional rendering logic

The rendering logic can be simplified for better readability by using a single conditional statement.

Apply this diff to simplify the JSX:

- {loading && <Loading />}
- {!loading && isWaitingOnActive && (
-   <>
-     <Waiting /> Another release is in progress
-   </>
- )}
- {!loading && !isWaitingOnActive && (
-   <>
-     <Passing /> All other releases finished
-   </>
- )}
+ {loading ? (
+   <Loading />
+ ) : isWaitingOnActive ? (
+   <>
+     <Waiting /> Another release is in progress
+   </>
+ ) : (
+   <>
+     <Passing /> All other releases finished
+   </>
+ )}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9e86c2a and edb99be.

📒 Files selected for processing (8)
  • apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/FlowDiagram.tsx (3 hunks)
  • apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/ReleaseSequencingNode.tsx (2 hunks)
  • apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/page.tsx (1 hunks)
  • packages/db/src/schema/job.ts (1 hunks)
  • packages/validators/src/jobs/conditions/comparison-condition.ts (4 hunks)
  • packages/validators/src/jobs/conditions/index.ts (1 hunks)
  • packages/validators/src/jobs/conditions/job-condition.ts (5 hunks)
  • packages/validators/src/jobs/conditions/release-condition.ts (1 hunks)
🔇 Additional comments (12)
packages/validators/src/jobs/conditions/release-condition.ts (1)

9-9: LGTM!

The type export using Zod's inference is correct and follows TypeScript best practices.

packages/validators/src/jobs/conditions/comparison-condition.ts (1)

11-11: LGTM! Clean integration of the ReleaseCondition type.

The changes consistently integrate the new ReleaseCondition type across imports, schema definition, and type declaration, maintaining the existing code structure and ordering patterns.

Also applies to: 21-21, 39-39, 58-58

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

Line range hint 49-56: LGTM! Workspace prop integration looks correct.

The workspace prop is properly fetched, validated, and passed to the FlowDiagram component. The implementation aligns well with the PR objectives for optimizing flow node queries.

Let's verify the prop type consistency across components:

✅ Verification successful

Props type consistency verified for workspace integration

The workspace prop is properly typed and integrated:

  • FlowDiagram component correctly imports the Workspace type from @ctrlplane/db/schema
  • Props interface properly declares workspace: Workspace as required prop
  • The type is consistently used across the component hierarchy
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify FlowDiagram component's workspace prop type definition
# Expected: Should find the workspace prop type definition in FlowDiagram.tsx

# Search for FlowDiagram component props interface/type
ast-grep --pattern 'interface $PROPS {
  $$$
  workspace: $_
  $$$
}'

# Backup search using ripgrep
rg -A 5 'interface.*FlowDiagram.*Props|type.*FlowDiagram.*Props'

Length of output: 392


Script:

#!/bin/bash
# Let's try a different approach to find the FlowDiagram component and its props
# First, let's locate the FlowDiagram component file
fd FlowDiagram.tsx

# Then let's examine its content focusing on props/interfaces
rg -A 10 "type.*Props|interface.*Props" $(fd FlowDiagram.tsx)

# Also search for workspace prop usage in FlowDiagram
rg "workspace[?:]\s*" $(fd FlowDiagram.tsx)

# Additionally, let's check ReleaseSequencingNode for workspace prop usage
fd ReleaseSequencingNode.tsx
rg "workspace[?:]\s*" $(fd ReleaseSequencingNode.tsx)

Length of output: 902


Script:

#!/bin/bash
# Let's examine the full content of FlowDiagram.tsx to understand the props interface
cat "apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/FlowDiagram.tsx" | head -n 50

# Also check for Workspace type import and definition
rg -B 2 -A 2 "type\s+Workspace|interface\s+Workspace"

Length of output: 3529

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

8-8: LGTM: Clean import addition

The Workspace type import is properly grouped with other schema types.


Line range hint 77-83: LGTM: Proper workspace context integration

The workspaceId is correctly derived from the workspace prop and properly integrated into the release-sequencing node data structure.


77-77: Verify workspaceId handling in dependent components

Let's verify that all components consuming the release-sequencing node data are updated to handle the new workspaceId field.

✅ Verification successful

Let me try a different search strategy to verify the impact.


Based on the search results, I can see that the workspaceId field is consistently used across the codebase, particularly in the context of flow diagrams and release sequencing. Let me verify one more aspect to ensure there are no inconsistencies.


Based on the comprehensive analysis of the codebase, I can now provide a final response:

✓ The workspaceId field is properly integrated

The workspaceId field in the release sequencing node is consistent with its usage across the codebase:

  • It's properly defined in the ReleaseSequencingNodeProps type
  • The field is correctly populated from the workspace context in FlowDiagram.tsx
  • All components consuming this data structure expect and handle the workspaceId field
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for components that might be affected by the workspaceId addition

# Look for files that reference release-sequencing node type
echo "Files potentially affected by release-sequencing node changes:"
rg -l "release-sequencing" --type tsx

# Look for direct usage of the node data
echo -e "\nComponents accessing release-sequencing node data:"
ast-grep --pattern 'data: { $$$workspaceId$$$, $$$}'

Length of output: 372


Script:

#!/bin/bash
# Search for components that might be affected by workspaceId in flow diagrams

# Look for files referencing flow diagrams and workspace data
echo "Files with flow diagram and workspace references:"
rg -l "FlowDiagram|workspaceId" --type-add 'tsx:*.{tsx,ts}'

# Look for data structure usage patterns
echo -e "\nRelevant data structure usage:"
rg -A 5 "workspaceId.*workspace\.id" --type-add 'tsx:*.{tsx,ts}'

Length of output: 35936


Script:

#!/bin/bash
# Search for release sequencing node data structure and usage
echo "Release sequencing node data structure:"
rg -A 5 "type ReleaseSequencingNode" --type-add 'tsx:*.{tsx,ts}'

echo -e "\nRelease sequencing node usage:"
rg -A 5 "ReleaseSequencingNode.*props" --type-add 'tsx:*.{tsx,ts}'

Length of output: 1296

packages/validators/src/jobs/conditions/job-condition.ts (4)

12-12: LGTM: Import statements follow consistent patterns.

The new imports for ReleaseCondition type and releaseCondition schema are properly structured and follow the established import patterns.

Also applies to: 27-27


38-39: LGTM: Type union extension is properly implemented.

The ReleaseCondition is correctly added to the JobCondition union type, maintaining type safety and consistency.


50-50: LGTM: Schema union is properly extended.

The releaseCondition is correctly added to the jobCondition Zod schema union, maintaining validation consistency.


12-12: Verify the release condition implementation.

Let's verify the implementation of the referenced release condition schema and type.

Also applies to: 27-27, 38-39, 50-50, 64-64

✅ Verification successful

Release condition implementation is properly integrated

The release condition is well-implemented with:

  • A proper Zod schema definition with type literal, operator constraint, and UUID value validation
  • Correct type exports and schema integration in the job condition union
  • Consistent usage across the conditions system
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the implementation of release-condition.js and its usage

# Test 1: Verify the release condition schema implementation
rg -t typescript "export const releaseCondition = " "./packages/validators/src/jobs/conditions/"

# Test 2: Check for any direct usage of the new release condition
rg -t typescript "type === (?:\"|')release(?:\"|')" -g '!job-condition.ts'

Length of output: 247


Script:

#!/bin/bash
# Let's try without typescript file type flag and check the implementation

# Check for release condition implementation
rg "export (type|interface) ReleaseCondition" ./packages/validators/src/jobs/conditions/
rg "export const releaseCondition" ./packages/validators/src/jobs/conditions/

# Check the usage context
rg "ReleaseCondition" -A 3 ./packages/validators/src/jobs/conditions/

Length of output: 1977


Script:

#!/bin/bash
# Let's check the implementation details of release-condition.ts

# Get the full content of release-condition.ts
cat ./packages/validators/src/jobs/conditions/release-condition.ts

# Check where the release condition is being used in the union
rg "releaseCondition" -A 2 ./packages/validators/src/jobs/conditions/job-condition.ts

Length of output: 529

packages/db/src/schema/job.ts (1)

222-222: LGTM! Verify table joins for release filtering.

The implementation of the release filter condition is correct and follows the established pattern. However, ensure that the necessary table joins for the release table are properly set up in the query where this condition is used.

Let's verify the table joins:

✅ Verification successful

Table joins are properly handled for release filtering

The implementation is correct. The releaseJobTriggerQuery function in the router properly sets up all necessary table joins, including the release table:

const releaseJobTriggerQuery = (tx: Tx) =>
  tx
    .select()
    .from(releaseJobTrigger)
    .innerJoin(job, eq(releaseJobTrigger.jobId, job.id))
    .innerJoin(target, eq(releaseJobTrigger.targetId, target.id))
    .innerJoin(release, eq(releaseJobTrigger.releaseId, release.id))
    .innerJoin(deployment, eq(release.deploymentId, deployment.id))
    .innerJoin(environment, eq(releaseJobTrigger.environmentId, environment.id))
    .innerJoin(jobAgent, eq(jobAgent.id, deployment.jobAgentId));

The release table is properly joined before the condition eq(release.id, cond.value) is used in the filter.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if release table joins are properly handled in job queries
# Test: Look for JOIN clauses between job and release tables
rg -A 5 "FROM.*job.*JOIN.*release|FROM.*release.*JOIN.*job"

Length of output: 61


Script:

#!/bin/bash
# Let's check the entire file content to understand the query building logic
cat packages/db/src/schema/job.ts

Length of output: 6529


Script:

#!/bin/bash
# Let's check where this condition is used to verify table joins
rg -A 10 "jobMatchesCondition|buildCondition" --type ts

Length of output: 8230


Script:

#!/bin/bash
# Let's check the query construction in the API router to see how joins are handled
cat packages/api/src/router/job.ts

Length of output: 20520

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

23-23: Ensure workspaceId is passed correctly

The workspaceId prop has been added to ReleaseSequencingNodeProps. Verify that all instances where this component is used are updated to pass the workspaceId to prevent potential runtime errors.

Run the following script to find all usages of ReleaseSequencingNode and check for the workspaceId prop:

✅ Verification successful

Let me gather more information to check where this component is being used.


Let me check the content of FlowDiagram.tsx since it's the only file that uses ReleaseSequencingNode.


Let me check how the nodes are created and passed to the ReleaseSequencingNode component.


Let me try a different approach to find the node creation and data passing logic.


No issues found - workspaceId is correctly passed

The verification shows that the workspaceId prop is correctly passed to the ReleaseSequencingNode component in FlowDiagram.tsx. Specifically, when creating the release sequencing nodes:

{
  id: env.id + "-release-sequencing",
  type: "release-sequencing",
  position: { x: 0, y: 0 },
  data: {
    workspaceId: workspace.id,  // workspaceId is properly passed here
    releaseId: release.id,
    deploymentId: release.deploymentId,
    environmentId: env.id,
    policyType: policy?.releaseSequencing,
    label: `${env.name} - release sequencing`,
  },
}

The component is only used in this one location and receives all required props, including workspaceId, as defined in ReleaseSequencingNodeProps.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all usages of ReleaseSequencingNode include the workspaceId prop

# Find all JSX files containing ReleaseSequencingNode
fd --extension jsx 'ReleaseSequencingNode'

# Search for instances without workspaceId
rg -A 5 -B 2 '<ReleaseSequencingNode' | rg -B 5 -A 5 -v 'workspaceId='

Length of output: 2622


Script:

#!/bin/bash
# Find all files that import or use ReleaseSequencingNode
rg -l "ReleaseSequencingNode"

# Show the actual usage of the component with context
rg -B 5 -A 5 "<ReleaseSequencingNode"

Length of output: 3842


Script:

#!/bin/bash
# Show the content of FlowDiagram.tsx focusing on ReleaseSequencingNode usage
rg -B 10 -A 10 "ReleaseSequencingNode" "apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/FlowDiagram.tsx"

Length of output: 1241


Script:

#!/bin/bash
# Search for node creation logic in FlowDiagram.tsx
rg -A 20 "const nodes = \[" "apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/FlowDiagram.tsx"

# Also check for any createNode functions that might be creating ReleaseSequencing nodes
rg -l "createNode.*release-sequencing" 

Length of output: 199


Script:

#!/bin/bash
# Show more content from FlowDiagram.tsx to understand the component usage
cat "apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/FlowDiagram.tsx"

# Also check the type definition of ReleaseSequencingNodeProps
rg -A 10 "type ReleaseSequencingNodeProps" "apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/ReleaseSequencingNode.tsx"

Length of output: 4561

Comment on lines +4 to +6
type: z.literal("release"),
operator: z.literal("equals"),
value: z.string().uuid(),
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

Consider supporting additional comparison operators.

The schema currently only supports the 'equals' operator. Consider adding support for other operators like 'not_equals' if there are use cases where excluding specific releases would be valuable.

 export const releaseCondition = z.object({
   type: z.literal("release"),
-  operator: z.literal("equals"),
+  operator: z.enum(["equals", "not_equals"]),
   value: z.string().uuid(),
 });
📝 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
type: z.literal("release"),
operator: z.literal("equals"),
value: z.string().uuid(),
type: z.literal("release"),
operator: z.enum(["equals", "not_equals"]),
value: z.string().uuid(),

@@ -4,3 +4,4 @@ export * from "./status-condition.js";
export * from "./deployment-condition.js";
export * from "./environment-condition.js";
export * from "./job-target-condition.js";
export * from "./release-condition.js";
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Warning: Potential naming conflict in release condition modules

The verification revealed two different ReleaseCondition types and releaseCondition schemas in the codebase:

  • packages/validators/src/jobs/conditions/release-condition.ts: A simple condition for UUID comparison
  • packages/validators/src/releases/conditions/release-condition.ts: A comprehensive release condition system with multiple types

The export in the jobs module might conflict with or be confused with the releases module. Consider:

  • Renaming the jobs condition to be more specific (e.g., JobReleaseCondition)
  • Or moving the jobs condition logic into the releases module if they should be unified
🔗 Analysis chain

LGTM! Verify the referenced module.

The new export follows consistent patterns with existing exports in terms of file extension and naming convention.

Let's verify the existence and exports of the referenced module:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence and exports of release-condition.js

# Test 1: Check if the file exists
fd -e ts "release-condition"

# Test 2: Examine the exports from the module
rg -t typescript "export (type|interface|const|function)" -A 2 "release-condition"

Length of output: 369


Script:

#!/bin/bash
# Let's examine the content of the release-condition.ts files to verify exports
echo "=== Content of packages/validators/src/jobs/conditions/release-condition.ts ==="
cat "packages/validators/src/jobs/conditions/release-condition.ts"

echo -e "\n=== Content of packages/validators/src/releases/conditions/release-condition.ts ==="
cat "packages/validators/src/releases/conditions/release-condition.ts"

Length of output: 3921

Comment on lines +34 to +40
workspace: Workspace;
systemId: string;
release: Release;
envs: Array<Environment>;
policies: Array<EnvironmentPolicy>;
policyDeployments: Array<EnvironmentPolicyDeployment>;
}> = ({ release, envs, policies, policyDeployments }) => {
}> = ({ workspace, release, envs, policies, policyDeployments }) => {
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 unused systemId prop

The systemId prop is declared but never used within the component. Consider removing it if it's not needed.

Apply this diff to remove the unused prop:

export const FlowDiagram: React.FC<{
  workspace: Workspace;
- systemId: string;
  release: Release;
  envs: Array<Environment>;
  policies: Array<EnvironmentPolicy>;
  policyDeployments: Array<EnvironmentPolicyDeployment>;
}> = ({ workspace, release, envs, policies, policyDeployments }) => {
📝 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
workspace: Workspace;
systemId: string;
release: Release;
envs: Array<Environment>;
policies: Array<EnvironmentPolicy>;
policyDeployments: Array<EnvironmentPolicyDeployment>;
}> = ({ release, envs, policies, policyDeployments }) => {
}> = ({ workspace, release, envs, policies, policyDeployments }) => {
workspace: Workspace;
release: Release;
envs: Array<Environment>;
policies: Array<EnvironmentPolicy>;
policyDeployments: Array<EnvironmentPolicyDeployment>;
}> = ({ workspace, release, envs, policies, policyDeployments }) => {

@@ -57,6 +61,7 @@ export enum JobFilterType {
Status = "status",
Deployment = "deployment",
Environment = "environment",
Release = "release",
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

Add missing type guard function for ReleaseCondition.

While the Release enum value is correctly added, there should be a corresponding type guard function for consistency with other condition types. Consider adding:

export const isReleaseCondition = (
  condition: JobCondition,
): condition is ReleaseCondition =>
  condition.type === JobFilterType.Release;

Comment on lines +53 to +95
const isSameEnvironment: EnvironmentCondition = {
type: JobFilterType.Environment,
operator: ColumnOperator.Equals,
value: environmentId,
};

const isPending: StatusCondition = {
type: JobFilterType.Status,
operator: ColumnOperator.Equals,
value: JobStatus.Pending,
};

const isInProgress: StatusCondition = {
type: JobFilterType.Status,
operator: ColumnOperator.Equals,
value: JobStatus.InProgress,
};

const isSameRelease: ReleaseCondition = {
type: JobFilterType.Release,
operator: ColumnOperator.Equals,
value: releaseId,
};

const isDifferentRelease: JobCondition = {
type: FilterType.Comparison,
operator: ComparisonOperator.And,
not: true,
conditions: [isSameRelease],
};

const pendingJobsForCurrentReleaseAndEnvFilter: JobCondition = {
type: FilterType.Comparison,
operator: ComparisonOperator.And,
conditions: [isSameEnvironment, isPending, isSameRelease],
};

const inProgressJobsForDifferentReleaseAndCurrentEnvFilter: JobCondition = {
type: FilterType.Comparison,
operator: ComparisonOperator.And,
conditions: [isSameEnvironment, isInProgress, isDifferentRelease],
};

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

Refactor condition objects into reusable functions

The condition objects defined between lines 53 and 95 have similar structures. Consider refactoring them into reusable helper functions to reduce code duplication and enhance maintainability.

You could create helper functions like createEnvironmentCondition, createStatusCondition, and createReleaseCondition:

function createEnvironmentCondition(environmentId: string): EnvironmentCondition {
  return {
    type: JobFilterType.Environment,
    operator: ColumnOperator.Equals,
    value: environmentId,
  };
}

function createStatusCondition(status: JobStatus): StatusCondition {
  return {
    type: JobFilterType.Status,
    operator: ColumnOperator.Equals,
    value: status,
  };
}

function createReleaseCondition(releaseId: string): ReleaseCondition {
  return {
    type: JobFilterType.Release,
    operator: ColumnOperator.Equals,
    value: releaseId,
  };
}

Then refactor the condition objects:

- const isSameEnvironment: EnvironmentCondition = {
-   type: JobFilterType.Environment,
-   operator: ColumnOperator.Equals,
-   value: environmentId,
- };
+ const isSameEnvironment = createEnvironmentCondition(environmentId);

- const isPending: StatusCondition = {
-   type: JobFilterType.Status,
-   operator: ColumnOperator.Equals,
-   value: JobStatus.Pending,
- };
+ const isPending = createStatusCondition(JobStatus.Pending);

- const isInProgress: StatusCondition = {
-   type: JobFilterType.Status,
-   operator: ColumnOperator.Equals,
-   value: JobStatus.InProgress,
- };
+ const isInProgress = createStatusCondition(JobStatus.InProgress);

- const isSameRelease: ReleaseCondition = {
-   type: JobFilterType.Release,
-   operator: ColumnOperator.Equals,
-   value: releaseId,
- };
+ const isSameRelease = createReleaseCondition(releaseId);

Comment on lines +96 to +111
const pendingJobsQ = api.job.config.byWorkspaceId.list.useQuery(
{
workspaceId,
filter: pendingJobsForCurrentReleaseAndEnvFilter,
limit: 1,
},
{ refetchInterval: 5_000 },
);

const isReleasePending = allJobs.data?.some(
(j) =>
j.job.status === JobStatus.Pending &&
j.release.id === releaseId &&
j.environmentId === environmentId,
const inProgressJobsQ = api.job.config.byWorkspaceId.list.useQuery(
{
workspaceId,
filter: inProgressJobsForDifferentReleaseAndCurrentEnvFilter,
limit: 1,
},
{ refetchInterval: 5_000 },
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 queries by combining them

Currently, there are two separate queries fetching pending and in-progress jobs. Consider combining these queries into a single query to reduce network requests and improve performance.

If the API supports fetching multiple statuses, you could adjust the filter:

const combinedStatusCondition: StatusCondition = {
  type: JobFilterType.Status,
  operator: ColumnOperator.In,
  value: [JobStatus.Pending, JobStatus.InProgress],
};

const combinedJobsFilter: JobCondition = {
  type: FilterType.Comparison,
  operator: ComparisonOperator.And,
  conditions: [isSameEnvironment, combinedStatusCondition],
};

- const pendingJobsQ = api.job.config.byWorkspaceId.list.useQuery(
-   {
-     workspaceId,
-     filter: pendingJobsForCurrentReleaseAndEnvFilter,
-     limit: 1,
-   },
-   { refetchInterval: 5_000 },
- );

- const inProgressJobsQ = api.job.config.byWorkspaceId.list.useQuery(
-   {
-     workspaceId,
-     filter: inProgressJobsForDifferentReleaseAndCurrentEnvFilter,
-     limit: 1,
-   },
-   { refetchInterval: 5_000 },
- );

+ const jobsQ = api.job.config.byWorkspaceId.list.useQuery(
+   {
+     workspaceId,
+     filter: combinedJobsFilter,
+     limit: 1,
+   },
+   { refetchInterval: 5_000 },
+ );

Update the loading and condition checks accordingly.

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

Comment on lines +114 to +115
const loading = pendingJobsQ.isLoading || inProgressJobsQ.isLoading;

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

Handle potential errors from queries

The current implementation checks for the loading state but doesn't handle errors that might occur during the queries. Incorporating error handling will improve robustness and user experience.

Modify the code to handle errors:

const loading = pendingJobsQ.isLoading || inProgressJobsQ.isLoading;
+ const error = pendingJobsQ.isError || inProgressJobsQ.isError;

...

return (
  <div className="flex items-center gap-2">
+   {error && <ErrorComponent message="Failed to load job data" />}
    {loading && <Loading />}
    {!loading && isWaitingOnActive && (
      <>
        <Waiting /> Another release is in progress
      </>
    )}
    {!loading && !isWaitingOnActive && (
      <>
        <Passing /> All other releases finished
      </>
    )}
  </div>
);

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants