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: Optimize release metadata keys query #161

Merged
merged 1 commit into from
Oct 22, 2024

Conversation

adityachoudhari26
Copy link
Contributor

@adityachoudhari26 adityachoudhari26 commented Oct 22, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced metadata handling in the application, providing separate queries for workspace and system metadata keys.
    • Conditional loading indicators for improved user experience during data fetching.
    • Streamlined access to release metadata through distinct procedures for system and workspace.
  • Bug Fixes

    • Improved logic for fetching metadata keys, ensuring more accurate data retrieval.
  • Documentation

    • Updated documentation to reflect the changes in metadata retrieval processes.

Copy link
Contributor

coderabbitai bot commented Oct 22, 2024

Walkthrough

The pull request introduces significant changes to the MetadataConditionRender component and the releaseRouter. In the component, the useParams hook is explicitly typed, and the fetching logic for metadata keys is refactored into two separate queries: workspaceMetadataKeys and systemMetadataKeys. The releaseRouter is restructured to replace the single metadataKeys procedure with nested procedures bySystem and byWorkspace, enhancing access control and filtering based on UUIDs.

Changes

File Path Change Summary
apps/webservice/src/app/[workspaceSlug]/_components/release-condition/MetadataConditionRender.tsx Refactored metadata key fetching logic into two queries; updated loading state handling and rendering logic.
packages/api/src/router/release.ts Restructured metadataKeys into nested bySystem and byWorkspace procedures with updated authorization checks. Removed workspace import.

Possibly related PRs

  • fix: Remove semver and regex release filter #160: The changes in this PR involve modifications to the DeploymentControl.tsx component, which includes the ReleaseConditionRender component. This is directly related to the main PR's updates to the MetadataConditionRender component, as both involve handling release conditions and improving the user interface for managing these conditions.

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 (1)
apps/webservice/src/app/[workspaceSlug]/_components/release-condition/MetadataConditionRender.tsx (1)

95-109: Handle empty metadata keys gracefully

If filteredMetadataKeys is empty while not loading, the popover will display an empty list, which might confuse users. Consider displaying a message indicating that no metadata keys were found.

You can modify the rendering logic as follows:

{!loadingMetadataKeys && filteredMetadataKeys.length === 0 ? (
  <div className="p-2 text-sm text-muted-foreground">
    No metadata keys found
  </div>
) : (
  filteredMetadataKeys.map((k) => (
    <Button
      variant="ghost"
      size="sm"
      key={k}
      className="w-full rounded-none text-left"
      onClick={() => {
        setKey(k);
        setOpen(false);
      }}
    >
      <div className="w-full">{k}</div>
    </Button>
  ))
)}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f204c25 and a7acccb.

📒 Files selected for processing (2)
  • apps/webservice/src/app/[workspaceSlug]/_components/release-condition/MetadataConditionRender.tsx (4 hunks)
  • packages/api/src/router/release.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (3)
packages/api/src/router/release.ts (3)

420-437: Verify authorization checks align with the intended permissions

Ensure that performing Permission.ReleaseGet on a system entity provides the correct level of access for fetching release metadata keys. If there are specific permissions for metadata access, consider using those instead to maintain precise access control.


439-457: Verify authorization checks align with the intended permissions

Similarly, confirm that performing Permission.ReleaseGet on a workspace entity is appropriate for accessing workspace-level release metadata keys. Adjust the permission if a more specific one is applicable.


431-436: Optimize query performance by indexing relevant columns

To improve query performance, especially on large datasets, consider adding indexes on the columns used in the WHERE and JOIN clauses, such as releaseMetadata.releaseId, deployment.systemId, and system.workspaceId. This can speed up data retrieval and reduce query execution time.

[performance]

Also applies to: 450-456

Comment on lines +71 to +75
const loadingMetadataKeys =
workspaceQ.isLoading ||
systemQ.isLoading ||
workspaceMetadataKeys.isLoading ||
systemMetadataKeys.isLoading;
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 query failures

Currently, the code does not handle potential errors from the queries. To enhance user experience, consider checking for errors and providing appropriate feedback if any query fails.

You can check the isError property of your queries and display an error message or fallback UI:

if (
  workspaceQ.isError ||
  systemQ.isError ||
  workspaceMetadataKeys.isError ||
  systemMetadataKeys.isError
) {
  return <div className="p-2 text-sm text-red-500">Error loading metadata keys.</div>;
}

Comment on lines +33 to +36
const systemQ = api.system.bySlug.useQuery(
{ workspaceSlug, systemSlug: systemSlug ?? "" },
{ enabled: systemSlug != 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

Avoid passing empty systemSlug when it is null

When systemSlug is null, the query is still receiving systemSlug: "", which may not be necessary and could lead to unintended behavior. It's better to conditionally include systemSlug only when it is defined.

Consider modifying the query parameters as follows:

const systemQ = api.system.bySlug.useQuery(
-  { workspaceSlug, systemSlug: systemSlug ?? "" },
+  systemSlug ? { workspaceSlug, systemSlug } : undefined,
  { enabled: systemSlug != 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 systemQ = api.system.bySlug.useQuery(
{ workspaceSlug, systemSlug: systemSlug ?? "" },
{ enabled: systemSlug != null },
);
const systemQ = api.system.bySlug.useQuery(
systemSlug ? { workspaceSlug, systemSlug } : undefined,
{ enabled: systemSlug != null },
);

Comment on lines +420 to +437
bySystem: protectedProcedure
.meta({
authorizationCheck: ({ canUser, input }) =>
canUser.perform(Permission.ReleaseGet).on({
type: "system",
id: input,
}),
})
.input(z.string().uuid())
.query(async ({ input, ctx }) =>
ctx.db
.selectDistinct({ key: releaseMetadata.key })
.from(release)
.innerJoin(releaseMetadata, eq(releaseMetadata.releaseId, release.id))
.innerJoin(deployment, eq(release.deploymentId, deployment.id))
.where(eq(deployment.systemId, input))
.then((r) => r.map((row) => row.key)),
),
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider refactoring duplicated code in metadataKeys procedures

The bySystem and byWorkspace procedures share nearly identical query logic, differing mainly in the authorization checks and the where clause conditions. To enhance maintainability and reduce code duplication, consider abstracting the common query logic into a shared helper function or method that accepts parameters for the varying parts, such as the entity type and ID.

Also applies to: 439-457

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