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: External url button #158

Merged
merged 1 commit into from
Oct 22, 2024
Merged

fix: External url button #158

merged 1 commit into from
Oct 22, 2024

Conversation

adityachoudhari26
Copy link
Contributor

@adityachoudhari26 adityachoudhari26 commented Oct 22, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced job handling with the introduction of external link processing in the TargetReleaseTable, allowing users to view and interact with associated external links.
    • Added job status and reason enums to improve job state management.
  • Bug Fixes

    • Streamlined job metadata handling by removing unnecessary variables and improving logging for job dispatch processes.
  • Tests

    • Comprehensive test coverage added for the determineVariablesForReleaseJob function, ensuring robust handling of various job scenarios.

Copy link
Contributor

coderabbitai bot commented Oct 22, 2024

Walkthrough

The pull request introduces several changes across multiple files, primarily focusing on the removal of the externalUrl variable from the job dispatching logic, adjustments to the TargetReleaseTable component to handle external links, and enhancements to job metadata handling in the API router. The database schema is updated to drop the external_url column, and new enums and types are added for better structure and type safety. Additionally, new tests are introduced for the determineVariablesForReleaseJob function to ensure comprehensive coverage of its logic.

Changes

File Change Summary
apps/event-worker/src/job-dispatch/github.ts - Removed externalUrl variable and related references in logging and database updates.
- Modified destructuring of pRetry result.
- Updated logging to include only runId and status.
apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/TargetReleaseTable.tsx - Added imports for IconExternalLink and buttonVariants.
- Updated rendering logic to process and display external links associated with jobs, modifying job row structure to include new links section.
packages/api/src/router/job.ts - Added import for jobMetadata.
- Introduced left join with jobMetadata in byReleaseId procedure, updating the job object mapping to include a metadata field.
packages/db/drizzle/0018_round_franklin_richards.sql - Dropped external_url column from the job table, with a safeguard for non-existence.
packages/db/drizzle/meta/_journal.json - Added new journal entry with attributes for versioning in the PostgreSQL database.
packages/db/src/schema/job.ts - Added enums jobStatus and jobReason.
- Removed externalUrl field from job table schema.
- Introduced new types and methods for JobMetadata, JobVariable, and their respective creation and update schemas.
packages/job-dispatch/src/test/job-variables-deployment.test.ts - Introduced tests for determineVariablesForReleaseJob, mocking utilities and covering various scenarios to enhance test coverage.

Possibly related PRs

  • fix: Show job external url #154: The changes in this PR involve the addition of the externalUrl variable in the dispatchGithubJob function, which is directly related to the removal of the externalUrl variable in the main PR, indicating a shift in how external URLs are handled in job dispatching.
  • fix: Check existence from identifiers #155: This PR modifies the upsertTargets function to change how targets are processed, which may relate to the overall job handling and dispatching logic, although it does not directly reference the externalUrl variable.
  • fix: Redeploy to target button #157: The modifications in this PR include changes to the TargetDropdownMenu and TargetReleaseTable components, which may indirectly relate to how job statuses and external URLs are displayed or managed in the UI, but do not directly connect to the changes in the main PR regarding the externalUrl.

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

🧹 Outside diff range and nitpick comments (4)
packages/db/src/schema/job.ts (1)

Line range hint 71-93: LGTM! Consider adding JSDoc comments for better documentation.

The addition of new types (JobMetadata, Job, JobStatus) and the updateJob schema improves type safety and allows for partial updates, which is a good practice. The new jobVariable table and its associated types and schemas seem to be a well-structured addition for storing job-specific variables.

Consider adding JSDoc comments to the exported types and functions for better documentation. For example:

/** Represents the metadata associated with a job */
export type JobMetadata = InferSelectModel<typeof jobMetadata>;

/** Represents a job in the system */
export type Job = InferSelectModel<typeof job>;

/** Represents the possible statuses of a job */
export type JobStatus = Job["status"];

/** Schema for updating a job, allowing partial updates */
export const updateJob = createInsertSchema(job)
  .omit({
    id: true,
    jobAgentConfig: true,
    createdAt: true,
    updatedAt: true,
  })
  .partial();
apps/event-worker/src/job-dispatch/github.ts (1)

108-108: LGTM! Consider adding a comment for clarity.

The removal of the url property from the destructuring assignment is consistent with the overall changes to remove external URL handling. This change aligns well with the database schema update and simplifies the job dispatching logic.

Consider adding a brief comment explaining why the url is no longer needed:

-    const { runId: runId_, status: status_ } = await pRetry(
+    // Note: 'url' is no longer used as external URL handling has been removed
+    const { runId: runId_, status: status_ } = await pRetry(
apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/TargetReleaseTable.tsx (2)

105-125: Handle empty links object to avoid rendering issues

If links is an empty object, the code will render an empty container. Consider adding a check to ensure links has entries before rendering.

Apply this diff:

 {links != null && Object.keys(links).length > 0 && (
   <div className="flex items-center gap-1">
     {Object.entries(links).map(([label, url]) => (
       // ... rest of the code

75-76: Fix conditional class rendering in TableRow

Using logical AND (&&) inside cn may result in unintended class names when the condition is false. It's better to use a ternary operator for clarity.

Apply this diff:

 className={cn(
-  idx !== jobs.length - 1 && "border-b-neutral-800/50",
+  idx !== jobs.length - 1 ? "border-b-neutral-800/50" : ""
)}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2da5458 and 3e8a581.

📒 Files selected for processing (7)
  • apps/event-worker/src/job-dispatch/github.ts (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/TargetReleaseTable.tsx (2 hunks)
  • packages/api/src/router/job.ts (3 hunks)
  • packages/db/drizzle/0018_round_franklin_richards.sql (1 hunks)
  • packages/db/drizzle/meta/_journal.json (1 hunks)
  • packages/db/src/schema/job.ts (1 hunks)
  • packages/job-dispatch/src/test/job-variables-deployment.test.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • packages/job-dispatch/src/test/job-variables-deployment.test.ts
✅ Files skipped from review due to trivial changes (1)
  • packages/db/drizzle/0018_round_franklin_richards.sql
🧰 Additional context used
🔇 Additional comments (4)
packages/db/src/schema/job.ts (1)

Line range hint 1-93: Overall changes look good. Confirm the removal of externalUrl.

The additions of new types, enums, and schemas improve the structure and type safety of the job-related data. These changes align well with the objectives mentioned in the PR summary.

Although not directly visible in the provided code segment, the AI-generated summary mentioned the removal of the externalUrl field from the job table. Let's verify this change:

If the script confirms the removal, no further action is needed. If it doesn't, please double-check the removal of externalUrl from the job table.

packages/db/drizzle/meta/_journal.json (1)

130-136: LGTM: New migration entry added correctly.

The new entry (idx: 18) has been added to the journal with the correct structure and format. This entry corresponds to the migration that removes the external_url column from the job table, as mentioned in the PR summary.

A few observations:

  1. The idx value (18) is sequential and correct.
  2. The version remains "7", consistent with previous entries.
  3. The when timestamp (1729564036579) is later than the previous entry, maintaining chronological order.
  4. The tag "0018_round_franklin_richards" follows the naming convention and matches the idx.
  5. The breakpoints value is set to true, consistent with other entries.

This change aligns with the broader updates mentioned in the AI summary, particularly the removal of the external_url column from the job table.

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

15-15: Import of jobMetadata is necessary and correct

The addition of jobMetadata to the imports reflects its usage in subsequent queries and ensures that the module is available for use.


193-196: Validate the additional leftJoin statements for necessity and performance

The inclusion of leftJoin with jobMetadata, environmentPolicy, and environmentPolicyReleaseWindow enriches the data retrieved by the query. However, these joins can impact query performance, especially with large datasets. Ensure that these joins are necessary for the functionality and consider indexing the joined columns to optimize performance.

If these joins are crucial, confirm that appropriate indexes exist on the following columns to improve query execution speed:

  • jobMetadata.jobId
  • environment.policyId
  • environmentPolicyReleaseWindow.policyId

{Object.entries(links).map(([label, url]) => (
<Link
key={label}
href={url}
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

Validate URLs before rendering

When rendering external links, ensure that the URLs are valid and safe. This helps prevent potential security risks such as XSS attacks.

Consider validating the url before using it in the href attribute. You can use the built-in URL constructor for validation:

 <Link
   key={label}
-  href={url}
+  href={(() => {
+    try {
+      const safeUrl = new URL(url);
+      return safeUrl.toString();
+    } catch {
+      console.error('Invalid URL:', url);
+      return '#';
+    }
+  })()}
   target="_blank"
   rel="noopener noreferrer"
   className={buttonVariants({
     variant: "secondary",
     size: "sm",
     className: "gap-1",
   })}
 >

Committable suggestion was skipped due to low confidence.

Comment on lines +68 to +69
? (JSON.parse(linksMetadata) as Record<string, string>)
: null;
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

Add error handling for JSON parsing

If linksMetadata contains invalid JSON, JSON.parse will throw an error, potentially causing the component to crash. Consider adding error handling to manage parsing errors gracefully.

Apply this diff to add error handling:

 const links =
   linksMetadata != null
-    ? (JSON.parse(linksMetadata) as Record<string, string>)
+    ? (() => {
+        try {
+          return JSON.parse(linksMetadata) as Record<string, string>;
+        } catch (e) {
+          console.error('Failed to parse linksMetadata:', e);
+          return null;
+        }
+      })()
     : 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
? (JSON.parse(linksMetadata) as Record<string, string>)
: null;
? (() => {
try {
return JSON.parse(linksMetadata) as Record<string, string>;
} catch (e) {
console.error('Failed to parse linksMetadata:', e);
return null;
}
})()
: null;

Comment on lines +209 to +212
job: {
...v[0]!.job,
metadata: v.map((t) => t.job_metadata).filter(isPresent),
},
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

Ensure safe access to array elements and handle potential undefined values

The usage of non-null assertion ! in v[0]! assumes that the array v is not empty. If v can be an empty array, accessing v[0]! will result in an undefined value and could lead to runtime errors when properties are accessed. Consider adding a check to ensure v is not empty before accessing its elements.

Apply this diff to safely access the first element of the array:

- ...v[0]!.release_job_trigger,
+ ...(v[0]?.release_job_trigger || {}),

Similarly, update the subsequent usages:

- job: {
-   ...v[0]!.job,
-   metadata: v.map((t) => t.job_metadata).filter(isPresent),
- },
+ job: v[0]?.job
+   ? {
+       ...v[0].job,
+       metadata: v.map((t) => t.job_metadata).filter(isPresent),
+     }
+   : undefined,

This ensures that you only access properties if v[0] is defined.

Committable suggestion was skipped due to low confidence.

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