-
Notifications
You must be signed in to change notification settings - Fork 9
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
base: main
Are you sure you want to change the base?
Conversation
WalkthroughThe 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
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
Poem
Tip ⚡💬 Agentic Chat (Pro Plan, General Availability)
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
Documentation and Community
|
There was a problem hiding this 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
📒 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:
- Checking if the object matches the expected kind and version
- 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:
- Accepts generic objects to maintain type safety
- Iterates through the array of objects
- Validates each object using the
anySchemaError
function- 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:
- Checking if the object matches the expected kind and version
- 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 thebodySchema
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 genericgetSchemaParseError
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 inferredIdentifiable
type is a good practice for type safety across the codebase.
10-12
: Well-implemented type guard.The
isIdentifiable
type guard correctly uses Zod'ssafeParse
method to check if an object conforms to theIdentifiable
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:
- Checks if the object is identifiable
- Verifies if it matches the specified criteria
- Validates it against the provided schema
- 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 tsLength of output: 457
Function usage confirmed: No removal necessary.
The function
getIdentifiableSchemaParseError
inpackages/validators/src/resources/util.ts
is imported and used inpackages/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.
Summary by CodeRabbit
New Features
Refactor