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: Deployment job graph popover #266

Merged
merged 5 commits into from
Dec 17, 2024
Merged

Conversation

adityachoudhari26
Copy link
Contributor

@adityachoudhari26 adityachoudhari26 commented Dec 16, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new DailyJobsChart component for visualizing job execution data.
    • Added JobHistoryPopover component to display job execution data in a popover format.
    • Enhanced the DeploymentPageContent with a new JobHistoryPopover button for accessing job history.
  • Bug Fixes

    • Simplified the dailyCount procedure under byWorkspaceId for improved functionality.
  • Documentation

    • Updated type definitions and method signatures for improved clarity and usability.

Copy link
Contributor

coderabbitai bot commented Dec 16, 2024

Walkthrough

This pull request introduces a new DailyJobsChart component for visualizing job execution data over a six-week period. The changes involve creating a reusable chart component in DailyJobsChart.tsx, refactoring the existing JobHistoryChart.tsx to use the new component, and adding a JobHistoryPopover to display job history in deployment pages. Additionally, the API router in job.ts is updated to support fetching daily job counts for specific deployments, enabling more granular job status tracking and visualization.

Changes

File Change Summary
apps/webservice/src/app/[workspaceSlug]/(app)/_components/DailyJobsChart.tsx New React component for visualizing job execution data with interactive chart and custom tooltip
apps/webservice/src/app/[workspaceSlug]/(app)/systems/JobHistoryChart.tsx Removed custom chart implementation, now uses DailyJobsChart component
apps/webservice/src/app/[workspaceSlug]/(app)/systems/[systemSlug]/deployments/[deploymentSlug]/releases/DeploymentPageContent.tsx Added JobHistoryPopover and adjusted layout
apps/webservice/src/app/[workspaceSlug]/(app)/systems/[systemSlug]/deployments/[deploymentSlug]/releases/JobHistoryPopover.tsx New component for displaying job history in a popover
packages/api/src/router/job.ts Added byDeploymentId router with dailyCount procedure for fetching deployment-specific job statistics

Sequence Diagram

sequenceDiagram
    participant User
    participant DeploymentPage
    participant JobHistoryPopover
    participant API
    participant DailyJobsChart

    User->>DeploymentPage: View Deployment
    DeploymentPage->>JobHistoryPopover: Render Popover Trigger
    User->>JobHistoryPopover: Click Popover
    JobHistoryPopover->>API: Fetch Daily Job Counts
    API-->>JobHistoryPopover: Return Job Counts
    JobHistoryPopover->>DailyJobsChart: Render Chart
    DailyJobsChart->>User: Display Interactive Job Statistics
Loading

Possibly related PRs

Suggested reviewers

  • zacharyblasczyk

Poem

🐰 Hop, hop, through data's domain,
Charts dancing with jobs' refrain,
Deployment stories now unfold,
In pixels bright and metrics bold,
A rabbit's view of progress clear! 📊

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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 (5)
apps/webservice/src/app/[workspaceSlug]/(app)/_components/DailyJobsChart.tsx (3)

110-115: Use user's locale instead of hardcoded 'en-US' for X-axis labels

Consider using the user's locale when formatting dates on the X-axis to enhance internationalization support.

Apply this diff:

- return date.toLocaleDateString("en-US", {
+ return date.toLocaleDateString(undefined, {

147-151: Use user's locale instead of hardcoded 'en-US' in tooltip date formatting

To support users from various locales, use the default locale when formatting dates in the tooltip.

Apply this diff:

- {new Date(label).toLocaleDateString("en-US", {
+ {new Date(label).toLocaleDateString(undefined, {

203-264: Refactor onClick handler for better readability

The onClick handler in the Bar component is lengthy and could be extracted into a separate function to improve readability and maintainability.

Apply this refactor:

+ const handleBarClick = (e: any) => {
+   const start = new Date(e.date);
+   const end = addDays(start, 1);
+ 
+   // ...existing code...
+ 
+   router.push(filterLink);
+ };
...
              <Bar
                key={status}
                dataKey={status.toLowerCase()}
                stackId="jobs"
                className="cursor-pointer"
                yAxisId="right"
                fill={color}
-               onClick={(e) => {
-                 // existing onClick code
-               }}
+               onClick={handleBarClick}
              />
apps/webservice/src/app/[workspaceSlug]/(app)/systems/[systemSlug]/deployments/[deploymentSlug]/releases/JobHistoryPopover.tsx (1)

37-37: Consider making PopoverContent width responsive

Rather than hardcoding the width, consider making the PopoverContent width responsive to enhance usability on various screen sizes.

Apply this diff:

- <PopoverContent className="w-[700px]">
+ <PopoverContent className="w-full max-w-[700px]">
packages/api/src/router/job.ts (1)

290-346: Consider extracting shared SQL query logic.

Both dailyCount procedures in byWorkspaceId and byDeploymentId share similar SQL query structure. Consider extracting the common logic into a reusable function to improve maintainability.

Example refactor:

+ const createDailyCountQuery = (
+   db: Tx,
+   dateTruncExpr: SQL,
+   whereClause: SQL
+ ) => {
+   const subquery = db
+     .select({
+       date: dateTruncExpr.as("date"),
+       status: schema.job.status,
+       countPerStatus: sql<number>`COUNT(*)`.as("countPerStatus"),
+     })
+     .from(schema.releaseJobTrigger)
+     .innerJoin(
+       schema.job,
+       eq(schema.releaseJobTrigger.jobId, schema.job.id),
+     )
+     .where(
+       and(
+         whereClause,
+         notInArray(schema.job.status, [
+           JobStatus.Pending,
+           JobStatus.Cancelled,
+           JobStatus.Skipped,
+         ]),
+       ),
+     )
+     .groupBy(dateTruncExpr, schema.job.status)
+     .as("sub");
+
+   return db
+     .select({
+       date: subquery.date,
+       totalCount: sql<number>`SUM(${subquery.countPerStatus})`.as(
+         "totalCount",
+       ),
+       statusCounts: sql<Record<JobStatus, number>>`
+         jsonb_object_agg(${subquery.status}, ${subquery.countPerStatus})
+       `.as("statusCounts"),
+     })
+     .from(subquery)
+     .groupBy(subquery.date)
+     .orderBy(subquery.date);
+ };

  byWorkspaceId: createTRPCRouter({
    dailyCount: protectedProcedure
      .input(z.object({ workspaceId: z.string().uuid(), timezone: z.string() }))
      .meta({
        authorizationCheck: ({ canUser, input }) =>
          canUser
            .perform(Permission.SystemList)
            .on({ type: "workspace", id: input.workspaceId }),
      })
      .query(async ({ ctx, input }) => {
        const dateTruncExpr = sql<Date>`date_trunc('day', ${schema.releaseJobTrigger.createdAt} AT TIME ZONE 'UTC' AT TIME ZONE '${sql.raw(input.timezone)}')`;
-       // ... existing query code ...
+       return createDailyCountQuery(
+         ctx.db,
+         dateTruncExpr,
+         eq(schema.system.workspaceId, input.workspaceId)
+       );
      }),
  }),

  byDeploymentId: createTRPCRouter({
    dailyCount: protectedProcedure
      .input(z.object({ deploymentId: z.string().uuid(), timezone: z.string() }))
      .meta({
        authorizationCheck: ({ canUser, input }) =>
          canUser
            .perform(Permission.JobList)
            .on({ type: "deployment", id: input.deploymentId }),
      })
      .query(async ({ ctx, input }) => {
        const dateTruncExpr = sql<Date>`date_trunc('day', ${schema.releaseJobTrigger.createdAt} AT TIME ZONE 'UTC' AT TIME ZONE '${sql.raw(input.timezone)}')`;
-       // ... existing query code ...
+       return createDailyCountQuery(
+         ctx.db,
+         dateTruncExpr,
+         eq(schema.release.deploymentId, input.deploymentId)
+       );
      }),
  }),

Also applies to: 232-289

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e863175 and d55e75b.

📒 Files selected for processing (5)
  • apps/webservice/src/app/[workspaceSlug]/(app)/_components/DailyJobsChart.tsx (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/(app)/systems/JobHistoryChart.tsx (2 hunks)
  • apps/webservice/src/app/[workspaceSlug]/(app)/systems/[systemSlug]/deployments/[deploymentSlug]/releases/DeploymentPageContent.tsx (4 hunks)
  • apps/webservice/src/app/[workspaceSlug]/(app)/systems/[systemSlug]/deployments/[deploymentSlug]/releases/JobHistoryPopover.tsx (1 hunks)
  • packages/api/src/router/job.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
apps/webservice/src/app/[workspaceSlug]/(app)/systems/[systemSlug]/deployments/[deploymentSlug]/releases/JobHistoryPopover.tsx (1)

Pattern **/*.{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.

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

Pattern **/*.{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.

apps/webservice/src/app/[workspaceSlug]/(app)/_components/DailyJobsChart.tsx (1)

Pattern **/*.{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/job.ts (1)

Pattern **/*.{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.

apps/webservice/src/app/[workspaceSlug]/(app)/systems/[systemSlug]/deployments/[deploymentSlug]/releases/DeploymentPageContent.tsx (1)

Pattern **/*.{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.

🔇 Additional comments (8)
apps/webservice/src/app/[workspaceSlug]/(app)/systems/JobHistoryChart.tsx (2)

13-13: Importing DailyJobsChart component

The DailyJobsChart component is correctly imported, promoting reusability and simplifying the codebase.


69-69: Rendering DailyJobsChart with dailyCounts data

DailyJobsChart is rendered with the appropriate dailyCounts prop, ensuring accurate visualization of job executions.

apps/webservice/src/app/[workspaceSlug]/(app)/systems/[systemSlug]/deployments/[deploymentSlug]/releases/JobHistoryPopover.tsx (1)

1-51: Implementation of JobHistoryPopover component is correct

The JobHistoryPopover component is well-structured and integrates the DailyJobsChart appropriately to display job execution data.

apps/webservice/src/app/[workspaceSlug]/(app)/systems/[systemSlug]/deployments/[deploymentSlug]/releases/DeploymentPageContent.tsx (3)

6-11: Importing additional icons from @tabler/icons-react

The import statements for the additional icons, including IconHistory, are correct.


39-39: Importing JobHistoryPopover component

The JobHistoryPopover component is correctly imported, enabling its use within this file.


144-165: Adding JobHistoryPopover for job execution data

The JobHistoryPopover is properly integrated, providing users with access to job execution data related to the deployment.

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

232-232: LGTM! Clean input declaration.

The consolidated input declaration maintains type safety while improving code readability.


290-346: LGTM! Well-scoped implementation with proper authorization.

The new router correctly implements deployment-level job counting with:

  • Proper authorization checks
  • Optimized SQL query using only necessary table joins
  • Consistent status filtering

@adityachoudhari26 adityachoudhari26 merged commit 6887251 into main Dec 17, 2024
6 checks passed
@adityachoudhari26 adityachoudhari26 deleted the deployment-job-graph branch December 17, 2024 18:34
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