Skip to content

enforce resource schema on WS upsert API #473

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

j7m4
Copy link
Contributor

@j7m4 j7m4 commented Apr 11, 2025

  • validation check for each concrete resource type, wip
  • correctly filters non-matching schemas for matching version/kind resources
  • format, lint fixes

Summary by CodeRabbit

  • New Features

    • Enhanced resource validations now provide clear error feedback at API endpoints, ensuring only valid data is processed.
    • Standardized and consistent validation routines have been introduced across cloud services, Kubernetes clusters, and virtual machine operations.
  • Refactor

    • Streamlined internal validation utilities to improve maintainability and reliability in resource processing.

Copy link
Contributor

coderabbitai bot commented Apr 11, 2025

Walkthrough

The changes update resource handling and schema validation across multiple modules. In the webservice, the PATCH route now uses detailed schema definitions and validation utilities to partition incoming resources into valid and error cases. In the validators package, hardcoded literals have been replaced with constants and new schema parsing error functions have been introduced for cloud, Kubernetes, and VM resources. Additionally, new utility modules provide identifiable schemas and generic validation functions, with updated exports to expose the additional functionality.

Changes

File(s) Change Summary
apps/webservice/.../route.ts Introduces new type BodySchema and constant bodyResource; updates the body schema for PATCH requests; integrates partitionForSchemaErrors to separate valid resources from those with validation errors.
packages/validators/src/resources/{cloud-v1.ts, kubernetes-v1.ts, vm-v1.ts} Replaces hardcoded kind and version with constants; adds new functions (getCloudVpcV1SchemaParserError, getKubernetesClusterAPIV1SchemaParseError, getVmV1SchemaParseError) that utilize generic schema parse utilities to return ZodError details.
packages/validators/src/resources/{util.ts, validate.ts} Adds new utility functions: defines an identifiable schema and type guard isIdentifiable; introduces getIdentifiableSchemaParseError and getSchemaParseError in util.ts, and creates anySchemaError and partitionForSchemaErrors functions in validate.ts for multi-schema validation.
packages/validators/src/resources/index.ts Adds a new export statement to expose all entities from validate.js.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant R as Route Handler (/set/route.ts)
    participant V as Validation Utility (partitionForSchemaErrors)
    participant P as Resource Processor (handleResourceProviderScan)

    C->>R: PATCH request with resource data
    R->>V: Validate and partition resources
    alt Valid resources found
      R->>P: Process valid resources
      P-->>R: Return processed data
      R-->>C: 200 OK with results
    else Validation errors present
      R-->>C: 400 Error with error details
    end
Loading

Poem

I’m a rabbit hopping through code so neat,
Chewing on bugs with a joyful beat.
Schemas refined and constants in sight,
Validations clear as day and night.
With functions and checks, my heart does race—
A code-hop celebration in every place!
🐇✨

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @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.

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 (1)
apps/webservice/src/app/api/v1/resource-providers/[providerId]/set/route.ts (1)

107-107: Consider adding more context to empty response.

When there are no resources (neither valid nor with errors), the function returns an empty array. While technically correct, consider adding a more descriptive message to clarify that no resources were processed.

-      return NextResponse.json([]);
+      return NextResponse.json({ resources: [], message: "No resources were provided" });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c0586e7 and b102af7.

📒 Files selected for processing (7)
  • apps/webservice/src/app/api/v1/resource-providers/[providerId]/set/route.ts (3 hunks)
  • packages/validators/src/resources/cloud-v1.ts (3 hunks)
  • packages/validators/src/resources/index.ts (1 hunks)
  • packages/validators/src/resources/kubernetes-v1.ts (3 hunks)
  • packages/validators/src/resources/util.ts (1 hunks)
  • packages/validators/src/resources/validate.ts (1 hunks)
  • packages/validators/src/resources/vm-v1.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{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...

**/*.{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/validators/src/resources/index.ts
  • packages/validators/src/resources/cloud-v1.ts
  • packages/validators/src/resources/validate.ts
  • packages/validators/src/resources/kubernetes-v1.ts
  • packages/validators/src/resources/vm-v1.ts
  • packages/validators/src/resources/util.ts
  • apps/webservice/src/app/api/v1/resource-providers/[providerId]/set/route.ts
🧬 Code Graph Analysis (3)
packages/validators/src/resources/validate.ts (4)
packages/validators/src/resources/util.ts (1)
  • getIdentifiableSchemaParseError (14-18)
packages/validators/src/resources/cloud-v1.ts (1)
  • getCloudVpcV1SchemaParserError (54-62)
packages/validators/src/resources/kubernetes-v1.ts (1)
  • getKubernetesClusterAPIV1SchemaParseError (103-111)
packages/validators/src/resources/vm-v1.ts (1)
  • getVmV1SchemaParseError (45-51)
packages/validators/src/resources/kubernetes-v1.ts (1)
packages/validators/src/resources/util.ts (3)
  • getSchemaParseError (27-38)
  • identifiable (3-6)
  • Identifiable (8-8)
packages/validators/src/resources/vm-v1.ts (1)
packages/validators/src/resources/util.ts (3)
  • getSchemaParseError (27-38)
  • identifiable (3-6)
  • Identifiable (8-8)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: Typecheck
  • GitHub Check: Lint
🔇 Additional comments (29)
packages/validators/src/resources/index.ts (1)

6-6: Looks good - appropriate module export added.

The new export statement correctly makes the validation functionality from validate.js available to consumers of this module.

packages/validators/src/resources/cloud-v1.ts (4)

1-5: Appropriate imports for schema validation functionality.

These imports properly set up the necessary types and utilities for implementing the schema validation.


26-28: Good use of constants for schema identification.

Extracting these values as constants improves maintainability by centralizing the definition of schema identifiers.


30-31: Schema appropriately updated to use constants.

Using the constants instead of string literals maintains consistency and makes the code more maintainable.


54-62: Well-implemented schema validation function.

This function correctly implements schema validation for Cloud VPC resources by:

  1. Checking if the object matches the expected kind and version
  2. Only validating against the schema if it's the right resource type

This aligns with the PR objective of enforcing resource schema validation.

packages/validators/src/resources/validate.ts (4)

1-7: Appropriate imports for schema validation utilities.

The imports correctly bring in all the necessary schema validation functions from different resource types.


8-15: Well-implemented composite validation function.

The anySchemaError function elegantly uses the nullish coalescing operator to try multiple schema validators in sequence, returning the first error found or undefined if all validations pass. This approach is concise and efficient.


17-20: Clear interface definition for validation results.

The interface clearly defines the structure for storing both valid objects and validation errors.


22-38: Well-implemented partition function for validation.

The partitionForSchemaErrors function correctly:

  1. Accepts generic objects to maintain type safety
  2. Iterates through the array of objects
  3. Validates each object using the anySchemaError function
  4. Categorizes objects into valid or errors based on validation results

This function is key to implementing the PR objective of filtering non-matching schemas and enforcing schema validation.

packages/validators/src/resources/kubernetes-v1.ts (4)

1-6: Appropriate imports for schema validation.

These imports correctly set up the necessary types and utilities for implementing schema validation.


61-63: Good use of constants for schema identification.

Extracting these values as constants improves maintainability and consistency across the codebase.


65-66: Schema appropriately updated to use constants.

Using the constants instead of string literals maintains consistency and reduces the risk of typos.


103-111: Well-implemented schema validation function.

This function correctly implements schema validation for Kubernetes Cluster API resources by:

  1. Checking if the object matches the expected kind and version
  2. Only validating against the schema if it's the right resource type

The implementation is consistent with the other validation functions in the PR, which is good for maintaining code consistency.

apps/webservice/src/app/api/v1/resource-providers/[providerId]/set/route.ts (8)

15-15: Good addition of the schema validation utility.

The import of partitionForSchemaErrors from the validators package is a good approach for separating validation logic from the route handler.


21-39: Well-structured schema definition with robust validation.

The creation of a separate bodyResource constant improves code organization by clearly defining the expected resource structure. The schema properly extends the base resource schema while adding support for metadata and variables with appropriate validation rules.

I particularly like the refinement on line 34-38 that prevents duplicate variable keys, which is an important validation to ensure data integrity.


42-43: Clean schema composition.

Utilizing the previously defined bodyResource in the bodySchema improves maintainability and readability.


45-45: Good use of type inference.

Using Zod's z.infer to derive the TypeScript type from the schema ensures type safety and consistency between runtime validation and compile-time type checking.


57-81: LGTM: Proper parameter extraction and provider validation.

The handler correctly extracts parameters, validates the provider existence, and prepares resources for insertion with the necessary workspaceId and providerId.


82-84: Good separation of valid resources and validation errors.

Using partitionForSchemaErrors to separate resources into valid ones and those with schema errors is a clean approach that aligns with the PR objective of enforcing resource schemas.


85-98: Clean handling of valid resources.

The code properly processes valid resources through handleResourceProviderScan and handles null values in variables correctly with the null coalescing operator.


100-105: Good error response with detailed feedback.

Returning a 400 status code with detailed validation issues provides clear feedback to API consumers about what went wrong.

packages/validators/src/resources/vm-v1.ts (4)

1-5: Good import organization.

Separating type imports and function imports improves readability. The explicit import of ZodError type ensures proper type checking.


14-15: Good extraction of constants.

Extracting version and kind as constants improves maintainability by centralizing these values, making it easier to update them in one place if needed.


20-21: Proper use of constants in schema definition.

Using the extracted constants in the schema definition reduces duplication and ensures consistency.


45-51: Well-implemented schema validation function.

The implementation of getVmV1SchemaParseError follows a clean pattern of reusing the generic getSchemaParseError function with a specific matcher for VM resources. This approach ensures consistent validation across different resource types.

packages/validators/src/resources/util.ts (4)

3-8: Good schema and type definition.

The identifiable schema correctly defines the common structure for all resource types, and exporting the inferred Identifiable type is a good practice for type safety across the codebase.


10-12: Well-implemented type guard.

The isIdentifiable type guard correctly uses Zod's safeParse method to check if an object conforms to the Identifiable schema, providing proper TypeScript type narrowing.


20-38: Well-documented and implemented generic validation function.

The getSchemaParseError function is thoroughly documented with JSDoc comments, making its purpose and parameters clear. The implementation correctly:

  1. Checks if the object is identifiable
  2. Verifies if it matches the specified criteria
  3. Validates it against the provided schema
  4. Returns appropriate errors or undefined

This approach provides a clean and reusable way to handle schema validation for different resource types.


14-18:

✅ Verification successful

Verify if this function is used elsewhere.

While the getIdentifiableSchemaParseError function is implemented correctly, you might want to verify if it's actually used elsewhere in the codebase. If not, consider removing it to keep the code lean.


🏁 Script executed:

#!/bin/bash
# Search for uses of getIdentifiableSchemaParseError in the codebase
echo "Searching for uses of getIdentifiableSchemaParseError..."
rg "getIdentifiableSchemaParseError" --type ts

Length of output: 457


Function usage confirmed: No removal necessary.

The function getIdentifiableSchemaParseError in packages/validators/src/resources/util.ts is imported and used in packages/validators/src/resources/validate.ts (as seen in the shell script output). This confirms that the function is indeed utilized in the codebase. No further action is required on this function.

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