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

Add threading.Thread Class Override #490

Merged
merged 4 commits into from
Jan 7, 2025

Conversation

gerrymeixiong
Copy link
Contributor

@gerrymeixiong gerrymeixiong commented Dec 16, 2024

Proposed changes

This adds the ability to override the threading.Thread class used within ListenWebSocketClient.

By default, the standard Python threading.Thread class will be used. There is an option to specify an override which sub-classes threading.Thread.

Custom thread classes may be used for session management and logging, such as when using ContextVar.

Types of changes

What types of changes does your code introduce to the community Python 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

Summary by CodeRabbit

  • New Features
    • Introduced a customizable threading option for the WebSocket client, allowing users to specify a custom thread class.
  • Bug Fixes
    • Improved thread management for keep-alive and flush operations without altering existing functionality.

Copy link
Contributor

coderabbitai bot commented Dec 16, 2024

Walkthrough

The pull request introduces a new parameter thread_cls to the WebSocket client classes in the Deepgram library. This parameter allows developers to specify a custom thread class when initializing WebSocket clients, providing more flexibility in thread management. The changes are made in two files: the abstract sync WebSocket client and the listen WebSocket client. The modification enables custom thread class injection while maintaining the default behavior of using the standard threading.Thread.

Changes

File Change Summary
deepgram/clients/common/v1/abstract_sync_websocket.py - Added thread_cls parameter to __init__ method
- Default value set to threading.Thread
- Updated thread initialization to use thread_cls
deepgram/clients/listen/v1/websocket/client.py - Added thread_cls parameter to __init__ method
- Added _thread_cls attribute
- Updated thread creation to use self._thread_cls
- Added Type import for type hinting

Sequence Diagram

sequenceDiagram
    participant Client as WebSocket Client
    participant ThreadFactory as Thread Factory
    
    Client->>ThreadFactory: Specify custom thread class (optional)
    alt Default Thread
        ThreadFactory-->>Client: Use threading.Thread
    else Custom Thread
        ThreadFactory-->>Client: Use provided custom thread class
    end
    
    Client->>ThreadFactory: Create threads for operations
    ThreadFactory-->>Client: Return thread instances
Loading

The sequence diagram illustrates how the new thread_cls parameter allows for flexible thread class selection during WebSocket client initialization, with a fallback to the standard threading.Thread if no custom class is provided.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e84be76 and e4b2ab7.

📒 Files selected for processing (2)
  • deepgram/clients/common/v1/abstract_sync_websocket.py (5 hunks)
  • deepgram/clients/listen/v1/websocket/client.py (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • deepgram/clients/listen/v1/websocket/client.py
  • deepgram/clients/common/v1/abstract_sync_websocket.py

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.

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

🧹 Nitpick comments (3)
deepgram/clients/common/v1/abstract_sync_websocket.py (1)

159-159: Document the thread_cls parameter usage

The thread creation correctly uses the custom thread class. Consider adding documentation about this parameter in the class docstring.

Add to the class docstring:

 """
 Abstract class for using WebSockets.

 This class provides methods to establish a WebSocket connection generically for
 use in all WebSocket clients.
+
+ Args:
+     config (DeepgramClientOptions): all the options for the client
+     endpoint (str): the endpoint to connect to
+     thread_cls (Type[threading.Thread]): optional thread class to use for creating threads,
+         defaults to threading.Thread. Useful for custom thread management like ContextVar support.
 """
deepgram/clients/listen/v1/websocket/client.py (2)

65-65: Document the thread_cls parameter in ListenWebSocketClient

The thread class parameter implementation is correct. Consider updating the class docstring to document this parameter.

Add to the class docstring:

 """
 Client for interacting with Deepgram's live transcription services over WebSockets.

 This class provides methods to establish a WebSocket connection for live transcription and handle real-time transcription events.

 Args:
     config (DeepgramClientOptions): all the options for the client.
+    thread_cls (Type[threading.Thread]): optional thread class to use for creating threads,
+        defaults to threading.Thread. Useful for custom thread management like ContextVar support.
 """

Also applies to: 83-83


169-169: LGTM: Flush thread uses custom thread class

The flush thread correctly uses the configured thread class. Consider adding tests to verify custom thread class behavior.

Would you like me to help create test cases for verifying custom thread class functionality? This could include:

  1. Basic thread class override verification
  2. ContextVar propagation tests
  3. Thread lifecycle tests
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7df7b27 and 000d45c.

📒 Files selected for processing (2)
  • deepgram/clients/common/v1/abstract_sync_websocket.py (4 hunks)
  • deepgram/clients/listen/v1/websocket/client.py (4 hunks)
🔇 Additional comments (4)
deepgram/clients/common/v1/abstract_sync_websocket.py (2)

7-7: LGTM: Type imports and thread class attribute

The changes correctly add type hinting support and class attribute for thread class customization.

Also applies to: 55-55


62-62: LGTM: Constructor changes for thread class customization

The thread class parameter is correctly implemented with proper typing and default value, maintaining backward compatibility.

Also applies to: 78-78

✅ Verification successful

Thread class customization is properly implemented across the inheritance chain

The verification confirms that:

  • AbstractSyncWebSocketClient is the base class with proper thread_cls parameter implementation
  • Both concrete implementations (ListenWebSocketClient and SpeakWSClient) inherit from it
  • The thread_cls parameter is consistently used across the codebase for thread creation in:
    • Base class: _listen_thread creation
    • ListenWebSocketClient: _keep_alive_thread and _flush_thread creation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the inheritance chain to ensure no conflicts
ast-grep --pattern 'class $_ (AbstractSyncWebSocketClient) {
  $$$
}'

Length of output: 71


Script:

#!/bin/bash
# Let's try a different approach to verify the inheritance chain
# First, let's find all Python files that might contain the class
fd '\.py$' --exec grep -l "AbstractSyncWebSocketClient" {}

# Then, let's examine the content of these files to understand the inheritance
fd '\.py$' --exec grep -A 5 "class.*AbstractSyncWebSocketClient" {}

Length of output: 677


Script:

#!/bin/bash
# Let's examine the concrete implementations to verify thread_cls usage
rg -A 5 "class.*\(" ./deepgram/clients/listen/v1/websocket/client.py
rg -A 5 "class.*\(" ./deepgram/clients/speak/v1/websocket/client.py

# Also check for any existing thread_cls usage
rg "thread_cls" ./deepgram/clients/

Length of output: 1692

deepgram/clients/listen/v1/websocket/client.py (2)

7-7: LGTM: Consistent thread class attribute implementation

The changes correctly mirror the parent class implementation.

Also applies to: 58-58


161-161: LGTM: Keep-alive thread uses custom thread class

The keep-alive thread correctly uses the configured thread class.

@gerrymeixiong
Copy link
Contributor Author

gerrymeixiong commented Dec 16, 2024

Hey @davidvonthenen, @DamienDeepgram - can you let me know what you think about this change? This would help us at Hippocratic as we have custom thread classes (mostly for logging) and would like to pass them in when we open socket connections using the SDK.

@DamienDeepgram
Copy link
Contributor

Thanks for the PR.

Can you share a little more context about the motivation for this PR?

  • Why is it needed?
  • What challenge does it solve?
  • Is it required for development only or also needed in prod?

Also it would help to add a working example for this that can be run which shows how it would work and add it to be part of the CI to make sure it does not break.

@gerrymeixiong
Copy link
Contributor Author

Thanks for the PR.

Can you share a little more context about the motivation for this PR?

  • Why is it needed?
    We have custom threading classes that use ContextVar to supplement logging. For example, we are able to group logs according to UUIDs. This is useful for log querying and debugging, particularly when errors occur.
  • What challenge does it solve?
    Similar to above. Default behavior is the same, but it'd be nice to have the option to specify a custom Thread subclass.
  • Is it required for development only or also needed in prod?
    For my use-case, it would be nice to have it in prod.

Also it would help to add a working example for this that can be run which shows how it would work and add it to be part of the CI to make sure it does not break.

@jpvajda jpvajda requested a review from lukeocodes December 17, 2024 16:04
@gerrymeixiong
Copy link
Contributor Author

gerrymeixiong commented Dec 17, 2024

Also @DamienDeepgram, I'm having trouble adding an example as I believe the existing examples in examples/ rely on the installed deepgram module and not the source code in the repo.

@jpvajda
Copy link
Contributor

jpvajda commented Dec 23, 2024

@gerrymeixiong Yes, the examples rely on the installed Deepgram module rather than the source code. This is evident from the import statement. This import statement pulls from the installed deepgram package rather than the local source code.

from deepgram import (
    DeepgramClient,
    ClientOptionsFromEnv,
    PrerecordedOptions,
)

@gerrymeixiong
Copy link
Contributor Author

Do you have any suggestions on how to add an example?

@jpvajda
Copy link
Contributor

jpvajda commented Dec 23, 2024

@gerrymeixiong

I'm debating if we actually need one, Most of our examples show how the API works and can be used for testing and validating features. It really depends on if this is consider a major feature of the SDK, or just a minor one.

Though if you were too create one, you can probably borrow code from an existing one, and add in this threading override.

Also if you can review the Code Rabbit Suggestions here, It would be good to add this addition information

@jpvajda
Copy link
Contributor

jpvajda commented Dec 23, 2024

@gerrymeixiong Let's skip the example for now, and if you can address those comments by Code Rabbit this will move the PR along.

@jpvajda jpvajda added the needs information Needs information from user label Dec 23, 2024
@gerrymeixiong
Copy link
Contributor Author

@gerrymeixiong Let's skip the example for now, and if you can address those comments by Code Rabbit this will move the PR along.

Thanks @jpvajda. I've addressed Code Rabbit's comments.

@naomi-lgbt naomi-lgbt merged commit ad276e1 into deepgram:main Jan 7, 2025
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs information Needs information from user
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants