Skip to content

add simple queue #543

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

add simple queue #543

wants to merge 2 commits into from

Conversation

jsbroks
Copy link
Member

@jsbroks jsbroks commented May 2, 2025

Summary by CodeRabbit

  • New Features

    • Improved job queuing to prevent duplicate evaluation jobs for the same release target.
  • Refactor

    • Changed bulk job queueing to enqueue each release target individually, ensuring better control and reliability across various workflows.
    • Updated error handling to use a unified queuing approach for re-enqueuing jobs.
  • Chores

    • Removed unused and commented-out legacy queueing code for clarity.

Copy link
Contributor

coderabbitai bot commented May 2, 2025

Walkthrough

This change refactors the queuing mechanism for evaluating release targets throughout the codebase. Bulk queue operations using addBulk are replaced by sequential, individual enqueuing via a new function, queueEvaluateReleaseTarget. The new function ensures that duplicate jobs are not enqueued by checking for existing jobs with matching key fields before adding a new one. Several modules update their logic to use this function instead of direct queue manipulation. Some previously commented-out bulk queueing code is removed, and error handling in workers now leverages the new deduplicating enqueue function.

Changes

File(s) Change Summary
apps/event-worker/src/utils/dispatch-evaluate-jobs.ts Replaces bulk queue addition with sequential calls to queueEvaluateReleaseTarget for each release target.
apps/event-worker/src/workers/evaluate-release-target.ts Updates error handling to re-enqueue jobs using queueEvaluateReleaseTarget instead of direct queue access.
apps/jobs/src/policy-checker/index.ts Removes commented-out bulk queueing logic for policy evaluation.
packages/api/src/router/deployment-version-checks/approvals.ts Replaces bulk queue addition with sequential, awaited calls to queueEvaluateReleaseTarget.
packages/api/src/router/redeploy.ts Switches from direct queue addition to using queueEvaluateReleaseTarget for enqueuing release targets.
packages/events/src/index.ts Adds new exported function queueEvaluateReleaseTarget with deduplication logic for job enqueuing.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Any Module
    participant Events as queueEvaluateReleaseTarget
    participant Queue as EvaluateReleaseTarget Queue

    Caller->>Events: queueEvaluateReleaseTarget(releaseTarget)
    Events->>Queue: get waiting jobs
    Events->>Events: Check for duplicate job
    alt Duplicate exists
        Events-->>Caller: Return (do not enqueue)
    else No duplicate
        Events->>Queue: Add job with releaseTarget data
        Events-->>Caller: Return Job
    end
Loading

Poem

A bunny hops from queue to queue,
No more bulk, just one will do!
Each target checked, no job repeats,
With careful paws and nimble feats.
Deduped and tidy, the work flows right—
The warren’s code is snug tonight.
🐇✨


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a52a85f and 90712b3.

📒 Files selected for processing (1)
  • apps/event-worker/src/utils/dispatch-evaluate-jobs.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/event-worker/src/utils/dispatch-evaluate-jobs.ts
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Lint
  • GitHub Check: Typecheck
  • GitHub Check: build (linux/amd64)
  • GitHub Check: build (linux/amd64)
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

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

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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: 0

🧹 Nitpick comments (1)
packages/events/src/index.ts (1)

41-69: New deduplication queue function added with potential improvement areas.

The new queueEvaluateReleaseTarget function provides a helpful mechanism to prevent duplicate jobs in the queue by checking for existing jobs with matching properties before adding a new one.

While the implementation is generally solid, there are a few considerations:

  1. The deduplication only checks "waiting" jobs, but not "active" or "delayed" jobs, which could still lead to duplicates in certain scenarios.
  2. There's no indication to the caller when a duplicate is found (like a boolean return value or logging).
  3. Fetching all waiting jobs with getWaiting() might be inefficient with large queues.

Consider these improvements:

export const queueEvaluateReleaseTarget = async (
  value: ChannelMap[Channel.EvaluateReleaseTarget],
) => {
  const q = getQueue(Channel.EvaluateReleaseTarget);
-  const exists =
-    (await q.getWaiting()).filter((t) =>
+  // Check both waiting and active jobs for duplicates
+  const waitingJobs = await q.getWaiting();
+  const activeJobs = await q.getActive();
+  const allJobs = [...waitingJobs, ...activeJobs];
+  
+  const exists = allJobs.some((t) =>
      _.isEqual(
        _.pick(value, [
          "environmentId",
          "resourceId",
          "deploymentId",
          "skipDuplicateCheck",
        ]),
        _.pick(t.data, [
          "environmentId",
          "resourceId",
          "deploymentId",
          "skipDuplicateCheck",
        ]),
      ),
-    ).length > 0;
+    );

-  if (exists) return;
+  if (exists) {
+    logger.debug('Skipped duplicate job', { 
+      channel: Channel.EvaluateReleaseTarget, 
+      job: `${value.environmentId}-${value.resourceId}-${value.deploymentId}` 
+    });
+    return false;
+  }

-  return q.add(
+  await q.add(
    `${value.environmentId}-${value.resourceId}-${value.deploymentId}`,
    value,
  );
+  return true;
};
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4e9feab and a52a85f.

📒 Files selected for processing (6)
  • apps/event-worker/src/utils/dispatch-evaluate-jobs.ts (1 hunks)
  • apps/event-worker/src/workers/evaluate-release-target.ts (2 hunks)
  • apps/jobs/src/policy-checker/index.ts (0 hunks)
  • packages/api/src/router/deployment-version-checks/approvals.ts (1 hunks)
  • packages/api/src/router/redeploy.ts (2 hunks)
  • packages/events/src/index.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • apps/jobs/src/policy-checker/index.ts
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{ts,tsx}`: **Note on Error Handling:** Avoid strict enforcement of try/catch blocks. Code may use early returns, Promise chains (.then().catch()), or other patterns for error...

**/*.{ts,tsx}: Note on Error Handling:
Avoid strict enforcement of try/catch blocks. Code may use early returns, Promise chains (.then().catch()), or other patterns for error handling. These are acceptable as long as they maintain clarity and predictability.

  • packages/api/src/router/redeploy.ts
  • packages/api/src/router/deployment-version-checks/approvals.ts
  • apps/event-worker/src/workers/evaluate-release-target.ts
  • packages/events/src/index.ts
  • apps/event-worker/src/utils/dispatch-evaluate-jobs.ts
🧬 Code Graph Analysis (5)
packages/api/src/router/redeploy.ts (2)
packages/events/src/index.ts (1)
  • queueEvaluateReleaseTarget (41-69)
packages/db/src/schema/release.ts (1)
  • releaseTarget (20-42)
packages/api/src/router/deployment-version-checks/approvals.ts (1)
packages/events/src/index.ts (1)
  • queueEvaluateReleaseTarget (41-69)
apps/event-worker/src/workers/evaluate-release-target.ts (2)
packages/events/src/index.ts (1)
  • queueEvaluateReleaseTarget (41-69)
packages/db/src/schema/job.ts (1)
  • job (75-107)
packages/events/src/index.ts (1)
packages/events/src/types.ts (1)
  • ChannelMap (47-79)
apps/event-worker/src/utils/dispatch-evaluate-jobs.ts (2)
packages/rule-engine/src/types.ts (1)
  • ReleaseTargetIdentifier (74-78)
packages/events/src/index.ts (1)
  • queueEvaluateReleaseTarget (41-69)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: Typecheck
  • GitHub Check: Lint
  • GitHub Check: build (linux/amd64)
🔇 Additional comments (9)
packages/api/src/router/deployment-version-checks/approvals.ts (1)

115-116: Change looks good: sequential queue evaluation with duplicate prevention.

The updated code now uses the new queueEvaluateReleaseTarget function to process each release target individually. This approach provides built-in duplicate job detection and prevention, which improves system efficiency by avoiding redundant evaluations.

packages/api/src/router/redeploy.ts (2)

9-13: Import structure updated correctly to include new function.

The import statement has been properly expanded to include the new queueEvaluateReleaseTarget function alongside existing imports. The naming and organization are consistent.


65-65: Good refactor: now using centralized queue function with duplicate prevention.

Replaced direct queue manipulation with the new queueEvaluateReleaseTarget function. This change improves code maintainability and adds automatic deduplication of evaluation jobs.

apps/event-worker/src/workers/evaluate-release-target.ts (2)

8-13: Import structure updated correctly to include new function.

The import statement has been properly updated to include the queueEvaluateReleaseTarget function. The organization with named imports is clean and maintainable.


185-185: Improved error handling with consistent queue approach.

The error handling now uses queueEvaluateReleaseTarget to retry jobs when encountering row lock or uncommitted target errors. This is more consistent with the rest of the codebase and benefits from the built-in deduplication checks.

apps/event-worker/src/utils/dispatch-evaluate-jobs.ts (2)

3-7: Import structure updated correctly to include new function.

The import statement has been properly updated to include the queueEvaluateReleaseTarget function. The named imports format is clean and consistent.


10-12: Replaced bulk queue with sequential processing for better reliability.

Changed from bulk queue operations to sequential processing with the new queueEvaluateReleaseTarget function. This approach provides:

  1. Built-in deduplication of jobs
  2. More explicit control flow with awaited operations
  3. Consistent error handling

Note that for very large batches, sequential processing could be slower than bulk operations, but the deduplication benefit likely outweighs this consideration in most cases.

packages/events/src/index.ts (2)

4-4: New lodash dependency added.

The addition of lodash is appropriate for the deep equality comparison needed in the new queue function.


10-10: Import of Channel enum from types module.

This import is necessary for the new function to access the Channel enum value.

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