Skip to content

Commit 5737257

Browse files
Implement client instance reuse to avoid redundant TCP connections (#56)
This PR modifies the `Client` class to ensure that a single instance is reused for the same `server_url` and `auth_key`, preventing the creation of multiple TCP connections to the Electricity Trading API. This change is especially useful in environments with multiple actors or services interacting with the same API.
2 parents fe912f6 + a4aba45 commit 5737257

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

RELEASE_NOTES.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
## New Features
1212

1313
* Replace assert statements with proper exception handling
14+
* Implement client instance reuse to avoid redundant TCP connections
1415

1516
## Bug Fixes
1617

src/frequenz/client/electricity_trading/_client.py

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,32 @@ def validate_decimal_places(value: Decimal, decimal_places: int, name: str) -> N
8484
class Client(BaseApiClient[ElectricityTradingServiceStub]):
8585
"""Electricity trading client."""
8686

87+
_instances: dict[tuple[str, str | None], "Client"] = {}
88+
89+
def __new__(
90+
cls, server_url: str, connect: bool = True, auth_key: str | None = None
91+
) -> "Client":
92+
"""
93+
Create a new instance of the client or return an existing one if it already exists.
94+
95+
Args:
96+
server_url: The URL of the Electricity Trading service.
97+
connect: Whether to connect to the server immediately.
98+
auth_key: The API key for the authorization.
99+
100+
Returns:
101+
The client instance.
102+
"""
103+
key = (server_url, auth_key)
104+
105+
# Check if an instance already exists for this key
106+
if key not in cls._instances:
107+
# If not, create a new instance and store it in the cache
108+
instance = super(Client, cls).__new__(cls)
109+
cls._instances[key] = instance
110+
111+
return cls._instances[key]
112+
87113
def __init__(
88114
self, server_url: str, connect: bool = True, auth_key: str | None = None
89115
) -> None:
@@ -94,7 +120,11 @@ def __init__(
94120
connect: Whether to connect to the server immediately.
95121
auth_key: The API key for the authorization.
96122
"""
97-
super().__init__(server_url, ElectricityTradingServiceStub, connect=connect)
123+
if not hasattr(
124+
self, "_initialized"
125+
): # Prevent re-initialization of existing instances
126+
super().__init__(server_url, ElectricityTradingServiceStub, connect=connect)
127+
self._initialized = True
98128

99129
self._gridpool_orders_streams: dict[
100130
tuple[int, GridpoolOrderFilter],

0 commit comments

Comments
 (0)