h-message-bus 0.0.39__py3-none-any.whl → 0.0.40__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
1
  import logging
2
+ import asyncio
2
3
  from typing import Optional, Callable, Any
3
4
 
4
5
  import nats
@@ -6,37 +7,34 @@ from nats.aio.client import Client as NatsClient
6
7
 
7
8
  from ..infrastructure.nats_config import NatsConfig
8
9
 
9
-
10
10
  class NatsClientRepository:
11
11
  """
12
12
  Repository for managing connection and interaction with a NATS server.
13
-
14
- This class provides methods to establish a connection with a NATS server,
15
- publish and subscribe to subjects, send requests and handle responses, and
16
- cleanly disconnect from the server. It abstracts the connection and ensures
17
- seamless communication with the NATS server.
18
-
19
- :ivar config: Configuration details for the NATS client, including server
20
- connection parameters, timeouts, and limits.
21
- :type config: NatsConfig
22
- :ivar client: Instance of the NATS client used for communication. Initialized
23
- as None and assigned upon connecting to a NATS server.
24
- :type client: Optional[NatsClient]
25
- :ivar subscriptions: List of active subscriptions for NATS subjects.
26
- :type subscriptions: list
27
13
  """
28
14
 
29
15
  def __init__(self, config: NatsConfig):
30
16
  self.config = config
31
- self.client: NatsClient | None = None
32
-
17
+ self.client: Optional[NatsClient] = None
33
18
  self.subscriptions = []
34
19
  self.logger = logging.getLogger(__name__)
35
20
 
36
21
  async def connect(self) -> None:
37
- """Connect to NATS server."""
22
+ """Connect to NATS server with event handlers and logging."""
38
23
  if self.client and self.client.is_connected:
39
24
  return
25
+
26
+ async def error_cb(e):
27
+ self.logger.error(f"NATS client error: {e}")
28
+
29
+ async def disconnect_cb():
30
+ self.logger.warning("NATS client disconnected.")
31
+
32
+ async def reconnect_cb():
33
+ self.logger.info("NATS client reconnected.")
34
+
35
+ async def closed_cb():
36
+ self.logger.warning("NATS client connection closed.")
37
+
40
38
  self.logger.info(f"Connecting to NATS server at {self.config.server}")
41
39
 
42
40
  self.client = await nats.connect(
@@ -45,49 +43,67 @@ class NatsClientRepository:
45
43
  reconnect_time_wait=self.config.reconnect_time_wait,
46
44
  connect_timeout=self.config.connection_timeout,
47
45
  ping_interval=self.config.ping_interval,
48
- max_outstanding_pings=self.config.max_outstanding_pings
49
- ) #ignore client type warning
50
-
51
- async def publish(self, subject: str, payload: bytes) -> None:
52
- """Publish raw message to NATS."""
53
- if not self.client or not self.client.is_connected:
54
- await self.connect()
55
-
56
- try:
57
- await self.client.publish(subject, payload)
58
- except Exception as e:
59
- print(f"Failed to publish message: {e}")
60
- return
46
+ max_outstanding_pings=self.config.max_outstanding_pings,
47
+ error_cb=error_cb,
48
+ disconnected_cb=disconnect_cb,
49
+ reconnected_cb=reconnect_cb,
50
+ closed_cb=closed_cb,
51
+ ) # type: ignore
52
+
53
+ async def _ensure_connected(self, retries: int = 5):
54
+ """Wait and retry until the client is connected."""
55
+ for attempt in range(retries):
56
+ if self.client and self.client.is_connected:
57
+ return
58
+ self.logger.info(f"Waiting for NATS connection (attempt {attempt+1})...")
59
+ await asyncio.sleep(2 ** attempt)
60
+ raise ConnectionError("Could not establish connection to NATS server.")
61
+
62
+ async def publish(self, subject: str, payload: bytes, retries: int = 3) -> None:
63
+ """Publish raw message to NATS with retries and backoff."""
64
+ for attempt in range(retries):
65
+ try:
66
+ await self._ensure_connected()
67
+ await self.client.publish(subject, payload)
68
+ return
69
+ except Exception as e:
70
+ self.logger.error(f"Failed to publish message (attempt {attempt+1}): {e}")
71
+ await asyncio.sleep(2 ** attempt)
72
+ self.logger.error("Giving up publishing after retries.")
61
73
 
62
74
  async def subscribe(self, subject: str, callback: Callable) -> Any:
63
75
  """Subscribe to a subject with a callback."""
64
- if not self.client or not self.client.is_connected:
65
- await self.connect()
66
-
67
- subscription = await self.client.subscribe(subject, cb=callback)
68
- self.subscriptions.append(subscription)
69
- return subscription
70
-
71
- async def request(self, subject: str, payload: bytes, timeout: float = 2.0) -> Optional[bytes]:
72
- """Send a request and get raw response."""
73
- if not self.client or not self.client.is_connected:
74
- await self.connect()
75
-
76
+ await self._ensure_connected()
76
77
  try:
77
- response = await self.client.request(subject, payload, timeout=timeout)
78
- return response.data
78
+ subscription = await self.client.subscribe(subject, cb=callback)
79
+ self.subscriptions.append(subscription)
80
+ return subscription
79
81
  except Exception as e:
80
- print(f"NATS request failed: {e}")
82
+ self.logger.error(f"Failed to subscribe to {subject}: {e}")
81
83
  return None
82
84
 
85
+ async def request(self, subject: str, payload: bytes, timeout: float = 2.0, retries: int = 3) -> Optional[bytes]:
86
+ """Send a request and get raw response with retries and backoff."""
87
+ for attempt in range(retries):
88
+ try:
89
+ await self._ensure_connected()
90
+ response = await self.client.request(subject, payload, timeout=timeout)
91
+ return response.data
92
+ except Exception as e:
93
+ self.logger.error(f"NATS request failed (attempt {attempt+1}): {e}")
94
+ await asyncio.sleep(2 ** attempt)
95
+ self.logger.error("Giving up request after retries.")
96
+ return None
97
+
83
98
  async def close(self) -> None:
84
99
  """Close all subscriptions and NATS connection."""
85
100
  if self.client and self.client.is_connected:
86
- # Unsubscribe from all subscriptions
87
- for sub in self.subscriptions:
88
- await sub.unsubscribe()
89
-
90
- # Drain and close connection
91
- await self.client.drain()
92
- self.client = None
93
- self.subscriptions = []
101
+ try:
102
+ for sub in self.subscriptions:
103
+ await sub.unsubscribe()
104
+ await self.client.drain()
105
+ except Exception as e:
106
+ self.logger.error(f"Error during NATS cleanup: {e}")
107
+ finally:
108
+ self.client = None
109
+ self.subscriptions = []
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: h_message_bus
3
- Version: 0.0.39
3
+ Version: 0.0.40
4
4
  Summary: Message bus integration for HAI
5
5
  Author-email: shoebill <shoebill.hai@gmail.com>
6
6
  Classifier: Programming Language :: Python :: 3
@@ -68,9 +68,9 @@ h_message_bus/domain/request_messages/vector_save_request_message.py,sha256=Xqrd
68
68
  h_message_bus/domain/request_messages/web_get_docs_request_message.py,sha256=MkJySkRBlQ2CacMoPCd3FwXQt1tVVFdrZKxsA6yMsrk,1576
69
69
  h_message_bus/domain/request_messages/web_search_request_message.py,sha256=ZoB4idrFEs7HQ6IRxmwKrrfHWe3GlGF4LuOK68K5NEM,1000
70
70
  h_message_bus/infrastructure/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
71
- h_message_bus/infrastructure/nats_client_repository.py,sha256=bhaWRK94h2EmFIef2DALnoBJKnuTnx6-iU7IXO2S_EU,3642
71
+ h_message_bus/infrastructure/nats_client_repository.py,sha256=crxWCGkBS-DcUm5Ii4ngCCgQR32tedCEXVk9Tdq0ErY,4501
72
72
  h_message_bus/infrastructure/nats_config.py,sha256=Yzqqd1bCfmUv_4FOnA1dvqIpakzV0BUL2_nXQcndWvo,1304
73
- h_message_bus-0.0.39.dist-info/METADATA,sha256=KmLu3QbSLShufr-5caSergImL_oW9vElqIRMmXM8eqo,8834
74
- h_message_bus-0.0.39.dist-info/WHEEL,sha256=DnLRTWE75wApRYVsjgc6wsVswC54sMSJhAEd4xhDpBk,91
75
- h_message_bus-0.0.39.dist-info/top_level.txt,sha256=BArjhm_lwFR9yJJEIf-LT_X64psuLkXFdbpQRJUreFE,23
76
- h_message_bus-0.0.39.dist-info/RECORD,,
73
+ h_message_bus-0.0.40.dist-info/METADATA,sha256=UgqzgrRDT29K82kJkbnalFCnBq_SoHBhI0dx8OFPZ8s,8834
74
+ h_message_bus-0.0.40.dist-info/WHEEL,sha256=Nw36Djuh_5VDukK0H78QzOX-_FQEo6V37m3nkm96gtU,91
75
+ h_message_bus-0.0.40.dist-info/top_level.txt,sha256=BArjhm_lwFR9yJJEIf-LT_X64psuLkXFdbpQRJUreFE,23
76
+ h_message_bus-0.0.40.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (80.4.0)
2
+ Generator: setuptools (80.7.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5