Skip to content

fix: Get externalid from webhook#177

Merged
adityachoudhari26 merged 3 commits intomainfrom
external-id-webhook
Oct 27, 2024
Merged

fix: Get externalid from webhook#177
adityachoudhari26 merged 3 commits intomainfrom
external-id-webhook

Conversation

@adityachoudhari26
Copy link
Copy Markdown
Member

@adityachoudhari26 adityachoudhari26 commented Oct 27, 2024

Summary by CodeRabbit

  • New Features
    • Introduced new functions for handling workflow webhook events, including extractUuid for UUID extraction and getJob for retrieving job information.
  • Bug Fixes
    • Streamlined job status updates to ensure accurate handling based on job existence.
  • Chores
    • Removed the dependency on the p-retry package and associated retry logic for dispatching GitHub jobs.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Oct 27, 2024

Warning

Rate limit exceeded

@adityachoudhari26 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 11 minutes and 46 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Files that changed from the base of the PR and between f4e594b and 58a50bc.

Walkthrough

The pull request introduces several changes across multiple files in the @ctrlplane/event-worker project. Key modifications include the removal of the p-retry dependency from package.json, the deletion of the convertStatus function from github-utils.ts, and significant alterations to the dispatchGithubJob function in github.ts, which eliminates the retry logic for retrieving workflow runs. Additionally, new functions for handling workflow webhook events are added in handler.ts, enhancing job retrieval and status updating processes.

Changes

File Path Change Summary
apps/event-worker/package.json Removed dependency: "p-retry": "^6.2.0"
apps/event-worker/src/github-utils.ts Removed method: export const convertStatus = (status: string): JStatus
apps/event-worker/src/job-dispatch/github.ts Modified dispatchGithubJob: removed retry logic and associated error handling for workflow runs.
apps/webservice/src/app/api/github/webhook/handler.ts Added functions: extractUuid(str: string) and getJob(externalId: number, name: string). Modified handleWorkflowWebhookEvent function signature.

Possibly related PRs

  • fix: Show job external url #154: Modifications to the dispatchGithubJob function in github.ts, particularly the addition of an externalUrl variable, related to the removal of the p-retry dependency.
  • fix: External url button #158: Changes in the dispatchGithubJob function focusing on the removal of the externalUrl variable and related logging, reflecting ongoing modifications in job dispatching.

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.

// the externalRunId yet, as it depends on the job's instantiation. Therefore,
// the first event lacks the run ID, so we skip it and wait for the next event.
if (job == null) return;
.set({ status, externalId })
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

you can also generate the url at this point? I think

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

we are generating the URL below

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

🧹 Outside diff range and nitpick comments (3)
apps/event-worker/src/job-dispatch/github.ts (2)

Line range hint 89-106: Add error handling for workflow dispatch.

The workflow dispatch call is not wrapped in a try-catch block. If the dispatch fails, the error won't be properly handled and the job status won't be updated.

Consider adding error handling:

-  await octokit.actions.createWorkflowDispatch({
-    owner: parsed.data.owner,
-    repo: parsed.data.repo,
-    workflow_id: parsed.data.workflowId,
-    ref: ghOrg.branch,
-    inputs: {
-      job_id: je.id,
-    },
-    headers: {
-      "X-GitHub-Api-Version": "2022-11-28",
-      authorization: `Bearer ${installationToken.token}`,
-    },
-  });
+  try {
+    await octokit.actions.createWorkflowDispatch({
+      owner: parsed.data.owner,
+      repo: parsed.data.repo,
+      workflow_id: parsed.data.workflowId,
+      ref: ghOrg.branch,
+      inputs: {
+        job_id: je.id,
+      },
+      headers: {
+        "X-GitHub-Api-Version": "2022-11-28",
+        authorization: `Bearer ${installationToken.token}`,
+      },
+    });
+    await db.update(job).set({
+      status: JobStatus.Dispatched,
+      message: "Workflow dispatched successfully",
+    });
+  } catch (error) {
+    logger.error(`Failed to dispatch workflow for job ${je.id}:`, error);
+    await db.update(job).set({
+      status: JobStatus.DispatchFailed,
+      message: `Failed to dispatch workflow: ${error.message}`,
+    });
+  }

Line range hint 19-106: Consider updating job status after successful dispatch.

The function currently doesn't update the job status after successfully dispatching the workflow. This could lead to the job appearing stuck in its previous state.

Add a status update after successful dispatch as shown in the error handling diff above. This will help track the job's progress and indicate that it was successfully dispatched while waiting for the webhook to update its status with the external ID.

apps/webservice/src/app/api/github/webhook/workflow/handler.ts (1)

24-29: LGTM with a minor suggestion for input validation.

The UUID extraction logic is well-implemented. Consider adding input validation to handle undefined/null input gracefully.

 const extractUuid = (str: string) => {
+  if (!str) return null;
   const uuidRegex =
     /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/;
   const match = uuidRegex.exec(str);
   return match ? match[0] : null;
 };
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d44a6d8 and f4e594b.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (4)
  • apps/event-worker/package.json (0 hunks)
  • apps/event-worker/src/github-utils.ts (0 hunks)
  • apps/event-worker/src/job-dispatch/github.ts (1 hunks)
  • apps/webservice/src/app/api/github/webhook/workflow/handler.ts (1 hunks)
💤 Files with no reviewable changes (2)
  • apps/event-worker/package.json
  • apps/event-worker/src/github-utils.ts
🔇 Additional comments (3)
apps/event-worker/src/job-dispatch/github.ts (1)

17-17: Verify webhook implementation for external ID updates.

Since we're removing the polling mechanism for getting the run ID, we need to ensure the webhook handler properly updates the job's external ID when the workflow run is created.

Let's verify the webhook handler implementation:

apps/webservice/src/app/api/github/webhook/workflow/handler.ts (2)

59-61: LGTM: Improved job retrieval with early return.

The changes properly handle external ID from webhooks and implement a clean early return pattern when no job is found.


59-71: Verify webhook event field availability.

Let's ensure that all workflow webhook events contain the required fields.

✅ Verification successful

Required webhook fields are properly handled

The code safely handles the workflow run webhook event fields:

  • The id, status, conclusion, repository, and name fields are destructured from event.workflow_run
  • Null checks are in place for conclusion
  • The status is derived using proper fallback logic
  • Type definitions from @octokit/webhooks-types ensure type safety
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other webhook handlers to verify consistent field usage
rg -l "WorkflowRunEvent" | xargs rg "workflow_run\." -A 2

Length of output: 57


Script:

#!/bin/bash
# Let's first find the workflow event type definition and its usage
rg -A 5 "type WorkflowRunEvent" 

# Then search for workflow run related handlers
rg -A 10 "workflow.*run.*event"

Length of output: 67


Script:

#!/bin/bash
# Let's look at the imports and type definitions in the handler file
cat "apps/webservice/src/app/api/github/webhook/workflow/handler.ts"

# Also search for any GitHub webhook type definitions
fd -e ts -e js | xargs rg "interface.*WorkflowRun"

Length of output: 3042

Comment on lines +67 to +71
const externalId = id.toString();
await db
.update(schema.job)
.set({ status })
.where(eq(schema.job.externalId, id.toString()))
.returning()
.then(takeFirstOrNull);

// Addressing a race condition: When the job is created externally on GitHub,
// it triggers a webhook event. However, our system hasn't updated the job with
// the externalRunId yet, as it depends on the job's instantiation. Therefore,
// the first event lacks the run ID, so we skip it and wait for the next event.
if (job == null) return;
.set({ status, externalId })
.where(eq(schema.job.id, job.id));
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider using a transaction for atomic updates.

The status update and subsequent metadata update should be atomic to prevent potential race conditions.

-  await db
-    .update(schema.job)
-    .set({ status, externalId })
-    .where(eq(schema.job.id, job.id));
+  await db.transaction(async (tx) => {
+    await tx
+      .update(schema.job)
+      .set({ status, externalId })
+      .where(eq(schema.job.id, job.id));
+
+    const existingUrlMetadata = await tx
+      .select()
+      .from(schema.jobMetadata)
+      // ... rest of the metadata query ...
+
+    // ... metadata update logic ...
+    await tx
+      .insert(schema.jobMetadata)
+      // ... rest of the metadata insert ...
+  });

Committable suggestion was skipped due to low confidence.

Comment on lines +31 to +48
const getJob = async (externalId: number, name: string) => {
const jobFromExternalId = await db
.select()
.from(schema.job)
.where(eq(schema.job.externalId, externalId.toString()))
.then(takeFirstOrNull);

if (jobFromExternalId != null) return jobFromExternalId;

const uuid = extractUuid(name);
if (uuid == null) return null;

return db
.select()
.from(schema.job)
.where(eq(schema.job.id, uuid))
.then(takeFirstOrNull);
};
Copy link
Copy Markdown
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 for database operations.

The job retrieval logic is well-structured with a good fallback strategy. However, database operations could throw errors that should be handled gracefully.

 const getJob = async (externalId: number, name: string) => {
+  try {
     const jobFromExternalId = await db
       .select()
       .from(schema.job)
       .where(eq(schema.job.externalId, externalId.toString()))
       .then(takeFirstOrNull);

     if (jobFromExternalId != null) return jobFromExternalId;

     const uuid = extractUuid(name);
     if (uuid == null) return null;

     return db
       .select()
       .from(schema.job)
       .where(eq(schema.job.id, uuid))
       .then(takeFirstOrNull);
+  } catch (error) {
+    console.error('Failed to retrieve job:', error);
+    return null;
+  }
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const getJob = async (externalId: number, name: string) => {
const jobFromExternalId = await db
.select()
.from(schema.job)
.where(eq(schema.job.externalId, externalId.toString()))
.then(takeFirstOrNull);
if (jobFromExternalId != null) return jobFromExternalId;
const uuid = extractUuid(name);
if (uuid == null) return null;
return db
.select()
.from(schema.job)
.where(eq(schema.job.id, uuid))
.then(takeFirstOrNull);
};
const getJob = async (externalId: number, name: string) => {
try {
const jobFromExternalId = await db
.select()
.from(schema.job)
.where(eq(schema.job.externalId, externalId.toString()))
.then(takeFirstOrNull);
if (jobFromExternalId != null) return jobFromExternalId;
const uuid = extractUuid(name);
if (uuid == null) return null;
return db
.select()
.from(schema.job)
.where(eq(schema.job.id, uuid))
.then(takeFirstOrNull);
} catch (error) {
console.error('Failed to retrieve job:', error);
return null;
}
};

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