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: Target redeploy #210

Merged
merged 2 commits into from
Nov 11, 2024
Merged

fix: Target redeploy #210

merged 2 commits into from
Nov 11, 2024

Conversation

adityachoudhari26
Copy link
Contributor

@adityachoudhari26 adityachoudhari26 commented Nov 11, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a RedeployTargetDialog for redeploying targets, accessible from the Target Actions Dropdown.
    • Added a new dropdown menu item for redeployment with an IconRefresh.
    • Enhanced target management capabilities with a new redeploy procedure in the target router.
  • Bug Fixes

    • Improved logic for checking pending jobs related to release policies with the new isPassingNoPendingJobsPolicy function.
  • Documentation

    • Expanded public API by including exports from the pending-job-checker.js module.

Copy link
Contributor

coderabbitai bot commented Nov 11, 2024

Walkthrough

The pull request introduces a new dialog component, RedeployTargetDialog, to facilitate target redeployment within the existing TargetActionsDropdown. This dialog manages its state and utilizes an API mutation for redeployment. Additionally, the targetRouter in the API is updated to include a new redeploy procedure that handles job triggers and approvals. The job dispatch module is also enhanced with a new function to check for pending jobs, improving the overall job management logic.

Changes

File Path Change Summary
apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/TargetActionsDropdown.tsx Added RedeployTargetDialog component; updated TargetActionsDropdown to include a new menu item for redeploying.
packages/api/src/router/target.ts Introduced redeploy procedure in targetRouter for managing job triggers and approvals related to redeployment.
packages/job-dispatch/src/index.ts Added export statement for pending-job-checker.js, expanding the module's public API.
packages/job-dispatch/src/pending-job-checker.ts Introduced isPassingNoPendingJobsPolicy function to evaluate pending jobs for release triggers.

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

🧹 Outside diff range and nitpick comments (4)
packages/job-dispatch/src/index.ts (1)

25-25: Consider grouping related exports together.

The pending-job-checker export appears to be job-related functionality. Consider moving it near other job-related exports (around line 4) to maintain logical grouping in the file.

 export * from "./config.js";
 export * from "./release-job-trigger.js";
 export * from "./job-creation.js";
 export * from "./job-dispatch.js";
+export * from "./pending-job-checker.js";
 export * from "./policy-checker.js";
 export * from "./policy-create.js";
 export * from "./release-sequencing.js";
 export * from "./gradual-rollout.js";
 export * from "./new-target.js";
 export * from "./target.js";
 export * from "./lock-checker.js";
 export * from "./queue.js";

 export { isDateInTimeWindow } from "./utils.js";

 export * from "./policies/gradual-rollout.js";
 export * from "./policies/manual-approval.js";
 export * from "./policies/release-sequencing.js";
 export * from "./policies/success-rate-criteria-passing.js";
 export * from "./policies/release-dependency.js";
 export * from "./policies/release-string-check.js";
 export * from "./policies/concurrency-policy.js";
 export * from "./policies/release-window.js";
 export * from "./environment-creation.js";
-export * from "./pending-job-checker.js";
apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/TargetActionsDropdown.tsx (2)

121-127: Enhance loading state feedback.

The button shows a disabled state but could provide better visual feedback during redeployment.

Consider adding a loading spinner:

  <AlertDialogAction
    onClick={onRedeploy}
    className={buttonVariants({ variant: "default" })}
    disabled={redeployTarget.isPending}
  >
-   Redeploy
+   {redeployTarget.isPending ? (
+     <>
+       <IconLoader className="mr-2 h-4 w-4 animate-spin" />
+       Redeploying...
+     </>
+   ) : (
+     'Redeploy'
+   )}
  </AlertDialogAction>

152-158: Enhance accessibility for the redeploy menu item.

While the implementation is functionally correct, consider adding ARIA attributes for better accessibility.

Add appropriate ARIA attributes:

  <DropdownMenuItem
    className="flex cursor-pointer items-center gap-2"
    onSelect={(e) => e.preventDefault()}
+   aria-label="Redeploy target"
+   role="menuitem"
  >
    <IconRefresh className="h-4 w-4" />
    Redeploy
  </DropdownMenuItem>
packages/api/src/router/target.ts (1)

541-564: Refactor redeploy procedure using async/await for better readability

The current implementation uses nested promise chains with multiple .then() calls, which can make the code harder to read and maintain. Refactoring to use async/await syntax will enhance readability and simplify error handling.

Here is the refactored code:

  redeploy: protectedProcedure
      .input(z.string().uuid())
      .meta({
        authorizationCheck: ({ canUser, input }) =>
          canUser
            .perform(Permission.TargetUpdate)
            .on({ type: "target", id: input }),
      })
-     .mutation(({ ctx, input }) =>
-       createReleaseJobTriggers(ctx.db, "redeploy")
-         .causedById(ctx.session.user.id)
-         .targets([input])
-         .filter(isPassingReleaseStringCheckPolicy)
-         .filter(isPassingNoPendingJobsPolicy)
-         .then(createJobApprovals)
-         .insert()
-         .then((triggers) =>
-           dispatchReleaseJobTriggers(ctx.db)
-             .releaseTriggers(triggers)
-             .filter(isPassingAllPoliciesExceptNewerThanLastActive)
-             .then(cancelOldReleaseJobTriggersOnJobDispatch)
-             .dispatch(),
-         ),
-     ),
+     .mutation(async ({ ctx, input }) => {
+       const triggers = await createReleaseJobTriggers(ctx.db, "redeploy")
+         .causedById(ctx.session.user.id)
+         .targets([input])
+         .filter(isPassingReleaseStringCheckPolicy)
+         .filter(isPassingNoPendingJobsPolicy)
+         .then(createJobApprovals)
+         .insert();
+
+       await dispatchReleaseJobTriggers(ctx.db)
+         .releaseTriggers(triggers)
+         .filter(isPassingAllPoliciesExceptNewerThanLastActive)
+         .then(cancelOldReleaseJobTriggersOnJobDispatch)
+         .dispatch();
+     }),
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 26dae51 and 9d6e5b2.

📒 Files selected for processing (4)
  • apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/TargetActionsDropdown.tsx (3 hunks)
  • packages/api/src/router/target.ts (2 hunks)
  • packages/job-dispatch/src/index.ts (1 hunks)
  • packages/job-dispatch/src/pending-job-checker.ts (1 hunks)
🔇 Additional comments (3)
packages/job-dispatch/src/index.ts (1)

25-25: LGTM! Export statement follows established patterns.

The new export follows the consistent pattern of using .js extension and matches the barrel file's purpose of re-exporting functionality.

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

96-96: Verify backend validation for target redeployment.

Since redeployment affects all systems and environments, we should ensure proper validation is in place.

✅ Verification successful

Target redeployment implementation has proper validation and security measures

The implementation in packages/api/src/router/target.ts shows that the redeployment mutation is properly secured with:

  1. Authorization check requiring TargetUpdate permission on the target
  2. Multiple validation policies:
    • isPassingReleaseStringCheckPolicy
    • isPassingNoPendingJobsPolicy
    • isPassingAllPoliciesExceptNewerThanLastActive
  3. Proper job trigger management with cancellation of old triggers

The implementation follows a robust pattern of creating, validating, and dispatching release job triggers with appropriate security controls.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for validation checks in the target router implementation
ast-grep --pattern 'redeploy = protectedProcedure
  .input($_)
  .mutation(({ ctx, input }) => {
    $$$
  })'

# Look for any existing validation middleware
rg -A 5 'protectedProcedure.*redeploy'

Length of output: 153


Script:

#!/bin/bash
# Search for target router implementation files
fd "target.*router" --type f

# Search for redeploy mutation in any router file
rg -A 10 "redeploy.*=.*procedure" --type ts

# Look for any validation schemas related to target redeployment
rg -A 5 "z.object.*redeploy" --type ts

Length of output: 117


Script:

#!/bin/bash
# Search for any router files in the server/api directory
fd "router.ts" --type f

# Search for any files containing 'redeploy' in their content
rg -l "redeploy"

# Search for trpc procedure definitions containing redeploy
rg -A 10 "\.procedure.*redeploy" --type ts

Length of output: 2012


Script:

#!/bin/bash
# Check the target router implementation specifically
cat "packages/api/src/router/target.ts"

# Look for any validation schemas in the API package
rg "z.object" "packages/api/src"

Length of output: 21054

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

18-26: Imports are correctly added

The imported functions from @ctrlplane/job-dispatch are appropriate and are utilized in the new redeploy procedure.

children,
}) => {
const [open, setOpen] = useState(false);
const redeployTarget = api.target.redeploy.useMutation();
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

Invalidate relevant queries after redeployment.

After a successful redeployment, related queries should be invalidated to ensure UI consistency.

Add cache invalidation:

+ const utils = api.useUtils();
  const redeployTarget = api.target.redeploy.useMutation({
+   onSuccess: () => {
+     utils.target.byWorkspaceId.list.invalidate();
+     utils.target.jobs.list.invalidate();
+   }
  });
📝 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 redeployTarget = api.target.redeploy.useMutation();
const utils = api.useUtils();
const redeployTarget = api.target.redeploy.useMutation({
onSuccess: () => {
utils.target.byWorkspaceId.list.invalidate();
utils.target.jobs.list.invalidate();
}
});

Comment on lines +98 to +99
const onRedeploy = () =>
redeployTarget.mutateAsync(targetId).then(() => setOpen(false));
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 error handling and success feedback for redeployment.

The onRedeploy function should handle errors and provide feedback to users about the operation's status.

Consider this implementation:

  const onRedeploy = () =>
-   redeployTarget.mutateAsync(targetId).then(() => setOpen(false));
+   redeployTarget.mutateAsync(targetId)
+     .then(() => {
+       toast.success('Target redeployment initiated successfully');
+       setOpen(false);
+     })
+     .catch((error) => {
+       toast.error(`Failed to redeploy target: ${error.message}`);
+     });
📝 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 onRedeploy = () =>
redeployTarget.mutateAsync(targetId).then(() => setOpen(false));
const onRedeploy = () =>
redeployTarget.mutateAsync(targetId)
.then(() => {
toast.success('Target redeployment initiated successfully');
setOpen(false);
})
.catch((error) => {
toast.error(`Failed to redeploy target: ${error.message}`);
});

Comment on lines 40 to 45
!rows.some(
(r) =>
r.release_job_trigger.releaseId === w.releaseId &&
r.release_job_trigger.targetId === w.targetId &&
r.release_job_trigger.environmentId === w.environmentId,
),
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

Correct property access in filter logic

In the .then clause, the properties are accessed using r.release_job_trigger.releaseId, but the query result may not nest properties under release_job_trigger. This could lead to undefined property errors.

Ensure that you access the properties directly from r if they are not nested. Adjust the property access as follows:

             !rows.some(
               (r) =>
-                r.release_job_trigger.releaseId === w.releaseId &&
-                r.release_job_trigger.targetId === w.targetId &&
-                r.release_job_trigger.environmentId === w.environmentId,
+                r.releaseId === w.releaseId &&
+                r.targetId === w.targetId &&
+                r.environmentId === w.environmentId,
             ),

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

Comment on lines 23 to 36
or(
...wf.map((w) =>
and(
eq(SCHEMA.releaseJobTrigger.environmentId, w.environmentId),
eq(SCHEMA.releaseJobTrigger.releaseId, w.releaseId),
eq(SCHEMA.releaseJobTrigger.targetId, w.targetId),
or(
eq(SCHEMA.job.status, JobStatus.Pending),
eq(SCHEMA.job.status, JobStatus.InProgress),
),
),
),
),
)
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 empty workflow arrays to prevent query errors

If the wf array is empty, the or(...wf.map(...)) condition will result in an empty or() call, which may produce an invalid SQL query or unintended behavior.

Add a check to handle the case when wf is empty to prevent potential errors. You can return early or adjust the query accordingly.

Apply this diff to handle empty workflows:

     .where(
-      or(
-        ...wf.map((w) =>
-          and(
-            eq(SCHEMA.releaseJobTrigger.environmentId, w.environmentId),
-            eq(SCHEMA.releaseJobTrigger.releaseId, w.releaseId),
-            eq(SCHEMA.releaseJobTrigger.targetId, w.targetId),
-            or(
-              eq(SCHEMA.job.status, JobStatus.Pending),
-              eq(SCHEMA.job.status, JobStatus.InProgress),
-            ),
-          ),
-        ),
-      ),
+      wf.length > 0
+        ? and(
+            inArray(SCHEMA.releaseJobTrigger.environmentId, wf.map((w) => w.environmentId)),
+            inArray(SCHEMA.releaseJobTrigger.releaseId, wf.map((w) => w.releaseId)),
+            inArray(SCHEMA.releaseJobTrigger.targetId, wf.map((w) => w.targetId)),
+            or(
+              eq(SCHEMA.job.status, JobStatus.Pending),
+              eq(SCHEMA.job.status, JobStatus.InProgress),
+            ),
+          )
+        : false,
     )

Alternatively, you can return the original wf array if it's empty:

+  if (wf.length === 0) {
+    return wf;
+  }
📝 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
or(
...wf.map((w) =>
and(
eq(SCHEMA.releaseJobTrigger.environmentId, w.environmentId),
eq(SCHEMA.releaseJobTrigger.releaseId, w.releaseId),
eq(SCHEMA.releaseJobTrigger.targetId, w.targetId),
or(
eq(SCHEMA.job.status, JobStatus.Pending),
eq(SCHEMA.job.status, JobStatus.InProgress),
),
),
),
),
)
wf.length > 0
? and(
inArray(SCHEMA.releaseJobTrigger.environmentId, wf.map((w) => w.environmentId)),
inArray(SCHEMA.releaseJobTrigger.releaseId, wf.map((w) => w.releaseId)),
inArray(SCHEMA.releaseJobTrigger.targetId, wf.map((w) => w.targetId)),
or(
eq(SCHEMA.job.status, JobStatus.Pending),
eq(SCHEMA.job.status, JobStatus.InProgress),
),
)
: false,

Comment on lines 7 to 47
export const isPassingNoPendingJobsPolicy: ReleasePolicyChecker = async (
db,
wf,
) =>
db
.selectDistinctOn([
SCHEMA.releaseJobTrigger.releaseId,
SCHEMA.releaseJobTrigger.targetId,
SCHEMA.releaseJobTrigger.environmentId,
])
.from(SCHEMA.job)
.innerJoin(
SCHEMA.releaseJobTrigger,
eq(SCHEMA.releaseJobTrigger.jobId, SCHEMA.job.id),
)
.where(
or(
...wf.map((w) =>
and(
eq(SCHEMA.releaseJobTrigger.environmentId, w.environmentId),
eq(SCHEMA.releaseJobTrigger.releaseId, w.releaseId),
eq(SCHEMA.releaseJobTrigger.targetId, w.targetId),
or(
eq(SCHEMA.job.status, JobStatus.Pending),
eq(SCHEMA.job.status, JobStatus.InProgress),
),
),
),
),
)
.then((rows) =>
wf.filter(
(w) =>
!rows.some(
(r) =>
r.release_job_trigger.releaseId === w.releaseId &&
r.release_job_trigger.targetId === w.targetId &&
r.release_job_trigger.environmentId === w.environmentId,
),
),
);
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 query performance for large workflow lists

The current implementation constructs an OR condition for each item in the wf array, which can lead to performance issues with large datasets due to the generation of a lengthy SQL query.

Consider refactoring the query to use IN clauses, which are more efficient for handling multiple values. This approach reduces the complexity of the SQL query and improves performance.

Apply this diff to optimize the query:

 export const isPassingNoPendingJobsPolicy: ReleasePolicyChecker = async (
   db,
   wf,
 ) =>
+  {
+    const environmentIds = wf.map((w) => w.environmentId);
+    const releaseIds = wf.map((w) => w.releaseId);
+    const targetIds = wf.map((w) => w.targetId);
+
     return db
       .selectDistinctOn([
         SCHEMA.releaseJobTrigger.releaseId,
         SCHEMA.releaseJobTrigger.targetId,
         SCHEMA.releaseJobTrigger.environmentId,
       ])
       .from(SCHEMA.job)
       .innerJoin(
         SCHEMA.releaseJobTrigger,
         eq(SCHEMA.releaseJobTrigger.jobId, SCHEMA.job.id),
       )
       .where(
-        or(
-          ...wf.map((w) =>
-            and(
-              eq(SCHEMA.releaseJobTrigger.environmentId, w.environmentId),
-              eq(SCHEMA.releaseJobTrigger.releaseId, w.releaseId),
-              eq(SCHEMA.releaseJobTrigger.targetId, w.targetId),
-              or(
-                eq(SCHEMA.job.status, JobStatus.Pending),
-                eq(SCHEMA.job.status, JobStatus.InProgress),
-              ),
-            ),
-          ),
-        ),
+        and(
+          inArray(SCHEMA.releaseJobTrigger.environmentId, environmentIds),
+          inArray(SCHEMA.releaseJobTrigger.releaseId, releaseIds),
+          inArray(SCHEMA.releaseJobTrigger.targetId, targetIds),
+          or(
+            eq(SCHEMA.job.status, JobStatus.Pending),
+            eq(SCHEMA.job.status, JobStatus.InProgress),
+          ),
+        ),
       )
       .then((rows) =>
         wf.filter(
           (w) =>
             !rows.some(
               (r) =>
                 r.release_job_trigger.releaseId === w.releaseId &&
                 r.release_job_trigger.targetId === w.targetId &&
                 r.release_job_trigger.environmentId === w.environmentId,
             ),
         ),
       );
+  }
📝 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
export const isPassingNoPendingJobsPolicy: ReleasePolicyChecker = async (
db,
wf,
) =>
db
.selectDistinctOn([
SCHEMA.releaseJobTrigger.releaseId,
SCHEMA.releaseJobTrigger.targetId,
SCHEMA.releaseJobTrigger.environmentId,
])
.from(SCHEMA.job)
.innerJoin(
SCHEMA.releaseJobTrigger,
eq(SCHEMA.releaseJobTrigger.jobId, SCHEMA.job.id),
)
.where(
or(
...wf.map((w) =>
and(
eq(SCHEMA.releaseJobTrigger.environmentId, w.environmentId),
eq(SCHEMA.releaseJobTrigger.releaseId, w.releaseId),
eq(SCHEMA.releaseJobTrigger.targetId, w.targetId),
or(
eq(SCHEMA.job.status, JobStatus.Pending),
eq(SCHEMA.job.status, JobStatus.InProgress),
),
),
),
),
)
.then((rows) =>
wf.filter(
(w) =>
!rows.some(
(r) =>
r.release_job_trigger.releaseId === w.releaseId &&
r.release_job_trigger.targetId === w.targetId &&
r.release_job_trigger.environmentId === w.environmentId,
),
),
);
export const isPassingNoPendingJobsPolicy: ReleasePolicyChecker = async (
db,
wf,
) =>
{
const environmentIds = wf.map((w) => w.environmentId);
const releaseIds = wf.map((w) => w.releaseId);
const targetIds = wf.map((w) => w.targetId);
return db
.selectDistinctOn([
SCHEMA.releaseJobTrigger.releaseId,
SCHEMA.releaseJobTrigger.targetId,
SCHEMA.releaseJobTrigger.environmentId,
])
.from(SCHEMA.job)
.innerJoin(
SCHEMA.releaseJobTrigger,
eq(SCHEMA.releaseJobTrigger.jobId, SCHEMA.job.id),
)
.where(
and(
inArray(SCHEMA.releaseJobTrigger.environmentId, environmentIds),
inArray(SCHEMA.releaseJobTrigger.releaseId, releaseIds),
inArray(SCHEMA.releaseJobTrigger.targetId, targetIds),
or(
eq(SCHEMA.job.status, JobStatus.Pending),
eq(SCHEMA.job.status, JobStatus.InProgress),
),
),
)
.then((rows) =>
wf.filter(
(w) =>
!rows.some(
(r) =>
r.release_job_trigger.releaseId === w.releaseId &&
r.release_job_trigger.targetId === w.targetId &&
r.release_job_trigger.environmentId === w.environmentId,
),
),
);
}

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9d6e5b2 and 7d1136b.

📒 Files selected for processing (1)
  • packages/job-dispatch/src/pending-job-checker.ts (1 hunks)
🔇 Additional comments (2)
packages/job-dispatch/src/pending-job-checker.ts (2)

1-6: LGTM! Well-organized imports.

The imports are properly organized with clear separation between external and internal dependencies.


11-42: LGTM! Well-optimized query implementation.

The implementation shows good practices:

  • Proper handling of empty workflow arrays
  • Efficient use of selectDistinctOn
  • Optimized query using inArray instead of multiple OR conditions
  • Clear and maintainable query structure

Comment on lines +43 to +53
.then((rows) =>
wf.filter(
(w) =>
!rows.some(
(r) =>
r.release_job_trigger.releaseId === w.releaseId &&
r.release_job_trigger.targetId === w.targetId &&
r.release_job_trigger.environmentId === w.environmentId,
),
),
)
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

Property access in filter logic needs type safety improvements.

The code still uses nested property access r.release_job_trigger.releaseId which could lead to runtime errors if the structure is not as expected.

Apply this diff to make the property access more type-safe:

         .then((rows) =>
           wf.filter(
             (w) =>
               !rows.some(
                 (r) =>
-                  r.release_job_trigger.releaseId === w.releaseId &&
-                  r.release_job_trigger.targetId === w.targetId &&
-                  r.release_job_trigger.environmentId === w.environmentId,
+                  r.releaseId === w.releaseId &&
+                  r.targetId === w.targetId &&
+                  r.environmentId === w.environmentId,
               ),
           ),
         )

Additionally, consider adding type assertions or runtime checks:

interface JobTriggerRow {
  releaseId: string;
  targetId: string;
  environmentId: string;
}

// Add type guard
function isValidJobTrigger(row: unknown): row is JobTriggerRow {
  return (
    typeof row === 'object' &&
    row !== null &&
    'releaseId' in row &&
    'targetId' in row &&
    'environmentId' in row
  );
}

// Use in the filter
!rows.some((r) => {
  if (!isValidJobTrigger(r)) {
    console.warn('Invalid job trigger row structure:', r);
    return false;
  }
  return (
    r.releaseId === w.releaseId &&
    r.targetId === w.targetId &&
    r.environmentId === w.environmentId
  );
})

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.

1 participant