Skip to content

fix: Vm v1 schema#286

Merged
adityachoudhari26 merged 2 commits intomainfrom
vm-schema
Jan 21, 2025
Merged

fix: Vm v1 schema#286
adityachoudhari26 merged 2 commits intomainfrom
vm-schema

Conversation

@adityachoudhari26
Copy link
Copy Markdown
Member

@adityachoudhari26 adityachoudhari26 commented Jan 21, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced VM resource validation with a new schema for disk objects and VM configurations.
    • Added detailed VM configuration tracking, including new properties for VM resources.
    • Improved metadata collection with additional fields related to VM status and configuration.
  • Refactor

    • Updated VM resource type definitions to align with new validation structures.
    • Standardized VM resource export mechanisms for better accessibility.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jan 21, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request introduces significant updates to the VM (Virtual Machine) resource validation and scanning process for Google Cloud. The changes encompass multiple files, enhancing type definitions and resource mapping for VM resources. Modifications include the creation of a new Zod validation schema for VM resources, adjustments to the export mechanism in the validators package, and refinements to the VM resource conversion function in the event worker.

Changes

File Change Summary
apps/event-worker/src/resource-scan/google/vm.ts Updated instanceToResource function to return VmV1 type with expanded metadata and config properties; added getFlattenedMetadata and getFlattenedTags helper functions.
packages/validators/src/resources/index.ts Added export for vm-v1.js module.
packages/validators/src/resources/vm-v1.ts Created new Zod validation schema for VM resources, defined diskV1 and vmV1 schemas, and exported VmV1 type.

Sequence Diagram

sequenceDiagram
    participant EventWorker as Event Worker
    participant Validators as Resource Validators
    participant GoogleCloud as Google Cloud API

    GoogleCloud->>EventWorker: Retrieve VM Instances
    EventWorker->>Validators: Validate VM Resource Structure
    Validators-->>EventWorker: Return Validated VM Resource
    EventWorker->>EventWorker: Transform and Enrich VM Metadata
Loading

Possibly related PRs

Suggested reviewers

  • jsbroks

Poem

🐰 Hopping through clouds of code so bright,
VM resources now take flight!
Schemas validated, types precise,
A rabbit's leap into infrastructure's slice!
Zod-powered magic, metadata's delight! 🚀


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 87eea10 and 2c7578a.

📒 Files selected for processing (2)
  • apps/event-worker/src/resource-scan/google/vm.ts (6 hunks)
  • packages/validators/src/resources/vm-v1.ts (1 hunks)
✨ 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.

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
Copy Markdown
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

🔭 Outside diff range comments (2)
apps/event-worker/src/resource-scan/google/vm.ts (2)

Line range hint 23-46: Add error handling for disk size conversion.

The disk size conversion on line 43 might fail silently if diskSizeGb is not a valid number. Consider adding validation:

-          size: Number(disk.diskSizeGb),
+          size: disk.diskSizeGb != null ? Number(disk.diskSizeGb) : 0,

Also, consider validating required fields before returning:

+  if (!instance.name && !instance.id) {
+    throw new Error("Instance must have either name or id");
+  }
   return {
     workspaceId,
     name: String(instance.name ?? instance.id ?? ""),

Line range hint 61-108: Consider metadata security and performance implications.

  1. Some metadata fields might contain sensitive information. Consider filtering out sensitive fields:
+const SENSITIVE_METADATA_PREFIXES = ['vm/instance-encryption-key', 'vm/metadata/ssh-keys'];
+
+const isSensitiveMetadata = (key: string) =>
+  SENSITIVE_METADATA_PREFIXES.some(prefix => key.startsWith(prefix));

   metadata: omitNullUndefined({
     // ... existing metadata
+  }, (value, key) => !isSensitiveMetadata(key)),
  1. Consider implementing metadata size limits to prevent performance issues with large instances:
const MAX_METADATA_SIZE = 1000; // Example limit
if (Object.keys(instance.metadata ?? {}).length > MAX_METADATA_SIZE) {
  log.warn(`Instance ${instance.name} has excessive metadata`, {
    size: Object.keys(instance.metadata ?? {}).length,
  });
}
🧹 Nitpick comments (2)
packages/validators/src/resources/vm-v1.ts (2)

3-8: Consider enhancing disk schema validation.

The disk schema could benefit from additional validations:

  • Add min/max constraints for size
  • Add enum/pattern for common disk types
  • Consider making some fields optional if they aren't always available
 const diskV1 = z.object({
   name: z.string(),
-  size: z.number(),
+  size: z.number().min(1).max(65536), // Example: Set reasonable disk size limits
-  type: z.string(),
+  type: z.enum(['pd-standard', 'pd-balanced', 'pd-ssd']), // Example: Common GCP disk types
   encrypted: z.boolean(),
 });

10-33: Consider stricter type safety for VM configuration.

The use of .passthrough() on the config object (line 31) allows any additional properties, which might hide typos or invalid fields. Consider:

  1. Explicitly defining all expected fields
  2. Using strict() instead of passthrough() if possible

Also, the metadata type on line 32 could be more specific:

-  metadata: z.record(z.string()).and(z.object({}).partial()),
+  metadata: z.record(z.string().or(z.number().or(z.boolean()))).and(
+    z.object({
+      [ReservedMetadataKey.Links]: z.string(),
+      [ReservedMetadataKey.ExternalId]: z.string(),
+      "vm/status": z.string(),
+      // ... other known metadata keys
+    }).partial()
+  ),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6abf7a8 and 87eea10.

📒 Files selected for processing (3)
  • apps/event-worker/src/resource-scan/google/vm.ts (4 hunks)
  • packages/validators/src/resources/index.ts (1 hunks)
  • packages/validators/src/resources/vm-v1.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
packages/validators/src/resources/index.ts (1)

Pattern **/*.{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.

apps/event-worker/src/resource-scan/google/vm.ts (1)

Pattern **/*.{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/vm-v1.ts (1)

Pattern **/*.{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.

🔇 Additional comments (3)
packages/validators/src/resources/index.ts (1)

4-4: LGTM! Export follows established pattern.

The new export for vm-v1 module follows the same pattern as other resource exports.

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

35-35: LGTM! Type export follows best practices.

Using z.infer ensures type safety and consistency with the schema definition.

apps/event-worker/src/resource-scan/google/vm.ts (1)

2-2: LGTM! Import aligns with schema changes.

The VmV1 type import correctly supports the updated resource conversion.

@adityachoudhari26 adityachoudhari26 merged commit 0673b0c into main Jan 21, 2025
@adityachoudhari26 adityachoudhari26 deleted the vm-schema branch January 21, 2025 06:43
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