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

fix: backend error messages and dbt cloud adapterType #1519

Merged
merged 4 commits into from
Dec 11, 2024
Merged

Conversation

AdiGajbhiye
Copy link
Collaborator

@AdiGajbhiye AdiGajbhiye commented Dec 9, 2024

Overview

  • handled backend api error messages
  • fix dbt cloud adapterType

Problem

Describe the problem you are solving. Mention the ticket/issue if applicable.

Solution

Describe the implemented solution. Add external references if needed.

Screenshot/Demo

A picture is worth a thousand words. Please highlight the changes if applicable.

How to test

  • Steps to be followed to verify the solution or code changes
  • Mention if there is any settings configuration added/changed/deleted

Checklist

  • I have run this code and it appears to resolve the stated issue
  • README.md updated and added information about my change

Important

Improves error handling in AltimateRequest and fixes adapter type initialization in DBTCloudProjectIntegration.

  • Error Handling:
    • In AltimateRequest class in altimate.ts, fetch method now attempts to parse textResponse as JSON to extract detail field for APIError message.
    • If JSON parsing fails, falls back to using textResponse directly in APIError message.
  • DBT Cloud Integration:
    • In DBTCloudProjectIntegration class in dbtCloudIntegration.ts, changed adapter type check from !this.adapterType to this.adapterType === "unknown" to ensure correct initialization of adapter type.

This description was created by Ellipsis for 7e4e4b5. It will automatically update as commits are pushed.


Summary by CodeRabbit

  • Bug Fixes
    • Improved error messages for API response failures to provide clearer context.
    • Enhanced error handling for specific HTTP status codes (401, 403, 404, 402, 429) to improve user feedback.
    • Updated error handling in the DBT Cloud integration to provide clearer messages during initialization failures.
    • Refined logic for checking adapter type in the DBT Cloud integration for better accuracy.

Copy link
Contributor

coderabbitai bot commented Dec 9, 2024

Walkthrough

The changes in this pull request focus on enhancing the error handling logic within the fetch method of the AltimateRequest class and updating the DBTCloudProjectIntegration class. In AltimateRequest, a new variable, jsonResponse, is introduced for parsing the response text into JSON format, improving the clarity of error messages. The error handling now includes structured management of specific HTTP status codes (401, 403, 404, 402, and 429). In DBTCloudProjectIntegration, the adapterType property is changed to an empty string, and error handling in various methods is improved for better robustness.

Changes

File Change Summary
src/altimate.ts Enhanced error handling in the fetch method, including better parsing of JSON responses and refined error messages for specific HTTP status codes.
src/dbt_client/dbtCloudIntegration.ts Updated adapterType property to an empty string, improved error handling in initializePaths, initializeProject, findAdapterType, and findVersion methods.

Possibly related PRs

Suggested reviewers

  • mdesmet
  • saravmajestic

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. (Experiment)
  • @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.

@AdiGajbhiye AdiGajbhiye requested a review from mdesmet December 9, 2024 03:10
Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 Looks good to me! Reviewed everything up to a107dc8 in 25 seconds

More details
  • Looked at 18 lines of code in 1 files
  • Skipped 0 files when reviewing.
  • Skipped posting 2 drafted comments based on config settings.
1. src/altimate.ts:652
  • Draft comment:
    Consider logging an error message if JSON parsing fails to help with debugging.
  • Reason this comment was not posted:
    Confidence changes required: 50%
    The try-catch block for JSON parsing should log an error if parsing fails.
2. src/altimate.ts:650
  • Draft comment:
    Use semantic versioning (semver) for version comparisons instead of direct array index comparisons.
  • Reason this comment was not posted:
    Comment was on unchanged code.

Workflow ID: wflow_X3KjUojC8xDYcDjA


You can customize Ellipsis with 👍 / 👎 feedback, review rules, user-specific overrides, quiet mode, and more.

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

🧹 Outside diff range and nitpick comments (1)
src/altimate.ts (1)

650-653: LGTM! Consider adding type annotation for better type safety.

The JSON parsing implementation with silent error handling is good. However, consider adding a type annotation for better type safety.

-      let jsonResponse: any;
+      let jsonResponse: { detail?: string };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ddda6f6 and a107dc8.

📒 Files selected for processing (1)
  • src/altimate.ts (1 hunks)
🔇 Additional comments (1)
src/altimate.ts (1)

654-656: LGTM! Error message enhancement improves debugging.

The enhanced error message now includes more context from the API response, making it easier to diagnose issues.

Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 Looks good to me! Incremental review on 896503f in 15 seconds

More details
  • Looked at 13 lines of code in 1 files
  • Skipped 0 files when reviewing.
  • Skipped posting 2 drafted comments based on config settings.
1. src/dbt_client/dbtCloudIntegration.ts:179
  • Draft comment:
    Changing adapterType from 'unknown' to an empty string may lead to issues if other parts of the code expect a non-empty string. Consider ensuring that this change won't cause unexpected behavior.
  • Reason this comment was not posted:
    Comment did not seem useful.
2. src/dbt_client/dbtCloudIntegration.ts:177
  • Draft comment:
    Ensure that semantic versioning is consistently used for version comparisons, as seen in the getVersion method. This applies to other places where version comparisons are made, such as in detectDBT and dbtCloudCommand methods.
  • Reason this comment was not posted:
    Confidence changes required: 50%
    The version property in DBTCloudProjectIntegration class is being compared using semantic versioning, which is correct. However, the getVersion method returns an array of numbers, which is then converted to a string for comparison. This is not a direct array index comparison, but it is worth noting that semantic versioning is being used correctly here.

Workflow ID: wflow_E2JrxmzIiiKUgzHO


You can customize Ellipsis with 👍 / 👎 feedback, review rules, user-specific overrides, quiet mode, and more.

@AdiGajbhiye AdiGajbhiye changed the title fix: backend error messages fix: backend error messages and dbt cloud adapterType Dec 9, 2024
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

🧹 Outside diff range and nitpick comments (1)
src/dbt_client/dbtCloudIntegration.ts (1)

Line range hint 892-930: Consider improving error handling in getBulkCompiledSQL.

The current implementation catches and logs errors but continues execution, which could lead to incomplete results. Consider:

  1. Aggregating errors and returning them with the results
  2. Adding a flag to indicate partial success
  3. Allowing the caller to decide how to handle failures

Here's a suggested improvement:

- async getBulkCompiledSQL(models: NodeMetaData[]) {
+ async getBulkCompiledSQL(models: NodeMetaData[]): Promise<{
+   results: Record<string, string>;
+   errors: Record<string, Error>;
+ }> {
   const downloadArtifactsVersion = "0.37.20";
   const currentVersion = this.getVersion()
     .map((part) => new String(part))
     .join(".");
   if (semver.gte(currentVersion, downloadArtifactsVersion)) {
     // ... existing code ...
   }
   const result: Record<string, string> = {};
+  const errors: Record<string, Error> = {};
   for (const node of models) {
     try {
       // compiled sql file exists
       const fileContentBytes = await workspace.fs.readFile(
         Uri.file(node.compiled_path),
       );
       const query = fileContentBytes.toString();
       result[node.uniqueId] = query;
       continue;
     } catch (e) {
       this.terminal.error(
         "getBulkCompiledSQL",
         `Unable to find compiled sql file for model ${node.uniqueId}`,
         e,
         true,
       );
+      errors[node.uniqueId] = e as Error;
     }

     try {
       // compiled sql file doesn't exists or dbt below 0.37.20
       result[node.uniqueId] = await this.unsafeCompileNode(node.name);
     } catch (e) {
       this.terminal.error(
         "getBulkCompiledSQL",
         `Unable to compile sql for model ${node.uniqueId}`,
         e,
         true,
       );
+      errors[node.uniqueId] = e as Error;
     }
   }
-  return result;
+  return { results: result, errors };
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a107dc8 and 896503f.

📒 Files selected for processing (1)
  • src/dbt_client/dbtCloudIntegration.ts (1 hunks)
🔇 Additional comments (2)
src/dbt_client/dbtCloudIntegration.ts (2)

Line range hint 1019-1042: LGTM! Error handling improvements look good.

The error handling has been improved with:

  • Proper JSON error processing
  • Clear error message extraction
  • Appropriate error level filtering (error/fatal)
  • Fallback for unparseable errors

179-179: Verify the impact of changing adapterType initialization.

Changing the default value from "unknown" to an empty string might affect code paths that check for adapter type. While the telemetry events have a fallback to "unknown", other code might rely on the non-empty default value.

✅ Verification successful

Based on the search results, I can now provide a conclusive response about the impact of changing adapterType from "unknown" to empty string:

The empty string initialization is safe as fallbacks to "unknown" are consistently implemented

The codebase shows a robust pattern where all usages of adapterType have proper fallback handling:

  • Direct property access always includes a fallback: this.adapterType || "unknown"
  • getAdapterType() calls are handled with fallbacks in the caller code: project.getAdapterType() || "unknown"
  • The value is properly initialized when needed through findAdapterType()

Key evidence from the codebase:

  • src/manifest/dbtProject.ts: return this.dbtProjectIntegration.getAdapterType() || "unknown";
  • src/dbt_client/dbtCoreIntegration.ts: { adapter: this.adapterType || "unknown" }
  • src/dbt_client/dbtCloudIntegration.ts: adapter: this.getAdapterType() || "unknown"
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all usages of adapterType to verify the impact
# Look for direct property access
rg -A 2 "\.adapterType\b"

# Look for getAdapterType method calls
rg -A 2 "\.getAdapterType\(\)"

# Look for potential type checks
rg -A 2 "adapter.*type.*=.*[\"']unknown[\"']"

Length of output: 10080

@@ -176,7 +176,7 @@ export class DBTCloudProjectIntegration
private targetPath?: string;
private version: number[] | undefined;
private projectName: string = "unknown_" + crypto.randomUUID();
private adapterType: string = "unknown";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this required, this will change azure logs?

src/altimate.ts Show resolved Hide resolved
Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 Looks good to me! Incremental review on 7e4e4b5 in 38 seconds

More details
  • Looked at 22 lines of code in 1 files
  • Skipped 0 files when reviewing.
  • Skipped posting 2 drafted comments based on config settings.
1. src/dbt_client/dbtCloudIntegration.ts:238
  • Draft comment:
    The check for adapterType should be consistent with its initialization. Consider using this.adapterType === "unknown" instead of checking for falsy values.
    if (this.adapterType === "unknown") {
  • Reason this comment was not posted:
    Comment looked like it was already resolved.
2. src/dbt_client/dbtCloudIntegration.ts:176
  • Draft comment:
    Please specify a return type for the getDBTPath function to improve code readability and maintainability. This issue is also present in other utility functions like initializePaths, findAdapterType, and findVersion.
  • Reason this comment was not posted:
    Comment was not on a valid diff hunk.

Workflow ID: wflow_h80ig0BAC1OHsxgk


You can customize Ellipsis with 👍 / 👎 feedback, review rules, user-specific overrides, quiet mode, and more.

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

🧹 Outside diff range and nitpick comments (3)
src/dbt_client/dbtCloudIntegration.ts (3)

241-244: Consider initializing adapterType with empty string for consistency

The code checks if adapterType === "unknown" but initializes it as "unknown". For better consistency with the rest of the codebase, consider initializing it as an empty string.

-  private adapterType: string = "unknown";
+  private adapterType: string = "";

Line range hint 379-386: Fix typo in error message

There's a typo in the error message: "environemnt" should be "environment".

-        "Could not initalize Python environemnt",
+        "Could not initialize Python environment",

Line range hint 744-754: Use safer model name handling in getBulkCompiledSQL

The current implementation concatenates model names directly into a string, which could be unsafe if model names contain special characters. Consider using proper escaping or a safer way to handle model names.

-          "--model",
-          `"${models.map((item) => item.name).join(" ")}"`,
+          "--model",
+          models.map(item => `"${item.name.replace(/"/g, '\\"')}"`).join(" "),
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 896503f and 7e4e4b5.

📒 Files selected for processing (1)
  • src/dbt_client/dbtCloudIntegration.ts (1 hunks)
🔇 Additional comments (1)
src/dbt_client/dbtCloudIntegration.ts (1)

241-244: Verify the impact of adapterType changes

The changes to adapterType handling might affect other parts of the codebase that rely on this behavior. Let's verify the usage:

✅ Verification successful

Let me gather more information about how adapterType is used in the codebase and how findAdapterType updates it.


Based on the search results, I can now generate the final response:

Changes to adapterType handling are localized and safe

The adapterType usage is well-contained within the codebase:

  • In dbtCloudIntegration.ts, it's initialized as "unknown" and only updated once via findAdapterType()
  • In dbtCoreIntegration.ts, it has similar usage patterns with proper fallbacks to "unknown"
  • The change ensures the adapter type is fetched only once, which is an optimization to prevent unnecessary compilation previews
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for references to adapterType
rg -A 3 'adapterType.*=.*"unknown"' || echo "No direct assignments to 'unknown' found"

# Search for comparisons with "unknown"
rg -A 3 'adapterType.*===.*"unknown"' || echo "No strict equality comparisons found"
rg -A 3 'adapterType.*==.*"unknown"' || echo "No loose equality comparisons found"

Length of output: 1406


Script:

#!/bin/bash
# Search for all references to adapterType
rg -A 3 'adapterType' --type ts

# Search for findAdapterType implementation
ast-grep --pattern 'async findAdapterType() {
  $$$
}'

Length of output: 3546

@mdesmet mdesmet merged commit 65d0173 into master Dec 11, 2024
9 checks passed
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.

3 participants