Standard-Labs / real-intent

Python SDK and abstracted interface for Real Intent operations.
https://realintent.co
0 stars 0 forks source link

Thread safety in the main client #41

Closed preritdas closed 3 months ago

preritdas commented 3 months ago

Implement Thread Safety in BigDBMClient to Prevent Race Conditions

Description

The current implementation of BigDBMClient is not thread-safe, particularly in its access token management. This can lead to race conditions when the class is used in concurrent scenarios, potentially causing unexpected behavior or errors.

Current Behavior

Proposed Solution

Implement thread-safe mechanisms to protect critical sections of the BigDBMClient class, focusing on access token management.

Steps:

  1. Add a threading lock to the class.
  2. Use the lock to protect access to token-related methods.
  3. Consider using thread-local storage for high-concurrency scenarios.

Example Implementation

from threading import Lock

class BigDBMClient:
    def __init__(self, client_id: str, client_secret: str, logging: bool = DEFAULT_LOGGING) -> None:
        # ... existing code ...
        self._token_lock = Lock()

    def _update_token(self) -> None:
        with self._token_lock:
            # ... existing token update code ...

    def _access_token_valid(self) -> bool:
        with self._token_lock:
            # ... existing token validation code ...

    def __request(self, request: Request) -> dict:
        with self._token_lock:
            if not self._access_token_valid():
                self._update_token()
        # ... rest of the method ...

Additional Considerations

Expected Outcome

Testing

Questions