Skip to content

feat: Init new worker format#444

Merged
adityachoudhari26 merged 6 commits intomainfrom
init-new-worker-format
Apr 3, 2025
Merged

feat: Init new worker format#444
adityachoudhari26 merged 6 commits intomainfrom
init-new-worker-format

Conversation

@adityachoudhari26
Copy link
Copy Markdown
Member

@adityachoudhari26 adityachoudhari26 commented Apr 3, 2025

Summary by CodeRabbit

  • New Features

    • Added a new background job dispatch worker integrated with dynamic queue retrieval.
    • Expanded support for job dispatch channels with enhanced type safety.
  • Refactor

    • Streamlined job dispatching processes for more efficient job retrieval and improved error handling.
    • Introduced additional logging to monitor background worker creation.
    • Updated database relationships to better link job records with their agents.
    • Removed outdated queue management functionality.
  • Chores

    • Revised dependencies to support a dynamic event-driven architecture.
    • Updated Dockerfiles to include necessary package files for the build process.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 3, 2025

Walkthrough

The pull request refactors job dispatching and worker management in the event-worker and job-dispatch modules. The createDispatchExecutionJobWorker function is removed in favor of a new dispatchJobWorker, with corresponding updates in worker registration. The refactoring streamlines job queries, error handling, and logging. Additionally, new relationships between job and jobAgent are defined in the database schemas, and the channel definitions in the events package are extended to support dispatch jobs. A new dependency on @ctrlplane/events supports the updated dispatch process.

Changes

File(s) Change Summary
apps/event-worker/src/index.ts
apps/event-worker/src/job-dispatch/index.ts
apps/event-worker/src/workers/index.ts
Removed the import and invocation of createDispatchExecutionJobWorker in favor of a refactored dispatchJobWorker; updated the workers object to include a new entry for Channel.DispatchJob.
packages/db/src/schema/job-agent.ts
packages/db/src/schema/job.ts
Added a new export jobAgentRelations and enhanced jobRelations to include a one-to-one relationship linking the job table to jobAgent.
packages/events/src/index.ts
packages/events/src/types.ts
Introduced enhanced logging in the createWorker function and extended the ChannelMap type with a new entry for Channel.DispatchJob.
packages/job-dispatch/package.json
packages/job-dispatch/src/job-dispatch.ts
Added a new dependency on @ctrlplane/events and modified the dispatch logic to retrieve the queue dynamically using getQueue(Channel.DispatchJob).
packages/job-dispatch/src/index.ts
packages/job-dispatch/src/queue.ts
Removed the export statement for queue.js and deleted the queue.ts file, which contained job dispatch queue management logic.
apps/jobs/Dockerfile
apps/pty-proxy/Dockerfile
apps/webservice/Dockerfile
Added a command to copy the package.json file from the packages/events directory into the Docker image.

Possibly related PRs

  • init event lib #440: The changes in the main PR involve the removal of the createDispatchExecutionJobWorker function and its usage, while the retrieved PR introduces a new worker dispatchJobWorker and modifies the worker management logic, indicating a direct relationship in the context of worker functionality.
  • fix: Move events to job dispatch and use deleteResources utility function everywhere #222: The changes in the main PR, which involve the removal of the createDispatchExecutionJobWorker function, are related to the retrieved PR as both involve modifications to the job dispatching logic and the handling of worker functions, specifically the transition from the createDispatchExecutionJobWorker to the dispatchJobWorker.

Suggested reviewers

  • jsbroks

Poem

I'm a rabbit on the run, hopping through code all day,
Dispatching jobs with flair as functions find their way,
Gone are the old imports, a fresh flow now in view,
With logs, queues, and relations—everything's shiny and new!
Hoppy coding cheers from my burrow: 🐇✨


📜 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 4700c01 and e416cfd.

📒 Files selected for processing (1)
  • apps/webservice/Dockerfile (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Typecheck
  • GitHub Check: Lint
  • GitHub Check: build (linux/amd64)
🔇 Additional comments (1)
apps/webservice/Dockerfile (1)

40-40: New COPY Instruction for the Events Package

The addition of COPY packages/events/package.json ./packages/events/package.json is consistent with similar commands in this Dockerfile and across related services. It correctly ensures that the events package metadata is included in the image build context. Please verify that the file’s relative path remains accurate if the repository structure changes in the future.


🪧 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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
apps/event-worker/src/job-dispatch/index.ts (1)

10-37: Enhanced worker implementation with improved error handling.

The refactoring of the job dispatch worker is well-structured with several improvements:

  • Uses the standardized createWorker function
  • Optimizes database queries by fetching the job and its agent in a single request
  • Implements early returns for error conditions, improving code readability
  • Provides clear error logging

Consider adding try/catch blocks around the database query and the dispatchGithubJob call to handle potential exceptions:

export const dispatchJobWorker = createWorker(
  Channel.DispatchJob,
  async (queueJob) => {
    const { data } = queueJob;
    const { jobId } = data;

+   try {
      const job = await db.query.job.findFirst({
        where: eq(schema.job.id, jobId),
        with: { agent: true },
      });

      if (job == null) {
        queueJob.log(`Job ${jobId} not found`);
        return;
      }

      const { agent } = job;
      if (agent == null) {
        queueJob.log(`Job ${jobId} has no agent`);
        return;
      }

      if (agent.type === String(JobAgentType.GithubApp)) {
        queueJob.log(`Dispatching job ${jobId} to GitHub app`);
        await dispatchGithubJob(job);
      }
+   } catch (error) {
+     queueJob.log(`Error dispatching job ${jobId}: ${error.message}`);
+     // Consider updating job status to reflect the error
+   }
  },
);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 29ab609 and e3ab905.

📒 Files selected for processing (8)
  • apps/event-worker/src/index.ts (0 hunks)
  • apps/event-worker/src/job-dispatch/index.ts (1 hunks)
  • apps/event-worker/src/workers/index.ts (2 hunks)
  • packages/db/src/schema/job-agent.ts (2 hunks)
  • packages/db/src/schema/job.ts (1 hunks)
  • packages/events/src/index.ts (1 hunks)
  • packages/events/src/types.ts (1 hunks)
  • packages/validators/src/github/index.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • apps/event-worker/src/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/validators/src/github/index.ts
  • apps/event-worker/src/workers/index.ts
  • packages/db/src/schema/job-agent.ts
  • packages/events/src/types.ts
  • packages/db/src/schema/job.ts
  • apps/event-worker/src/job-dispatch/index.ts
  • packages/events/src/index.ts
🧬 Code Definitions (3)
apps/event-worker/src/workers/index.ts (1)
apps/event-worker/src/job-dispatch/index.ts (1)
  • dispatchJobWorker (10-37)
packages/db/src/schema/job-agent.ts (1)
packages/db/src/schema/job.ts (1)
  • job (74-106)
apps/event-worker/src/job-dispatch/index.ts (2)
packages/events/src/index.ts (1)
  • createWorker (9-23)
packages/db/src/schema/job.ts (1)
  • job (74-106)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: Lint
  • GitHub Check: Typecheck
🔇 Additional comments (8)
packages/validators/src/github/index.ts (1)

13-13: Addition of WorkflowJob enum member looks good!

The new WorkflowJob enum member is properly added to represent the "workflow_job" GitHub event type. This addition aligns with the new dispatch job worker functionality implemented elsewhere in the codebase.

packages/events/src/types.ts (1)

29-29: Type definition for DispatchJob channel is correct

The addition of the [Channel.DispatchJob]: { jobId: string } entry to the ChannelMap type provides proper type safety for the new dispatch job functionality. This simple structure with just a jobId suggests that job details are stored in the database and retrieved using this ID, which is a good practice.

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

2-2: Well-defined database relations

The addition of the jobAgentRelations export properly establishes the relationship between job agents and jobs in the database schema. This relation definition follows ORM best practices by explicitly declaring that a job agent can have many jobs, which aligns with the database schema where the job table has a jobAgentId field. This bidirectional relation enables efficient querying and improves code readability.

Also applies to: 7-7, 24-26

apps/event-worker/src/workers/index.ts (1)

6-7: Clean integration of the new dispatch job worker

The addition of the dispatchJobWorker import and its assignment to the Channel.DispatchJob entry in the workers object properly integrates the new worker into the existing system. This follows the established pattern for worker registration and enables the new job dispatching functionality to be managed within the same worker infrastructure.

Also applies to: 16-16

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

4-4: LGTM: Import logger for improved worker tracking.

Adding logging for worker creation is a good enhancement that will help with monitoring and debugging.


13-15: LGTM: Enhanced logging and code clarity.

Adding logging for worker creation is a good practice that improves monitoring capabilities. The explicit return keyword makes the function's intent clearer.

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

108-116: LGTM: Improved database schema relationship.

The addition of the one-to-one relationship between job and jobAgent is well-structured and properly implemented with correct field references. This enhancement will simplify queries that need to access job agent data.

apps/event-worker/src/job-dispatch/index.ts (1)

1-7: LGTM: Clean import restructuring.

The updated imports align well with the refactored worker implementation, particularly bringing in the createWorker function and the necessary database utilities.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (1)
packages/job-dispatch/src/job-dispatch.ts (1)

12-12: 🛠️ Refactor suggestion

Inconsistent queue usage pattern detected.

While dispatchRunbook now uses the new dynamic queue retrieval with getQueue(Channel.DispatchJob), the DispatchBuilder.dispatch method still uses the direct dispatchJobsQueue import. This inconsistency could lead to maintenance issues in the future.

Consider updating the bulk dispatch to also use the new queue retrieval mechanism:

- await dispatchJobsQueue.addBulk(
+ await getQueue(Channel.DispatchJob).addBulk(
  validJobsWithResolvedVariables.map((wf) => ({
    name: wf.id,
    data: { jobId: wf.id },
  })),
);

Also applies to: 97-103

🧹 Nitpick comments (1)
packages/job-dispatch/src/job-dispatch.ts (1)

12-12: Remove unused import if applicable.

After refactoring all code to use getQueue(Channel.DispatchJob), the dispatchJobsQueue import may become unused. Consider removing it once all usages are migrated.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e3ab905 and bc3cc96.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (2)
  • packages/job-dispatch/package.json (1 hunks)
  • packages/job-dispatch/src/job-dispatch.ts (2 hunks)
🧰 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/job-dispatch/src/job-dispatch.ts
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Typecheck
  • GitHub Check: Lint
  • GitHub Check: Format
  • GitHub Check: build (linux/amd64)
  • GitHub Check: build (linux/amd64)
🔇 Additional comments (3)
packages/job-dispatch/package.json (1)

29-29: Approval of New Dependency Addition

The newly added dependency @ctrlplane/events with version "workspace:*" is correctly included in the dependencies section. This change aligns with the refactoring in job dispatching and worker management as outlined in the PR objectives. Please ensure that the workspace resolution is properly configured to avoid any dependency resolution issues.

packages/job-dispatch/src/job-dispatch.ts (2)

6-6: Good addition of events module import.

The import of Channel and getQueue from @ctrlplane/events aligns with the PR's objective to refactor job dispatching and worker management.


137-137: Refactored job dispatch mechanism.

The change from using dispatchJobsQueue directly to using getQueue(Channel.DispatchJob) is a good implementation of the new worker format. This approach allows for more dynamic queue handling based on channel types.

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