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: Job distribution graph #152

Merged
merged 2 commits into from
Oct 20, 2024
Merged

fix: Job distribution graph #152

merged 2 commits into from
Oct 20, 2024

Conversation

adityachoudhari26
Copy link
Contributor

@adityachoudhari26 adityachoudhari26 commented Oct 20, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced job trigger data retrieval with a new structured method.
    • Added functionality to fetch daily job counts for improved job history tracking.
  • Bug Fixes

    • Updated logic for constructing job history charts to ensure accurate data representation.
  • Refactor

    • Improved organization of job trigger API procedures for better maintainability.

Copy link
Contributor

coderabbitai bot commented Oct 20, 2024

Walkthrough

The pull request introduces modifications to the job triggers fetching mechanism in the JobsPage and JobHistoryChart components. The API calls have been updated to a new structured method, transitioning from direct retrieval to a list-based approach. Additionally, a new daily count retrieval feature has been implemented in the JobHistoryChart, enhancing data processing. The router has been refactored to accommodate these changes, with the introduction of nested procedures for job triggers.

Changes

File Change Summary
apps/webservice/src/app/[workspaceSlug]/(job)/jobs/page.tsx Updated API call from api.job.config.byWorkspaceId(workspace.id) to api.job.config.byWorkspaceId.list(workspace.id) for fetching job triggers.
apps/webservice/src/app/[workspaceSlug]/systems/JobHistoryChart.tsx Changed API query from api.job.config.byWorkspaceId.useQuery to api.job.config.byWorkspaceId.list.useQuery and added api.job.config.byWorkspaceId.dailyCount.useQuery for daily job counts. Updated logic for chartData construction.
packages/api/src/router/job.ts Refactored releaseJobTriggerRouter to include nested procedures: list and dailyCount. Added SQL functionality for daily counts.

Possibly related PRs

  • refactor job policy checker app #151: The changes in the main PR regarding the update of API calls from byWorkspaceId to byWorkspaceId.list are related to the modifications in the JobHistoryChart component in the retrieved PR, which also updates the API query from byWorkspaceId.useQuery to byWorkspaceId.list.useQuery.

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9fbe8b4 and 2add81c.

📒 Files selected for processing (1)
  • packages/api/src/router/job.ts (2 hunks)
🧰 Additional context used
🔇 Additional comments (3)
packages/api/src/router/job.ts (3)

6-6: LGTM: New import for SQL functionality

The addition of the sql import from @ctrlplane/db is appropriate for the new dailyCount procedure implementation.


45-72: LGTM: Well-structured refactoring of byWorkspaceId procedure

The refactoring of the byWorkspaceId procedure into a nested structure with a list sub-procedure improves code organization while maintaining the original functionality. This change aligns well with the updates mentioned for JobHistoryChart.tsx and JobsPage.tsx.


73-102: ⚠️ Potential issue

Validate 'timezone' input to prevent SQL injection

The new dailyCount procedure adds valuable functionality for retrieving daily counts of release job triggers. However, the use of sql.raw(input.timezone) in the SQL query could potentially lead to SQL injection vulnerabilities if the input is not properly sanitized.

To mitigate this risk, consider validating input.timezone against a list of allowed timezones or using a library like moment-timezone to validate that the provided timezone is a valid IANA timezone identifier before using it in the SQL query.

Additionally, consider using parameterized queries instead of string interpolation for the timezone to further enhance security.


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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a2ab698 and 9fbe8b4.

📒 Files selected for processing (3)
  • apps/webservice/src/app/[workspaceSlug]/(job)/jobs/page.tsx (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/systems/JobHistoryChart.tsx (2 hunks)
  • packages/api/src/router/job.ts (2 hunks)
🧰 Additional context used
🔇 Additional comments (5)
apps/webservice/src/app/[workspaceSlug]/(job)/jobs/page.tsx (1)

24-26: LGTM! Verify error handling and type definitions.

The update to use api.job.config.byWorkspaceId.list(workspace.id) aligns with the reported API refactoring. The change is straightforward and doesn't affect the component's logic.

To ensure the change is fully compatible, please verify:

  1. Error handling for the new API call
  2. Type definitions for the returned data

Run the following script to check for any type-related changes:

apps/webservice/src/app/[workspaceSlug]/systems/JobHistoryChart.tsx (4)

28-31: Verify the updated query method and data structure

The query has been updated to api.job.config.byWorkspaceId.list.useQuery. Ensure that the data returned by this new endpoint matches the expected structure used in the component, especially when accessing releaseJobTriggers.data.


33-36: Ensure correct timezone handling in daily counts query

The dailyCounts query uses the client's timezone:

timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,

Verify that using the client's timezone aligns with the server's data and that it correctly reflects the desired timezone for all users, particularly in a multi-timezone context.


41-42: Check date comparisons for timezone consistency

When comparing dates using isSameDay(c.date, d):

jobs: dailyCounts.data?.find((c) => isSameDay(c.date, d))?.count ?? 0,

Ensure that both c.date and d are in the same timezone or adjusted appropriately to prevent any mismatches due to timezone differences.


Line range hint 71-73: Confirm data structure after query update

With the updated query, verify that releaseJobTriggers.data has the expected structure. Ensure that accessing t.job.status is valid and that t.job exists in the returned data.

Comment on lines 73 to 96
dailyCount: protectedProcedure
.input(
z.object({
workspaceId: z.string().uuid(),
timezone: z.string(),
}),
)
.query(async ({ ctx, input }) => {
const dateTruncExpr = sql<Date>`date_trunc('day', ${releaseJobTrigger.createdAt} AT TIME ZONE 'UTC' AT TIME ZONE '${sql.raw(input.timezone)}')`;
return ctx.db
.select({
date: dateTruncExpr.as("date"),
count: sql<number>`COUNT(*)`.as("count"),
})
.from(releaseJobTrigger)
.innerJoin(
environment,
eq(releaseJobTrigger.environmentId, environment.id),
)
.innerJoin(system, eq(environment.systemId, system.id))
.where(eq(system.workspaceId, input.workspaceId))
.groupBy(dateTruncExpr)
.orderBy(dateTruncExpr);
}),
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 missing authorization check to 'dailyCount' procedure

The dailyCount procedure currently lacks an authorization check, which could allow unauthorized access to sensitive data. To ensure that only authorized users can access this endpoint, please add an authorizationCheck similar to the one used in the list procedure.

Apply this diff to add the authorization check:

  dailyCount: protectedProcedure
+   .meta({
+     authorizationCheck: ({ canUser, input }) =>
+       canUser
+         .perform(Permission.SystemList)
+         .on({ type: "workspace", id: input.workspaceId }),
+   })
    .input(
      z.object({
        workspaceId: z.string().uuid(),
        timezone: z.string(),
      }),
    )
📝 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
dailyCount: protectedProcedure
.input(
z.object({
workspaceId: z.string().uuid(),
timezone: z.string(),
}),
)
.query(async ({ ctx, input }) => {
const dateTruncExpr = sql<Date>`date_trunc('day', ${releaseJobTrigger.createdAt} AT TIME ZONE 'UTC' AT TIME ZONE '${sql.raw(input.timezone)}')`;
return ctx.db
.select({
date: dateTruncExpr.as("date"),
count: sql<number>`COUNT(*)`.as("count"),
})
.from(releaseJobTrigger)
.innerJoin(
environment,
eq(releaseJobTrigger.environmentId, environment.id),
)
.innerJoin(system, eq(environment.systemId, system.id))
.where(eq(system.workspaceId, input.workspaceId))
.groupBy(dateTruncExpr)
.orderBy(dateTruncExpr);
}),
dailyCount: protectedProcedure
.meta({
authorizationCheck: ({ canUser, input }) =>
canUser
.perform(Permission.SystemList)
.on({ type: "workspace", id: input.workspaceId }),
})
.input(
z.object({
workspaceId: z.string().uuid(),
timezone: z.string(),
}),
)
.query(async ({ ctx, input }) => {
const dateTruncExpr = sql<Date>`date_trunc('day', ${releaseJobTrigger.createdAt} AT TIME ZONE 'UTC' AT TIME ZONE '${sql.raw(input.timezone)}')`;
return ctx.db
.select({
date: dateTruncExpr.as("date"),
count: sql<number>`COUNT(*)`.as("count"),
})
.from(releaseJobTrigger)
.innerJoin(
environment,
eq(releaseJobTrigger.environmentId, environment.id),
)
.innerJoin(system, eq(environment.systemId, system.id))
.where(eq(system.workspaceId, input.workspaceId))
.groupBy(dateTruncExpr)
.orderBy(dateTruncExpr);
}),

}),
)
.query(async ({ ctx, input }) => {
const dateTruncExpr = sql<Date>`date_trunc('day', ${releaseJobTrigger.createdAt} AT TIME ZONE 'UTC' AT TIME ZONE '${sql.raw(input.timezone)}')`;
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 'timezone' input to prevent SQL injection

Using sql.raw(input.timezone) directly interpolates user input into the SQL query, which could lead to SQL injection vulnerabilities if the input is not properly sanitized. To mitigate this risk, validate input.timezone against a list of allowed timezones.

Apply this diff to validate the timezone input:

 .input(
   z.object({
     workspaceId: z.string().uuid(),
-    timezone: z.string(),
+    timezone: z.enum([
+      'UTC',
+      'America/New_York',
+      'Europe/London',
+      'Asia/Tokyo',
+      // Add all supported time zones
+    ]),
 ),

Alternatively, consider using a library like moment-timezone to validate that the provided timezone is a valid IANA timezone identifier before using it in the SQL query.

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