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 API Key Using Property #350

Merged

Conversation

davidvonthenen
Copy link
Contributor

@davidvonthenen davidvonthenen commented Nov 4, 2024

Proposed changes

Addresses: #342, #346

Tested using microphone streaming example.

Types of changes

What types of changes does your code introduce to the community .NET SDK?
Put an x in the boxes that apply

  • Bugfix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update or tests (if none of the other choices apply)

Checklist

Put an x in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your code.

  • I have read the CONTRIBUTING doc
  • I have lint'ed all of my code using repo standards
  • I have added tests that prove my fix is effective or that my feature works
  • I have added necessary documentation (if appropriate)

Further comments

NA

Summary by CodeRabbit

  • New Features

    • Enhanced logging for ApiKey and BaseAddress in client options, improving visibility during initialization.
    • Improved validation for ApiKey in both DeepgramHttpClientOptions and DeepgramWsClientOptions.
  • Bug Fixes

    • Removed the DetectTopics property from the Config record to address an identified error.
  • Refactor

    • Updated constructor logic in DeepgramHttpClientOptions and DeepgramWsClientOptions for better error handling and configuration validation.

Copy link
Contributor

coderabbitai bot commented Nov 4, 2024

Walkthrough

The pull request introduces modifications to the DeepgramHttpClientOptions and DeepgramWsClientOptions classes, primarily focusing on the constructor logic for handling the ApiKey property. Enhancements include conditional checks for empty or whitespace ApiKey values, improved logging for various parameters, and refined error handling. Additionally, the Config record in the Deepgram.Models.Manage.v1 namespace has seen the removal of the DetectTopics property, which has been commented out due to an error. Overall, these changes aim to improve validation and logging mechanisms within the client configuration.

Changes

File Path Change Summary
Deepgram/Models/Authenticate/v1/DeepgramHttpClientOptions.cs Modified constructor to include checks and logging for ApiKey, refined BaseAddress handling, and retained error handling for invalid ApiKey.
Deepgram/Models/Authenticate/v1/DeepgramWsClientOptions.cs Updated constructor to check and log ApiKey, improved error handling, and refined BaseAddress management.
Deepgram/Models/Manage/v1/Config.cs Commented out DetectTopics property due to an error, while retaining the rest of the properties.

Possibly related PRs

Suggested reviewers

  • lukeocodes
  • jpvajda
  • naomi-lgbt

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

@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: 3

🧹 Outside diff range and nitpick comments (3)
Deepgram/Models/Authenticate/v1/DeepgramWsClientOptions.cs (3)

Line range hint 100-150: Enhance validation and logging for better observability.

While the validation logic is functional, consider these improvements:

  1. Move API key validation earlier in the constructor.
  2. Use more descriptive error messages.
  3. Adjust log levels for better production monitoring.

Consider this structure:

 public DeepgramWsClientOptions(...)
 {
     Log.Verbose("DeepgramWsClientOptions", "ENTER");
+    
+    // Validate and set API key first
+    if (!string.IsNullOrWhiteSpace(apiKey))
+    {
+        ApiKey = apiKey;
+        Log.Information("DeepgramWsClientOptions", "Using provided API key");
+    }
+    else 
+    {
+        ApiKey = Environment.GetEnvironmentVariable(Defaults.DEEPGRAM_API_KEY) ?? string.Empty;
+        if (!string.IsNullOrWhiteSpace(ApiKey))
+        {
+            Log.Information("DeepgramWsClientOptions", "Using API key from environment");
+        }
+    }
+
+    if (!OnPrem && string.IsNullOrWhiteSpace(ApiKey))
+    {
+        throw new ArgumentException(
+            "Deepgram API Key is required. Provide it via constructor or DEEPGRAM_API_KEY environment variable."
+        );
+    }

     // Rest of the initialization...
 }

Line range hint 151-200: Simplify URL handling logic using Uri class.

The current implementation uses multiple regex operations for URL validation and transformation. Consider using .NET's Uri class for more robust URL handling.

Here's a suggested implementation:

private string NormalizeBaseAddress(string address)
{
    // Remove any existing protocols
    var cleanAddress = address.Replace("http://", "")
                             .Replace("https://", "")
                             .Replace("ws://", "")
                             .Replace("wss://", "");

    // Ensure API version
    if (!cleanAddress.Contains($"/v{APIVersion}"))
    {
        cleanAddress = $"{cleanAddress.TrimEnd('/')}/{APIVersion}";
    }

    // Create WebSocket URL
    var wsUrl = $"wss://{cleanAddress.TrimStart('/')}";
    return new Uri(wsUrl).AbsoluteUri.TrimEnd('/');
}

// Usage in constructor:
BaseAddress = NormalizeBaseAddress(baseAddress ?? Defaults.DEFAULT_URI);
Log.Information("DeepgramWsClientOptions", $"Normalized BaseAddress: {BaseAddress}");

This approach:

  1. Simplifies the logic by handling URL normalization in a single method
  2. Uses Uri class for validation and normalization
  3. Reduces regex usage
  4. Makes the transformation steps more clear and maintainable

Line range hint 201-250: Enhance addon value parsing and validation.

The current addon parsing logic silently ignores parsing failures and doesn't validate the parsed values.

Consider this improved implementation:

private decimal ParseAddonValue(string key, decimal defaultValue = 0)
{
    if (!Addons.TryGetValue(key, out var addonValue))
    {
        Log.Debug("DeepgramWsClientOptions", $"Addon {key} not found, using default: {defaultValue}");
        return defaultValue;
    }

    if (!decimal.TryParse(addonValue, out var parsedValue))
    {
        Log.Warning("DeepgramWsClientOptions", $"Failed to parse {key} value: {addonValue}, using default: {defaultValue}");
        return defaultValue;
    }

    if (parsedValue < 0)
    {
        Log.Warning("DeepgramWsClientOptions", $"Invalid negative value for {key}: {parsedValue}, using default: {defaultValue}");
        return defaultValue;
    }

    Log.Information("DeepgramWsClientOptions", $"Using {key}: {parsedValue}");
    return parsedValue;
}

// Usage in constructor:
AutoFlushReplyDelta = ParseAddonValue(Constants.AutoFlushReplyDelta);
AutoFlushSpeakDelta = ParseAddonValue(Constants.AutoFlushSpeakDelta);

This approach:

  1. Provides better error handling and logging
  2. Validates parsed values
  3. Uses a consistent pattern for all addon parsing
  4. Makes the code more maintainable
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5991268 and 5acc3ac.

📒 Files selected for processing (3)
  • Deepgram/Models/Authenticate/v1/DeepgramHttpClientOptions.cs (1 hunks)
  • Deepgram/Models/Authenticate/v1/DeepgramWsClientOptions.cs (1 hunks)
  • Deepgram/Models/Manage/v1/Config.cs (1 hunks)
🔇 Additional comments (1)
Deepgram/Models/Authenticate/v1/DeepgramHttpClientOptions.cs (1)

103-106: Verify API key usage across the codebase

Since this modifies core authentication behavior, we should verify:

  1. All client instantiations handle the API key correctly
  2. No breaking changes for existing usage patterns
  3. Consistent behavior between HTTP and WebSocket clients
✅ Verification successful

API key handling is consistent and properly implemented

The verification shows that:

  1. Both HTTP and WebSocket clients implement the same IDeepgramClientOptions interface
  2. API key initialization is consistent across both client types, using the same null-coalescing pattern (apiKey ?? "")
  3. The change in DeepgramHttpClientOptions maintains consistency with the existing pattern in the codebase
  4. Client instantiations in tests and examples follow the expected patterns

The modification to check for null/whitespace before setting the API key is a safe enhancement that maintains backward compatibility while adding an extra validation layer.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for DeepgramHttpClientOptions instantiations
echo "Checking DeepgramHttpClientOptions usage patterns:"
rg -A 2 "new DeepgramHttpClientOptions"

# Compare with WebSocket client implementation
echo -e "\nChecking for consistency with WebSocket client:"
rg -A 10 "class DeepgramWsClientOptions"

# Look for direct ApiKey property access
echo -e "\nChecking direct ApiKey property usage:"
rg "\.ApiKey\s*[=]"

Length of output: 6206


Script:

#!/bin/bash
# Let's check the implementation of both client options classes
echo "Checking DeepgramHttpClientOptions implementation:"
rg -A 15 "class DeepgramHttpClientOptions"

echo -e "\nChecking DeepgramWsClientOptions implementation:"
rg -A 15 "class DeepgramWsClientOptions"

# Check for interface definition
echo -e "\nChecking IDeepgramClientOptions interface:"
rg -A 10 "interface IDeepgramClientOptions"

# Check for actual API key usage in client implementations
echo -e "\nChecking API key usage in client implementations:"
rg -A 3 "ApiKey\s*=\s*apiKey" --type cs

Length of output: 5122

@davidvonthenen davidvonthenen merged commit 86b27b7 into deepgram:main Nov 4, 2024
5 checks passed
@davidvonthenen davidvonthenen deleted the fix-apikey-using-property branch November 4, 2024 17:24
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