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

refactor: filter types for logs page #2878

Merged
merged 5 commits into from
Feb 10, 2025

Conversation

ogzhanolguncu
Copy link
Contributor

@ogzhanolguncu ogzhanolguncu commented Feb 7, 2025

What does this PR do?

WARNING: THIS SHOULD BE MERGED AFTER #2877

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

  • Refactor
    • Updated log filtering schemas and type definitions to improve consistency and validation.
  • Chore
    • Standardized import paths for utilities and hooks.
    • Removed redundant constants and outdated type definitions.
  • Tests
    • Removed obsolete test files and streamlined remaining tests to align with the updated filtering logic.

Copy link

changeset-bot bot commented Feb 7, 2025

⚠️ No Changeset found

Latest commit: d0f4aa5

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 Feb 10, 2025 10:28am
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 10, 2025 10:28am
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 10, 2025 10:28am
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 10, 2025 10:28am

Copy link
Contributor

coderabbitai bot commented Feb 7, 2025

📝 Walkthrough

Walkthrough

This pull request refactors the logs filtering functionality across the dashboard. The changes update various import paths and type definitions by replacing older types and enums (e.g. filterOperatorEnum and FilterValue) with new versions (logsFilterOperatorEnum and LogsFilterValue). Additionally, several hook implementations and test files were modified or removed, constants were deleted, and new utility functions for schema generation were introduced. Overall, the modifications streamline filter schema validation and enhance type safety within the logs modules.

Changes

Files Change Summary
.../logs/components/charts/query-timeseries.schema.ts
.../logs/components/table/query-logs.schema.ts
Updated operator import from filterOperatorEnum to logsFilterOperatorEnum in schema definitions.
.../logs/components/control-cloud/index.tsx
.../logs/components/controls/** (display-popover, filters-popover, logs-live-switch, logs-refresh, logs-search)
Updated useKeyboardShortcut import paths (moved from relative to absolute) and changed filter property type from FilterValue to LogsFilterValue.
.../logs/components/controls/components/logs-filters/** (filter-checkbox, paths-filter, status-filter)
.../logs/components/controls/components/hooks/use-checkbox-state.ts
Replaced FilterValue with LogsFilterValue in type definitions, updated return types and variable declarations, and changed the import path for ResponseStatus.
.../logs/filters.schema.ts
.../logs/filters.type.ts
.../logs/types.ts
.../components/logs/validation/**
Refactored filter schemas: renamed enums and configurations to use the logsFilter* prefix, introduced new types (e.g. LogsFilterOperator, LogsFilterValue, QuerySearchParams), and added schema generation utilities in validation.
.../logs/hooks/use-bookmarked-filters.ts
.../logs/hooks/use-filters.ts
.../logs/hooks/use-keyboard-shortcut.tsx
Updated hook logic: switched filters to the QuerySearchParams structure and updated parsers and active filter types to use logs-specific types; removed the useKeyboardShortcut hook file.
.../logs/constants.ts Removed constants ONE_DAY_MS and DEFAULT_LOGS_FETCH_COUNT.
.../trpc/routers/logs/llm-search/**
.../trpc/routers/ratelimit/llm-search/utils.test.ts
Updated system prompt generation to utilize logsFilterFieldConfig and modified test assertions (removing some timestamp tests).
.../logs/**/*.test.ts Deleted obsolete test files (filters-schema.test.ts and use-filters.test.ts).
.../components/logs/validation/utils/structured-output-schema-generator.ts Added createFilterOutputSchema and validateFieldValue functions for structured filter output validation.
.../components/logs/validation/filter.types.ts Introduced new filter types, enums, and field configuration types for validation.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant LogsSearch
    participant LLMService
    participant FilterUtil

    User->>LogsSearch: Triggers search (via UI/shortcut)
    LogsSearch->>LLMService: queryLLMForStructuredOutput()
    LLMService-->>LogsSearch: Returns structured output
    LogsSearch->>FilterUtil: transformStructuredOutputToFilters()
    FilterUtil-->>LogsSearch: Validated filter schema
    LogsSearch-->>User: Updates filter display
Loading
sequenceDiagram
    participant Component
    participant useFiltersHook
    participant QueryParser

    Component->>useFiltersHook: updateFilters(newFilters)
    useFiltersHook->>QueryParser: parseAsFilterValArray(new filter values)
    QueryParser-->>useFiltersHook: Parsed LogsFilterValue[]
    useFiltersHook-->>Component: Active filters updated
Loading

Possibly related PRs

Suggested labels

Bug, 🕹️ oss.gg, :joystick: 150 points

Suggested reviewers

  • mcstepp
  • perkinsjr
  • chronark
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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.

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

🔭 Outside diff range comments (3)
apps/dashboard/app/(app)/logs/components/controls/components/logs-refresh.tsx (1)

21-34: Consider using async/await and proper error handling.

The setTimeout usage could be replaced with a more robust solution.

-  const handleSwitch = () => {
+  const handleSwitch = async () => {
     const isLiveBefore = Boolean(isLive);
     setIsLoading(true);
-    toggleLive(false);
-    logs.queryLogs.invalidate();
-    logs.queryTimeseries.invalidate();
-
-    setTimeout(() => {
+    try {
+      toggleLive(false);
+      await Promise.all([
+        logs.queryLogs.invalidate(),
+        logs.queryTimeseries.invalidate()
+      ]);
+      await new Promise(resolve => setTimeout(resolve, 1000));
       setIsLoading(false);
       if (isLiveBefore) {
         toggleLive(true);
       }
-    }, 1000);
+    } catch (error) {
+      setIsLoading(false);
+      console.error('Failed to refresh logs:', error);
+    }
   };
apps/dashboard/app/(app)/logs/hooks/use-bookmarked-filters.ts (2)

31-41: Remove @ts-expect-error by improving type safety.

The code uses multiple @ts-expect-error comments which should be addressed with proper typing.

-        if (["startTime", "endTime", "since"].includes(field)) {
-          //@ts-expect-error fix later
-          acc[field] = value;
-        } else {
-          if (!acc[field]) {
-            //@ts-expect-error fix later
-            acc[field] = [];
-          }
-          //@ts-expect-error fix later
-          acc[field].push({ value, operator });
-        }
+        type TimeField = "startTime" | "endTime" | "since";
+        if (isTimeField(field)) {
+          acc[field as TimeField] = value;
+        } else {
+          const arrayField = field as keyof Omit<QuerySearchParams, TimeField>;
+          if (!acc[arrayField]) {
+            acc[arrayField] = [];
+          }
+          (acc[arrayField] as FilterUrlValue[]).push({ value, operator });
+        }

+// Add this helper function
+function isTimeField(field: string): field is TimeField {
+  return ["startTime", "endTime", "since"].includes(field);
+}

84-100: Add type guard for status field check.

The type casting for the status field can be replaced with a type guard for better type safety.

+          const isStatusField = (field: string): field is "status" => field === "status";
           (value as FilterUrlValue[]).forEach((filter) => {
             reconstructedFilters.push({
               id: crypto.randomUUID(),
               field: field as LogsFilterField,
               operator: filter.operator,
               value: filter.value,
               metadata:
-                field === "status"
+                isStatusField(field)
                   ? {
                       colorClass: logsFilterFieldConfig.status.getColorClass?.(
                         filter.value as number,
                       ),
                     }
                   : undefined,
             });
           });
🧹 Nitpick comments (10)
apps/dashboard/components/logs/validation/utils/structured-output-schema-generator.ts (1)

41-60: Consider stricter validation for unrecognized field types.
If a field type fails the string/number checks, the function defaults to returning true. This might allow invalid field types or incompatible values to pass silently.

apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/hooks/use-filters.ts (1)

78-132: updateFilters function is logically correct but could benefit from more robust typing.
Grouping filters by field is straightforward, but some type constraints (e.g., preventing assignment of string values to numeric-based filters) might further improve reliability.

apps/dashboard/app/(app)/logs/hooks/use-filters.ts (2)

16-21: Initialization of parseAsFilterValArray.
Defining parseAsFilterValArray with string-based operators ("is", "contains", "startsWith", "endsWith") is good for text-based fields. If future numeric or date-based operators are added, consider a separate parser variant.


116-120: Grouping filter arrays by field.
Creating dedicated arrays for each filter field is clear. However, you might reduce duplication by dynamically grouping them (e.g., grouping by filter.field in a single pass). If adding many fields, a more generic approach could improve maintainability.

apps/dashboard/app/(app)/logs/components/controls/components/logs-filters/components/methods-filter.tsx (1)

3-7: Consider using a union type for better type safety.

While using string works, consider defining a union type of HTTP methods for better type safety and autocomplete support:

+type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
+
 type MethodOption = {
   id: number;
-  method: string;
+  method: HttpMethod;
   checked: boolean;
 };
apps/dashboard/components/logs/validation/utils/nuqs-parsers.ts (1)

29-57: Consider adding input validation for empty values.

The implementation handles null inputs and invalid operators well, but it might allow empty values after the operator.

 const [operator, val] = item.split(/:(.+)/);
-if (!operators.includes(operator as TOperator)) {
+if (!operators.includes(operator as TOperator) || !val) {
   throw new Error("Invalid operator");
 }
apps/dashboard/components/logs/validation/filter.types.ts (1)

36-49: Consider making metadata type more specific.

The metadata type could be more specific to prevent potential type errors.

 metadata?: {
   colorClass?: string;
-  icon?: ReactNode;
+  icon?: Exclude<ReactNode, null | undefined | boolean | number>;
 };
apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/filters.schema.ts (3)

35-35: Simplify color class logic using object literal.

The ternary operator can be replaced with a more maintainable object literal lookup.

-    getColorClass: (value) => (value === "blocked" ? "bg-warning-9" : "bg-success-9"),
+    getColorClass: (value) => ({
+      blocked: "bg-warning-9",
+      passed: "bg-success-9",
+    }[value]),

31-36: Add type validation for status values.

The validValues array should be typed to ensure it matches the possible values in the getColorClass function.

+  type StatusValue = "blocked" | "passed";
   status: {
     type: "string",
     operators: ["is"],
-    validValues: ["blocked", "passed"],
+    validValues: ["blocked", "passed"] as StatusValue[],
     getColorClass: (value) => (value === "blocked" ? "bg-warning-9" : "bg-success-9"),
   } as const,

68-81: Consider adding JSDoc comments for exported types.

The exported types lack documentation. Adding JSDoc comments would improve code maintainability.

+/** Represents the URL-safe version of a rate limit filter value */
 export type RatelimitFilterUrlValue = Pick<
   FilterValue<RatelimitFilterField, RatelimitFilterOperator>,
   "value" | "operator"
 >;

+/** Represents a complete rate limit filter value with all properties */
 export type RatelimitFilterValue = FilterValue<RatelimitFilterField, RatelimitFilterOperator>;

+/** Represents the structure of query parameters for rate limit searches */
 export type RatelimitQuerySearchParams = {
   startTime?: number | null;
   endTime?: number | null;
   since?: string | null;
   identifiers: RatelimitFilterUrlValue[] | null;
   requestIds: RatelimitFilterUrlValue[] | null;
   status: RatelimitFilterUrlValue[] | null;
 };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 67213d2 and f739f13.

📒 Files selected for processing (42)
  • apps/dashboard/app/(app)/logs/components/charts/query-timeseries.schema.ts (2 hunks)
  • apps/dashboard/app/(app)/logs/components/control-cloud/index.tsx (2 hunks)
  • apps/dashboard/app/(app)/logs/components/controls/components/logs-display/components/display-popover.tsx (1 hunks)
  • apps/dashboard/app/(app)/logs/components/controls/components/logs-filters/components/filter-checkbox.tsx (3 hunks)
  • apps/dashboard/app/(app)/logs/components/controls/components/logs-filters/components/filters-popover.tsx (1 hunks)
  • apps/dashboard/app/(app)/logs/components/controls/components/logs-filters/components/hooks/use-checkbox-state.ts (1 hunks)
  • apps/dashboard/app/(app)/logs/components/controls/components/logs-filters/components/methods-filter.tsx (1 hunks)
  • apps/dashboard/app/(app)/logs/components/controls/components/logs-filters/components/paths-filter.tsx (2 hunks)
  • apps/dashboard/app/(app)/logs/components/controls/components/logs-filters/components/status-filter.tsx (1 hunks)
  • apps/dashboard/app/(app)/logs/components/controls/components/logs-live-switch.tsx (1 hunks)
  • apps/dashboard/app/(app)/logs/components/controls/components/logs-refresh.tsx (1 hunks)
  • apps/dashboard/app/(app)/logs/components/controls/components/logs-search/index.tsx (1 hunks)
  • apps/dashboard/app/(app)/logs/components/table/query-logs.schema.ts (2 hunks)
  • apps/dashboard/app/(app)/logs/constants.ts (0 hunks)
  • apps/dashboard/app/(app)/logs/filters-schema.test.ts (0 hunks)
  • apps/dashboard/app/(app)/logs/filters.schema.ts (2 hunks)
  • apps/dashboard/app/(app)/logs/filters.type.ts (0 hunks)
  • apps/dashboard/app/(app)/logs/hooks/use-bookmarked-filters.ts (2 hunks)
  • apps/dashboard/app/(app)/logs/hooks/use-filters.test.ts (0 hunks)
  • apps/dashboard/app/(app)/logs/hooks/use-filters.ts (6 hunks)
  • apps/dashboard/app/(app)/logs/hooks/use-keyboard-shortcut.tsx (0 hunks)
  • apps/dashboard/app/(app)/logs/types.ts (1 hunks)
  • apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/charts/query-timeseries.schema.ts (2 hunks)
  • apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/control-cloud/index.tsx (2 hunks)
  • apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/controls/components/logs-filters/components/filter-checkbox.tsx (3 hunks)
  • apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/controls/components/logs-filters/components/hooks/use-checkbox-state.ts (1 hunks)
  • apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/controls/components/logs-filters/components/identifiers-filter.tsx (2 hunks)
  • apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/controls/components/logs-search/index.tsx (1 hunks)
  • apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/table/query-logs.schema.ts (2 hunks)
  • apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/filters.schema.ts (2 hunks)
  • apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/filters.type.ts (0 hunks)
  • apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/hooks/use-filters.test.ts (4 hunks)
  • apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/hooks/use-filters.ts (4 hunks)
  • apps/dashboard/components/logs/validation/filter.types.ts (1 hunks)
  • apps/dashboard/components/logs/validation/utils/nuqs-parsers.ts (1 hunks)
  • apps/dashboard/components/logs/validation/utils/structured-output-schema-generator.ts (1 hunks)
  • apps/dashboard/components/logs/validation/utils/transform-structured-output-filter-format.ts (1 hunks)
  • apps/dashboard/components/logs/validation/utils/type-guards.ts (1 hunks)
  • apps/dashboard/lib/trpc/routers/logs/llm-search/utils.test.ts (0 hunks)
  • apps/dashboard/lib/trpc/routers/logs/llm-search/utils.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/ratelimit/llm-search/utils.test.ts (1 hunks)
  • apps/dashboard/lib/trpc/routers/ratelimit/llm-search/utils.ts (2 hunks)
💤 Files with no reviewable changes (7)
  • apps/dashboard/app/(app)/logs/constants.ts
  • apps/dashboard/lib/trpc/routers/logs/llm-search/utils.test.ts
  • apps/dashboard/app/(app)/logs/hooks/use-filters.test.ts
  • apps/dashboard/app/(app)/logs/filters-schema.test.ts
  • apps/dashboard/app/(app)/logs/hooks/use-keyboard-shortcut.tsx
  • apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/filters.type.ts
  • apps/dashboard/app/(app)/logs/filters.type.ts
✅ Files skipped from review due to trivial changes (5)
  • apps/dashboard/app/(app)/logs/types.ts
  • apps/dashboard/app/(app)/logs/components/controls/components/logs-live-switch.tsx
  • apps/dashboard/app/(app)/logs/components/controls/components/logs-filters/components/filters-popover.tsx
  • apps/dashboard/app/(app)/logs/components/controls/components/logs-filters/components/status-filter.tsx
  • apps/dashboard/app/(app)/logs/components/controls/components/logs-display/components/display-popover.tsx
🧰 Additional context used
📓 Learnings (1)
apps/dashboard/app/(app)/logs/hooks/use-bookmarked-filters.ts (1)
Learnt from: ogzhanolguncu
PR: unkeyed/unkey#2825
File: apps/dashboard/app/(app)/logs-v2/hooks/use-bookmarked-filters.ts:0-0
Timestamp: 2025-01-30T20:51:44.359Z
Learning: The user (ogzhanolguncu) prefers to handle refactoring suggestions in separate PRs to maintain focus in the current PR.
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Test Packages / Test ./packages/cache
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Test Packages / Test ./internal/encryption
  • GitHub Check: Test Agent Local / test_agent_local
  • GitHub Check: Test API / API Test Local
  • GitHub Check: Build / Build
  • GitHub Check: autofix
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (36)
apps/dashboard/components/logs/validation/utils/structured-output-schema-generator.ts (2)

5-9: Great use of generic parameters for flexibility.
This approach ensures the schema generation is adaptable for various field and operator enum configurations.


10-39: Ensure the field configuration is never undefined within .refine().
Currently, the code retrieves the field configuration but does not safeguard against a missing or undefined config. If the enum or configuration object ever becomes misaligned, an undefined config could cause undefined behavior.

Would you like to add an explicit check to confirm that config is defined before checking config.operators?

apps/dashboard/app/(app)/logs/filters.schema.ts (4)

11-56: Field configurations look structurally consistent.
This organized approach simplifies future expansions and ensures clarity.


58-62: StatusConfig extends NumberConfig correctly.
The validate function ensures that only valid status codes are allowed, which is good for data integrity.


78-82: filterOutputSchema creation aligns well with the new Enums.
The composition with createFilterOutputSchema is a clean pattern for consistent runtime validation.


99-114: Check QuerySearchParams for optional fields.
It's beneficial that numeric and string fields are nullable, but ensure the rest of your UI and logic handle these null cases gracefully.

apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/hooks/use-filters.ts (2)

16-16: parseAsFilterValArray usage is concise and clear.
Defining the allowed operators in one place helps maintain consistency.


56-58: Confirm type consistency for status color mapping.
If the status field is a number, ensure getColorClass can handle numeric input. Casting as string may lead to unexpected results or user confusion if the function expects numeric logic.

apps/dashboard/app/(app)/logs/hooks/use-filters.ts (7)

1-4: Imports look consistent.
The introduction of parseAsFilterValueArray and parseAsRelativeTime from "@/components/logs/validation/utils/nuqs-parsers" appears correct and consistent with the usage further down in the file.


7-14: Types imported for logs filtering.
Bringing in LogsFilterField, LogsFilterOperator, LogsFilterValue, and so on from "../filters.schema" aligns well with the specialized logs filtering. Just ensure that references to these types and configs remain consistent throughout.


23-27: Unified filter arrays in queryParamsPayload.
Assigning parseAsFilterValArray to multiple fields like requestId, host, methods, paths, and status is concise. If one of these fields should be numeric-only (e.g., status codes), double-check that string-based parse logic is intended. Otherwise, this is a clean approach.


37-37: Initialization of activeFilters array.
Declaring const activeFilters: LogsFilterValue[] = [] is straightforward and ensures type safety for the subsequent push operations.


44-44: Handling numeric status value.
• Line 44 merely pushes the raw value into the filter.
• Line 46 calls getColorClass with status.value cast as a number. Double-check that this cast is always valid (i.e., the status field is guaranteed to be numeric).

Also applies to: 46-46


92-92: Force-casting field to LogsFilterField.
Casting field as LogsFilterField can mask real type mismatches. Confirm that only valid keys appear in the "startTime", "endTime", and "since" iteration.


103-103: updateFilters signature.
updateFilters accepting an array of LogsFilterValue clarifies usage and ensures all filter updates remain typed. This helps avoid passing in unintended filter structures.

apps/dashboard/components/logs/validation/utils/type-guards.ts (1)

1-9: Well-structured type guards.
Both isNumberConfig and isStringConfig correctly refine the config object’s type field. This is a standard TypeScript approach to narrowing. No issues found.

apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/charts/query-timeseries.schema.ts (1)

2-2: Usage of ratelimitFilterOperatorEnum.
Switching to ratelimitFilterOperatorEnum for operator fields is consistent with the specialized rate limit filtering. Please verify that all operator references in related code have been updated to avoid mismatches or type errors.
[approve]

Also applies to: 13-13

apps/dashboard/app/(app)/logs/components/charts/query-timeseries.schema.ts (1)

2-2: Verify enum values compatibility.

The change from filterOperatorEnum to logsFilterOperatorEnum looks good, but please ensure that all possible values in logsFilterOperatorEnum are compatible with the existing filter operations.

Also applies to: 12-12

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Compare the values of old and new filter operator enums

# Search for enum definitions
echo "Searching for old and new enum definitions..."
rg -A 10 "filterOperatorEnum|logsFilterOperatorEnum"

Length of output: 7577


Final Verification: Enum Values Compatibility Confirmed

  • The new enum "logsFilterOperatorEnum" is defined in "apps/dashboard/app/(app)/logs/filters.schema.ts" with the values ["is", "contains", "startsWith", "endsWith"].
  • The old enum "filterOperatorEnum" in "apps/dashboard/components/logs/validation/filter.types.ts" contains the identical set of values.
  • Therefore, all values in "logsFilterOperatorEnum" are fully compatible with the existing filter operations.
apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/table/query-logs.schema.ts (1)

2-2: Verify rate limit-specific operators.

The change to use ratelimitFilterOperatorEnum suggests that rate limit filters might have different operators than log filters. Please ensure that this separation is intentional and document any differences between the two sets of operators.

Also applies to: 14-14

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Compare logs and rate limit filter operators

# Search for both enum definitions
echo "Comparing logs and rate limit filter operators..."
rg -A 10 "logsFilterOperatorEnum|ratelimitFilterOperatorEnum"

Length of output: 14285


Verification: Rate Limit Operator Enums are Intentionally Separated

  • The logs filter operator enum (defined in apps/dashboard/app/(app)/logs/filters.schema.ts) includes four operators: "is", "contains", "startsWith", and "endsWith".
  • In contrast, the ratelimit filter operator enum (defined in apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/filters.schema.ts) restricts the valid operators to just "is" and "contains".

This discrepancy indicates an intentional design decision to limit rate limit filters to a subset of the operators used for log filters. If this separation is by design, it is recommended to document the rationale for the narrower set of operators in the rate limit filters for clarity.

apps/dashboard/app/(app)/logs/components/table/query-logs.schema.ts (1)

2-2: LGTM! Schema changes are consistent.

The change to use logsFilterOperatorEnum maintains consistency with other log-related schemas and aligns with the refactoring objectives.

Also applies to: 13-13

apps/dashboard/components/logs/validation/utils/nuqs-parsers.ts (1)

5-25: LGTM! Well-implemented parser with proper error handling.

The implementation correctly handles null inputs and validates relative time strings.

apps/dashboard/components/logs/validation/filter.types.ts (1)

4-7: Consider adding validation for operator values.

While using zod for enum validation is good, consider adding runtime validation to ensure operator values match the enum.

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Check if all operator usages match the enum values
rg -A 2 "operator.*=.*['\"](?:is|contains|startsWith|endsWith)['\"]"

Length of output: 962


Runtime Validation for Operator Values

The zod enum in filter.types.ts already performs runtime validation when used in a zod parsing context. Our grep search confirms that operator comparisons (e.g., checking for "is") consistently use the valid enum string values. If inputs are piped through zod—for example, using filterOperatorEnum.parse(input)—then operator values are validated at runtime. In cases where input isn’t processed through zod, adding an explicit runtime check might provide an extra layer of safety, but based on the usage we found, current implementations assume already validated input.

apps/dashboard/app/(app)/logs/components/controls/components/logs-filters/components/hooks/use-checkbox-state.ts (1)

1-1: LGTM! Type update aligns with the new filter schema.

The change from FilterValue to LogsFilterValue maintains type safety while aligning with the new filter schema.

Also applies to: 6-6

apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/controls/components/logs-filters/components/hooks/use-checkbox-state.ts (1)

1-1: LGTM! Type update aligns with the new filter schema.

The change from FilterValue to RatelimitFilterValue maintains type safety while aligning with the new filter schema.

Also applies to: 6-6

apps/dashboard/app/(app)/logs/components/controls/components/logs-filters/components/paths-filter.tsx (1)

1-1: LGTM! Type safety improvements.

The changes correctly update the filter type from generic FilterValue to the more specific LogsFilterValue, improving type safety while maintaining the existing functionality.

Also applies to: 40-40

apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/controls/components/logs-filters/components/filter-checkbox.tsx (1)

5-5: LGTM! Consistent type refactoring.

The changes correctly update the filter types to use the more specific RatelimitFilterValue, maintaining consistency with the broader refactoring effort.

Also applies to: 24-24, 50-50

apps/dashboard/app/(app)/logs/components/controls/components/logs-filters/components/filter-checkbox.tsx (1)

1-1: LGTM! Parallel type refactoring.

The changes correctly update the filter types to use the more specific LogsFilterValue, maintaining consistency with the parallel changes in the rate limits component.

Also applies to: 24-24, 50-50

apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/controls/components/logs-filters/components/identifiers-filter.tsx (1)

6-6: LGTM! Import path and type updated correctly.

The change from FilterValue to RatelimitFilterValue aligns with the broader refactoring to separate rate limit and logs filter types.

apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/controls/components/logs-search/index.tsx (1)

1-4: LGTM! Import paths updated correctly.

The changes align with the broader refactoring effort to centralize utility functions and hooks.

apps/dashboard/app/(app)/logs/components/controls/components/logs-search/index.tsx (1)

1-4: LGTM! Import paths updated correctly.

The changes align with the broader refactoring effort to centralize utility functions and hooks.

apps/dashboard/lib/trpc/routers/ratelimit/llm-search/utils.ts (2)

1-25: LGTM! Import updated and documentation added.

The change from filterFieldConfig to ratelimitFilterFieldConfig aligns with the broader refactoring. The added JSDoc documentation with examples significantly improves code maintainability.


37-37: Verify the OpenAI model name.

The model name "gpt-4o-mini" seems unusual. OpenAI's standard model names don't include a model called "gpt-4o-mini".

✅ Verification successful

🌐 Web query:

What are the available OpenAI GPT-4 model names?

💡 Result:

Available OpenAI GPT-4 model names include several variants optimized for different use cases and deployment scenarios. Here's a structured breakdown:

### Core Models
1. **GPT-4 Turbo**  
   - General Availability (GA) version: `gpt-4` with `turbo-2024-04-09`  
   - Replaced older preview models:  
     - `gpt-4` (`1106-Preview`, `0125-Preview`, `vision-preview`) [1][6]

2. **GPT-4o ("omni")**  
   - Multimodal model handling text/images/audio:  
     - Versions: `2024-11-20`, `2024-08-06`, `2024-05-13` [1][2][10]  
   - Requires deployment in **standard** or **global-standard** Azure regions [1]

3. **GPT-4o mini**  
   - Smaller, cost-efficient variant:  
     - Version: `2024-07-18` (`gpt-4o-mini`) [1][4]  

---

### Specialized Models
**Realtime Beta (Preview)**  
   - Real-time audio/text interaction via WebRTC/WebSocket:  
     - `gpt-4o-realtime-preview` (versions: `2024-12-17`, `2024-10–01`)  
     - `gpt–4o–mini–realtime–preview` (`2024–12–17`) [4]

**Vision Capabilities**  
   - Integrated into GPT‑4 Turbo as `gpt‑4‑turbo` via Chat Completions API [6]  

---

### Deprecated/Historical Models
   - Early versions: `gpt‑40314`, `gpt‑41106-Preview` (phased out) [7][9]  

---

### Access Requirements
Models are accessible via:
1. **OpenAI API**: After $5+ payment (usage tier 1) [8]  
2. **Azure OpenAI Service**: Requires resource deployment in supported regions [1][10]  

For developers, programmatic deployments use exact model+version identifiers like `gpt‑40` or `gpt‑40‑mini`[1][4]. Always verify regional availability and API documentation for compatibility updates.

Citations:

- 1: https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models?tabs=python-secure%2Cglobal-standard%2Cstandard-chat-completions&wt.mc_id=studentamb_264449
- 2: https://en.wikipedia.org/wiki/GPT-4
- 3: https://gptforwork.com/guides/openai-gpt3-models
- 4: https://platform.openai.com/docs/models
- 5: https://openai.com/product/gpt-4/
- 6: https://help.openai.com/en/articles/8555496-gpt-4-vision-api
- 7: https://community.openai.com/t/cant-find-and-use-gpt-4-model-i-have-the-gpt-4-invitation/137192
- 8: https://help.openai.com/en/articles/7102672-how-can-i-access-gpt-4-gpt-4-turbo-gpt-4o-and-gpt-4o-mini
- 9: https://community.openai.com/t/what-do-the-numbers-on-gpt-models-actually-mean/623711
- 10: https://learn.microsoft.com/en-us/azure/ai-services/openai/whats-new

Verification Result: The "gpt-4o-mini" model name is valid.

The web query confirms that "gpt-4o-mini" is an available variant of the GPT-4 series, specifically a smaller and cost-efficient model introduced on 2024-07-18. Based on this information, the code snippet using "gpt-4o-mini" is correct and does not require any changes.

  • File: apps/dashboard/lib/trpc/routers/ratelimit/llm-search/utils.ts, line 37 uses a valid OpenAI model name.
apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/control-cloud/index.tsx (1)

3-3: LGTM! The type changes improve separation of concerns.

The changes correctly separate rate limit filter types from general filter types, making the codebase more maintainable and type-safe. The absolute import path for useKeyboardShortcut is also a good practice.

Also applies to: 9-9, 47-47

apps/dashboard/app/(app)/logs/components/control-cloud/index.tsx (1)

3-3: LGTM! The type changes maintain consistency with rate limits.

The changes mirror those in the rate limits component, ensuring consistent type separation and import paths across the codebase.

Also applies to: 9-9, 60-60

apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/hooks/use-filters.test.ts (1)

1-4: LGTM! The validation utilities are now centralized.

The changes correctly move parser functions to a centralized location, improving code organization. The test cases maintain their functionality while using the new utilities.

Also applies to: 10-10

apps/dashboard/lib/trpc/routers/logs/llm-search/utils.ts (1)

2-2: LGTM! The LLM search now uses logs-specific filter configuration.

The changes correctly align the LLM search functionality with the new filter type separation, maintaining the same functionality while using the logs-specific configuration.

Also applies to: 77-77

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 (1)
apps/dashboard/lib/trpc/routers/logs/llm-search.ts (1)

90-159: Consider restricting the status code range.

The function is well-implemented, but the status code range (100-599) might be too permissive. Consider restricting it to commonly used HTTP status codes to prevent invalid inputs.

-        constraints = " and must be between 100-599";
+        constraints = " and must be a valid HTTP status code (e.g., 200, 201, 400, 401, 403, 404, 500, 503)";
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f739f13 and 7402ffc.

📒 Files selected for processing (3)
  • apps/dashboard/app/(app)/logs/components/controls/components/logs-filters/components/paths-filter.tsx (2 hunks)
  • apps/dashboard/app/(app)/logs/components/controls/components/logs-search/index.tsx (1 hunks)
  • apps/dashboard/lib/trpc/routers/logs/llm-search.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/dashboard/app/(app)/logs/components/controls/components/logs-search/index.tsx
  • apps/dashboard/app/(app)/logs/components/controls/components/logs-filters/components/paths-filter.tsx
🔇 Additional comments (3)
apps/dashboard/lib/trpc/routers/logs/llm-search.ts (3)

2-2: LGTM! Import statement correctly updated.

The import statement has been properly updated to use the new logsFilterFieldConfig as part of the filter types refactoring.


16-80: Well-implemented error handling and type safety.

The function implementation is robust with:

  • Comprehensive error handling for different scenarios
  • Clear user-friendly error messages
  • Proper rate limit handling
  • Type safety through schema validation

23-23: Fix the OpenAI model name.

The model name "gpt-4o-2024-08-06" appears to be incorrect. OpenAI model names typically follow the format "gpt-4-YYYY-MM-DD".

-      model: "gpt-4o-2024-08-06",
+      model: "gpt-4-0613",
✅ Verification successful

🌐 Web query:

What are the available OpenAI GPT-4 models that support function calling or JSON mode?

💡 Result:

OpenAI's GPT-4 models with function calling and JSON mode support include:

Function Calling Support

These models enable API integration through structured JSON outputs:

  • gpt-4-0613
    Original model supporting function calls via functions parameter[1][7]
  • gpt-4 (1106-Preview/0125-Preview)
    Enhanced parallel function calling via tools parameter[10]
  • gpt-4o & gpt-4o-mini
    Latest multimodal models with native tool/tool_choice implementation[9][10]

JSON Mode Support

Models constrained to return valid JSON:

Model Key Features
gpt-4 (1106-Preview) Initial JSON schema enforcement[5][6]
gpt-4o Combines JSON mode with vision/audio[9][5]
gpt-4o-mini Compact version with JSON constraints[9][5]

Both features require API version 2023-12-01-preview or newer[5][10]. For production use cases requiring strict schema validation, newer gpt-4o variants are recommended over legacy 0613/Preview models due to improved reliability[3][9].

Citations:


Fix the OpenAI model name.

The model name "gpt-4o-2024-08-06" does not match any standardized naming pattern. OpenAI’s documentation and community resources indicate that stable function calling is supported with models like "gpt-4-0613", while the "gpt-4o" (without a date suffix) is used to reference the latest multimodal variants. To avoid API errors and ensure compatibility, it's recommended to replace the incorrect model name with a valid one—such as "gpt-4-0613" if function calling is the primary requirement.

  • File: apps/dashboard/lib/trpc/routers/logs/llm-search.ts
    • Line 23: change "gpt-4o-2024-08-06" to "gpt-4-0613" (or "gpt-4o" if multimodal support is intended)

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