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

feat: Query logs component #2879

Merged
merged 70 commits into from
Mar 31, 2025
Merged

feat: Query logs component #2879

merged 70 commits into from
Mar 31, 2025

Conversation

MichaelUnkey
Copy link
Collaborator

@MichaelUnkey MichaelUnkey commented Feb 7, 2025

What does this PR do?

Fixes # (issue)

If there is not an issue for this, please create one first. This is used to tracking purposes and also helps use understand why this PR exists

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Chore (refactoring code, technical debt, workflow improvements)
  • Enhancement (small improvements)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How should this be tested?

  • Test A
  • Test B

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read Contributing Guide
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand areas
  • Ran pnpm build
  • Ran pnpm fmt
  • Checked for warnings, there are none
  • Removed all console.logs
  • Merged the latest changes from main onto my branch with git pull origin main
  • My changes don't cause any responsiveness issues

Appreciated

  • If a UI change was made: Added a screen recording or screenshots to this PR
  • Updated the Unkey Docs if changes were necessary

Summary by CodeRabbit

  • New Features

    • Launched a comprehensive query management interface in the dashboard logs, featuring a popover with “Recent” and “Saved” tabs. Users can view query details including user info, timestamps, paths, methods, and status indicators, with interactive bookmark toggling and toast notifications.

    • Expanded the icon library with new visuals and an extra "2xl" size option for improved UI clarity.

  • Tests

    • Added unit tests to ensure reliable bookmarked filter behavior.
  • Style

    • Enhanced layout spacing and implemented consistent scrollbar hiding across browsers.

Summary by CodeRabbit

  • New Features

    • Added an interactive queries interface in the logs dashboard that lets users toggle query visibility, switch between recent and saved views, and quickly manage query filters.

    • Introduced intuitive empty state screens to guide users when no queries or filters are available.

    • New components for displaying query filters, including ListGroup, StatusRow, MethodRow, and others to enhance user interaction.

  • Enhancements

    • Improved filter management with flexible bookmarking and sorting.

    • Refined control layouts and spacing for a cleaner, more cohesive user experience.

    • Expanded the icon set for consistent visual feedback.

  • Tests

    • Implemented tests to ensure reliable filtering and bookmarking functionality.

Summary by CodeRabbit

  • New Features

    • Introduced a new LogsQueries component for managing audit log queries with filter states and a popover interface.
    • Added a QueriesPopover for selecting and managing saved queries with keyboard navigation support.
    • Enhanced log query handling with new utility functions for formatting and managing filter values.
    • Expanded the icon library with new icons, including Book2, Bookmark, Bucket, and more.
    • Introduced a context for managing query parameters and filters in a React application.
    • Added new components for better organization of controls, including ControlsContainer, ControlsLeft, and ControlsRight.
  • Tests

    • Added comprehensive tests to ensure reliable bookmark and filter management functionality.

Sorry, something went wrong.

Copy link

changeset-bot bot commented Feb 7, 2025

⚠️ No Changeset found

Latest commit: 2fe3554

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link

vercel bot commented Feb 7, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
dashboard ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 31, 2025 2:00pm
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 31, 2025 2:00pm
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 31, 2025 2:00pm
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 31, 2025 2:00pm

Copy link
Contributor

coderabbitai bot commented Feb 7, 2025

📝 Walkthrough

Walkthrough

This pull request introduces a comprehensive update to the dashboard’s query management and icon libraries. New components such as LogsQueries, EmptyQueries, ListGroup, QueriesPopover, QueriesTabs, QueriesToast, and QueriesItemRow have been added, along with a new context and utility functions to format and manage query filters. Existing control layouts have been refactored to use modular components (ControlsContainer, ControlsLeft, ControlsRight). Additionally, the icon set is expanded with new icons and updates to size mapping, and a new hook (with tests) for bookmarked filters is implemented.

Changes

File(s) Change Summary
apps/dashboard/app/(app)/logs/components/controls/components/logs-queries/index.tsx
apps/dashboard/app/(app)/audit/components/controls/components/logs-queries/index.tsx
apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/controls/components/logs-queries/index.tsx
Added new LogsQueries components that utilize the useFilters hook and render a QueriesPopover with interactive toggling.
apps/dashboard/app/(app)/logs/components/controls/index.tsx
apps/dashboard/app/(app)/ratelimits/_components/controls/index.tsx
apps/dashboard/app/(app)/apis/_components/controls/index.tsx
apps/dashboard/app/(app)/audit/components/controls/index.tsx
apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/controls/index.tsx
apps/dashboard/app/(app)/ratelimits/[namespaceId]/_overview/components/controls/index.tsx
Refactored control layouts to use modular components—ControlsContainer, ControlsLeft, and ControlsRight—instead of nested <div>s.
apps/dashboard/components/logs/queries/*.tsx
(Empty, ListGroup, QueriesMadeBy, QueriesOverflow, QueriesPill, QueriesPopover, QueriesTabs, QueriesToast, QueriesItemRow)
Introduced new components for displaying and interacting with query filters including empty state, list groups, user info, overflow handling, pill displays, a popover interface, tab navigation, toast messages, and individual query rows.
apps/dashboard/components/logs/hooks/use-bookmarked-filters.ts
apps/dashboard/components/logs/hooks/use-bookmarked-filters.test.ts
apps/dashboard/components/logs/queries/utils.ts
apps/dashboard/app/(app)/audit/components/controls/components/logs-queries/utils.ts
apps/dashboard/app/(app)/logs/components/controls/components/logs-queries/utils.ts
apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/controls/components/logs-queries/utils.ts
apps/dashboard/components/logs/queries/queries-context.tsx
Added a new hook for managing bookmarked filters (with accompanying tests), new utility files for formatting filter values and retrieving icons, and a queries context to manage global filter state.
internal/icons/src/*
(Multiple icon files, props.ts, index.ts)
Expanded the icon library with new icons (e.g., Book2, Bookmark, ChartActivity2, etc.), updated size mappings (including a new "2xl" option), and modified exports in the index file.
apps/dashboard/styles/tailwind/tailwind.css
internal/ui/colors.css
apps/engineering/app/components/icon-swatch.tsx
apps/dashboard/app/(app)/logs/datetime/datetime-popover.tsx
Introduced new CSS variables (e.g., --shadow-lg), added rules for hiding scrollbars, and made minor class name reordering adjustments in various UI components.
apps/dashboard/components/logs/controls-container.tsx Added new container components (ControlsContainer, ControlsLeft, ControlsRight) to further modularize the control layouts.

Sequence Diagram(s)

Loading
sequenceDiagram
    participant U as User
    participant LQ as LogsQueries
    participant QP as QueriesPopover
    participant UF as useFilters / useBookmarkedFilters
    participant LS as localStorage

    U->>LQ: Click query toggle button
    LQ->>QP: Open popover with filter props
    QP->>UF: Retrieve & update filter state
    UF->>LS: Persist filter changes
    LS-->>UF: Return saved filters
    QP-->>LQ: Render updated queries

Possibly related PRs

  • fix: ratelimits ui filters and logs ordering #2811: The changes in the main PR, which introduce a new LogsQueries component that utilizes the QueriesPopover, are related to the retrieved PR as both involve modifications to the handling and display of log queries, specifically through the use of similar components for managing filters.
  • feat: new filter logic #2804: The changes in the main PR, which introduce a new LogsQueries component utilizing the useFilters hook, are related to the retrieved PR that also implements filter management through the useFilters hook in the ControlCloud component, indicating a shared focus on filter functionality.
  • fix(dashboard): "No bucket found" message position on Audit Logs page #2413: The changes in the main PR, which introduce a new LogsQueries component and its integration into the dashboard, are related to the retrieved PR as both involve modifications to the handling and display of log queries, specifically through the use of the QueriesPopover component. Both PRs enhance the user interface for managing queries in the dashboard context.

Suggested labels

Improvement, Needs Approval

Suggested reviewers

  • mcstepp
  • perkinsjr
  • ogzhanolguncu

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fc70b4f and 2fe3554.

📒 Files selected for processing (1)
  • apps/dashboard/components/logs/datetime/datetime-popover.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/dashboard/components/logs/datetime/datetime-popover.tsx

🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

github-actions bot commented Feb 7, 2025

Thank you for following the naming conventions for pull request titles! 🙏

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 (6)
apps/dashboard/app/(app)/audit/components/controls/components/logs-queries/utils.ts (6)

48-48: Remove the accidentally mixed comment with code.

There appears to be a leftover comment that includes what looks like old code definition for the transformed variable. This could cause confusion during maintenance.

- // Handle special cases for different field types const transformed: Record<string, { operator: string; values: { value: string; color: string | null }[], icon: React.ReactNode }> = {};
+ // Handle special cases for different field types

70-72: Simplify return statement in forEach callback.

The callback is returning an empty array [], but since this is inside a forEach loop, the return value is ignored. For better clarity, use a simple return statement instead.

  if (field === "startTime" || field === "endTime" || field === "since" || field === "time") {
-    return [];
+    return;
  }

110-110: Remove debug console.log statement.

Debug console.log statements should be removed before merging to production.

- console.log("field", field);

15-26: Consider a more flexible approach for status code handling.

The current implementation only handles specific status codes (200, 400, 500). For better flexibility and maintenance, consider a more general approach that handles ranges (2xx, 4xx, 5xx).

case "status":
  return {
-   value:
-     value === "200" ? "2xx" : value === "400" ? "4xx" : value === "500" ? "5xx" : value,
-   color:
-     value === "200"
-       ? "bg-success-9"
-       : value === "400"
-         ? "bg-warning-9"
-         : value === "500"
-           ? "bg-error-9"
-           : null,
+   value: getStatusCodeLabel(value),
+   color: getStatusCodeColor(value),
  };

// Add these helper functions outside the main function
function getStatusCodeLabel(statusCode: string): string {
  const code = parseInt(statusCode, 10);
  if (code >= 200 && code < 300) return "2xx";
  if (code >= 400 && code < 500) return "4xx";
  if (code >= 500 && code < 600) return "5xx";
  return statusCode;
}

function getStatusCodeColor(statusCode: string): string | null {
  const code = parseInt(statusCode, 10);
  if (code >= 200 && code < 300) return "bg-success-9";
  if (code >= 400 && code < 500) return "bg-warning-9";
  if (code >= 500 && code < 600) return "bg-error-9";
  return null;
}

112-112: Improve type safety in shouldTruncateRow function.

The function casts the input parameter to a specific type without validation. This could potentially cause issues if an invalid field is passed. Consider adding validation or using a more type-safe approach.

export function shouldTruncateRow(field: string): boolean {
-  return FieldsToTruncate.includes(field as (typeof FieldsToTruncate)[number]);
+  return FieldsToTruncate.includes(field as any);
}

Alternatively, for even better type safety:

export function shouldTruncateRow(field: string): boolean {
-  return FieldsToTruncate.includes(field as (typeof FieldsToTruncate)[number]);
+  // Check if the field is one of the values in FieldsToTruncate
+  return FieldsToTruncate.some(truncateField => truncateField === field);
}

94-97: Consider adding error handling for iconsPerField access.

The function directly accesses the iconsPerField object without checking if the field exists. While the fallback to ChartActivity2 handles undefined cases, explicit null/undefined checking would make the code more robust.

export function getFilterFieldIcon(field: string): JSX.Element {
-  const Icon = iconsPerField[field] || ChartActivity2;
+  const Icon = field && iconsPerField[field] ? iconsPerField[field] : ChartActivity2;
  return React.createElement(Icon, { size: "md-regular", className: "justify-center" });
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3d774b5 and fc70b4f.

📒 Files selected for processing (2)
  • apps/dashboard/app/(app)/audit/components/controls/components/logs-queries/index.tsx (1 hunks)
  • apps/dashboard/app/(app)/audit/components/controls/components/logs-queries/utils.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/dashboard/app/(app)/audit/components/controls/components/logs-queries/index.tsx
🧰 Additional context used
🧬 Code Definitions (1)
apps/dashboard/app/(app)/audit/components/controls/components/logs-queries/utils.ts (1)
apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/controls/components/logs-queries/utils.ts (4)
  • formatFilterValues (7-83)
  • getFilterFieldIcon (85-88)
  • FieldsToTruncate (90-97)
  • shouldTruncateRow (99-101)
⏰ Context from checks skipped due to timeout of 90000ms (17)
  • GitHub Check: Test Agent Local / test_agent_local
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Test Go API Local / Test (Shard 7/8)
  • GitHub Check: Test Go API Local / Test (Shard 8/8)
  • GitHub Check: Test Go API Local / Test (Shard 6/8)
  • GitHub Check: Test Go API Local / Test (Shard 5/8)
  • GitHub Check: Test Go API Local / Test (Shard 1/8)
  • GitHub Check: Test Go API Local / Test (Shard 3/8)
  • GitHub Check: Test Go API Local / Test (Shard 4/8)
  • GitHub Check: Test Packages / Test ./packages/hono
  • GitHub Check: Test Go API Local / Test (Shard 2/8)
  • GitHub Check: Test Packages / Test ./packages/rbac
  • GitHub Check: Test Packages / Test ./internal/id
  • GitHub Check: Test Packages / Test ./internal/encryption
  • GitHub Check: Test Packages / Test ./packages/api
  • GitHub Check: Build / Build
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
apps/dashboard/app/(app)/audit/components/controls/components/logs-queries/utils.ts (1)

1-114:

❓ Verification inconclusive

Consider extracting shared logic to avoid duplication with ratelimits version.

There is significant code duplication between this file and the similar utility in apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/controls/components/logs-queries/utils.ts. Consider extracting the common logic into a shared utility to improve maintainability.


🏁 Script executed:

#!/bin/bash
# Find similar utility files to identify potential duplication
echo "Searching for similar utility files..."
fd utils.ts --full-path "**/logs-queries/" --exec echo "{}" | sort

Length of output: 259


Extract Shared Logic to Eliminate Duplication

It appears that a similar implementation exists in both the audit and the ratelimits logs query utility files (i.e., in
apps/dashboard/app/(app)/audit/components/controls/components/logs-queries/utils.ts and
apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/controls/components/logs-queries/utils.ts). To improve maintainability, please refactor the duplicated logic—especially around the transformation functions like formatFilterValues—into a shared utility module. This change should help avoid inconsistencies and reduce the future maintenance overhead.

Before proceeding, please verify that the ratelimits version indeed contains similar logic and that the proposed consolidation will not affect any specialized behavior in either context.

@MichaelUnkey MichaelUnkey added this pull request to the merge queue Mar 31, 2025
auto-merge was automatically disabled March 31, 2025 14:28

Pull Request is not mergeable

Merged via the queue into main with commit 9d0f00d Mar 31, 2025
35 of 37 checks passed
@MichaelUnkey MichaelUnkey deleted the query-logs-component branch March 31, 2025 14:28
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.

None yet

3 participants