stompman 3.0.0__tar.gz → 3.2.0__tar.gz

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,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: stompman
3
- Version: 3.0.0
3
+ Version: 3.2.0
4
4
  Summary: Python STOMP client with pleasant API
5
5
  Project-URL: repository, https://github.com/community-of-python/stompman
6
6
  Author-email: Lev Vereshchagin <mail@vrslev.com>
@@ -148,6 +148,7 @@ stompman takes care of cleaning up resources automatically. When you leave the c
148
148
 
149
149
  - When connection is lost, stompman will attempt to handle it automatically. `stompman.FailedAllConnectAttemptsError` will be raised if all connection attempts fail. `stompman.FailedAllWriteAttemptsError` will be raised if connection succeeds but sending a frame or heartbeat lead to losing connection.
150
150
  - To implement health checks, use `stompman.Client.is_alive()` — it will return `True` if everything is OK and `False` if server is not responding.
151
+ - `stompman` will write log warnings when connection is lost, after successful reconnection or invalid state during ack/nack.
151
152
 
152
153
  ### ...and caveats
153
154
 
@@ -30,6 +30,7 @@ from stompman.frames import (
30
30
  SubscribeFrame,
31
31
  UnsubscribeFrame,
32
32
  )
33
+ from stompman.logger import LOGGER as logger # noqa: N811
33
34
  from stompman.serde import FrameParser, dump_frame
34
35
  from stompman.subscription import AckableMessageFrame, AutoAckSubscription, ManualAckSubscription
35
36
  from stompman.transaction import Transaction
@@ -70,4 +71,5 @@ __all__ = [
70
71
  "UnsubscribeFrame",
71
72
  "UnsupportedProtocolVersion",
72
73
  "dump_frame",
74
+ "logger",
73
75
  ]
@@ -49,8 +49,8 @@ class Client:
49
49
  _active_subscriptions: ActiveSubscriptions = field(default_factory=ActiveSubscriptions, init=False)
50
50
  _active_transactions: set[Transaction] = field(default_factory=set, init=False)
51
51
  _exit_stack: AsyncExitStack = field(default_factory=AsyncExitStack, init=False)
52
- _listen_task: asyncio.Task[None] = field(init=False)
53
- _task_group: asyncio.TaskGroup = field(init=False)
52
+ _listen_task: asyncio.Task[None] = field(init=False, repr=False)
53
+ _task_group: asyncio.TaskGroup = field(init=False, repr=False)
54
54
 
55
55
  def __post_init__(self) -> None:
56
56
  self._connection_manager = ConnectionManager(
@@ -36,7 +36,7 @@ class ConnectionParameters:
36
36
  return unquote(self.passcode)
37
37
 
38
38
  @classmethod
39
- def from_pydantic_multihost_hosts(cls, hosts: list[MultiHostHostLike]) -> list[Self]: # noqa: C901
39
+ def from_pydantic_multihost_hosts(cls, hosts: list[MultiHostHostLike]) -> list[Self]:
40
40
  """Create connection parameters from `pydantic_code.MultiHostUrl.hosts()`.
41
41
 
42
42
  .. code-block:: python
@@ -76,9 +76,8 @@ class ConnectionParameters:
76
76
  msg = "password is set, username must be set"
77
77
  raise ValueError(msg)
78
78
  elif password is None:
79
- if username is not None:
80
- msg = "username is set, password must be set"
81
- raise ValueError(msg)
79
+ msg = "username is set, password must be set"
80
+ raise ValueError(msg)
82
81
  else:
83
82
  all_credentials.append((username, password))
84
83
 
@@ -28,6 +28,8 @@ class EstablishedConnectionResult:
28
28
 
29
29
 
30
30
  class AbstractConnectionLifespan(Protocol):
31
+ connection_parameters: ConnectionParameters
32
+
31
33
  async def enter(self) -> EstablishedConnectionResult | StompProtocolConnectionIssue: ...
32
34
  async def exit(self) -> None: ...
33
35
 
@@ -11,12 +11,13 @@ from stompman.connection import AbstractConnection
11
11
  from stompman.errors import (
12
12
  AllServersUnavailable,
13
13
  AnyConnectionIssue,
14
- ConnectionLost,
15
14
  ConnectionLostError,
15
+ ConnectionLostOnLifespanEnter,
16
16
  FailedAllConnectAttemptsError,
17
17
  FailedAllWriteAttemptsError,
18
18
  )
19
19
  from stompman.frames import AnyClientFrame, AnyServerFrame
20
+ from stompman.logger import LOGGER
20
21
 
21
22
  if TYPE_CHECKING:
22
23
  from stompman.connection_lifespan import AbstractConnectionLifespan, ConnectionLifespanFactory
@@ -60,7 +61,7 @@ class ConnectionManager:
60
61
  await self._task_group.__aenter__()
61
62
  self._send_heartbeat_task = self._task_group.create_task(asyncio.sleep(0))
62
63
  self._check_server_heartbeat_task = self._task_group.create_task(asyncio.sleep(0))
63
- self._active_connection_state = await self._get_active_connection_state()
64
+ self._active_connection_state = await self._get_active_connection_state(is_initial_call=True)
64
65
  return self
65
66
 
66
67
  async def __aexit__(
@@ -102,7 +103,7 @@ class ConnectionManager:
102
103
  if not self._active_connection_state:
103
104
  continue
104
105
  if not self._active_connection_state.is_alive(self.check_server_alive_interval_factor):
105
- self._active_connection_state = None
106
+ self._clear_active_connection_state()
106
107
 
107
108
  async def _create_connection_to_one_server(
108
109
  self, server: ConnectionParameters
@@ -140,7 +141,7 @@ class ConnectionManager:
140
141
  try:
141
142
  connection_result = await lifespan.enter()
142
143
  except ConnectionLostError:
143
- return ConnectionLost()
144
+ return ConnectionLostOnLifespanEnter()
144
145
 
145
146
  return (
146
147
  ActiveConnectionState(
@@ -150,7 +151,7 @@ class ConnectionManager:
150
151
  else connection_result
151
152
  )
152
153
 
153
- async def _get_active_connection_state(self) -> ActiveConnectionState:
154
+ async def _get_active_connection_state(self, *, is_initial_call: bool = False) -> ActiveConnectionState:
154
155
  if self._active_connection_state:
155
156
  return self._active_connection_state
156
157
 
@@ -165,6 +166,11 @@ class ConnectionManager:
165
166
 
166
167
  if isinstance(connection_result, ActiveConnectionState):
167
168
  self._active_connection_state = connection_result
169
+ if not is_initial_call:
170
+ LOGGER.warning(
171
+ "reconnected after failure connection failure. connection_parameters: %s",
172
+ connection_result.lifespan.connection_parameters,
173
+ )
168
174
  return connection_result
169
175
 
170
176
  connection_issues.append(connection_result)
@@ -173,6 +179,12 @@ class ConnectionManager:
173
179
  raise FailedAllConnectAttemptsError(retry_attempts=self.connect_retry_attempts, issues=connection_issues)
174
180
 
175
181
  def _clear_active_connection_state(self) -> None:
182
+ if not self._active_connection_state:
183
+ return
184
+ LOGGER.warning(
185
+ "connection lost. connection_parameters: %s",
186
+ self._active_connection_state.lifespan.connection_parameters,
187
+ )
176
188
  self._active_connection_state = None
177
189
 
178
190
  async def write_heartbeat_reconnecting(self) -> None:
@@ -28,7 +28,7 @@ class UnsupportedProtocolVersion:
28
28
 
29
29
 
30
30
  @dataclass(frozen=True, kw_only=True, slots=True)
31
- class ConnectionLost: ...
31
+ class ConnectionLostOnLifespanEnter: ...
32
32
 
33
33
 
34
34
  @dataclass(frozen=True, kw_only=True, slots=True)
@@ -38,7 +38,7 @@ class AllServersUnavailable:
38
38
 
39
39
 
40
40
  StompProtocolConnectionIssue = ConnectionConfirmationTimeout | UnsupportedProtocolVersion
41
- AnyConnectionIssue = StompProtocolConnectionIssue | ConnectionLost | AllServersUnavailable
41
+ AnyConnectionIssue = StompProtocolConnectionIssue | ConnectionLostOnLifespanEnter | AllServersUnavailable
42
42
 
43
43
 
44
44
  @dataclass(kw_only=True)
@@ -0,0 +1,5 @@
1
+ import logging
2
+ from typing import Final
3
+
4
+ __all__ = ["LOGGER"]
5
+ LOGGER: Final = logging.getLogger("stompman")
@@ -46,7 +46,7 @@ HEADER_UNESCAPE_CHARS: Final = {
46
46
  }
47
47
 
48
48
 
49
- def iter_bytes(bytes_: bytes) -> tuple[bytes, ...]:
49
+ def iter_bytes(bytes_: bytes | bytearray) -> tuple[bytes, ...]:
50
50
  return struct.unpack(f"{len(bytes_)!s}c", bytes_)
51
51
 
52
52
 
@@ -14,6 +14,7 @@ from stompman.frames import (
14
14
  SubscribeFrame,
15
15
  UnsubscribeFrame,
16
16
  )
17
+ from stompman.logger import LOGGER
17
18
 
18
19
 
19
20
  @dataclass(kw_only=True, slots=True, frozen=True)
@@ -30,8 +31,12 @@ class ActiveSubscriptions:
30
31
  def get_all(self) -> list["AutoAckSubscription | ManualAckSubscription"]:
31
32
  return list(self.subscriptions.values())
32
33
 
34
+ def get_ids(self) -> list[str]:
35
+ return list(self.subscriptions.keys())
36
+
33
37
  def delete_by_id(self, subscription_id: str) -> None:
34
- del self.subscriptions[subscription_id]
38
+ if subscription_id in self.subscriptions:
39
+ del self.subscriptions[subscription_id]
35
40
  if not self.subscriptions:
36
41
  self.event.set()
37
42
 
@@ -68,16 +73,46 @@ class BaseSubscription:
68
73
  await self._connection_manager.maybe_write_frame(UnsubscribeFrame(headers={"id": self.id}))
69
74
 
70
75
  async def _nack(self, frame: MessageFrame) -> None:
71
- if self._active_subscriptions.contains_by_id(self.id) and (ack_id := frame.headers.get("ack")):
72
- await self._connection_manager.maybe_write_frame(
73
- NackFrame(headers={"id": ack_id, "subscription": frame.headers["subscription"]})
76
+ if not self._active_subscriptions.contains_by_id(self.id):
77
+ LOGGER.warning(
78
+ "failed to nack message frame: subscription is not active. "
79
+ "message_id: %s, subscription_id: %s, active_subscriptions: %s",
80
+ frame.headers["message-id"],
81
+ self.id,
82
+ self._active_subscriptions.get_ids(),
83
+ )
84
+ return
85
+ if not (ack_id := frame.headers.get("ack")):
86
+ LOGGER.warning(
87
+ 'failed to nack message frame: it has no "ack" header. "'
88
+ "message_id: %s, subscription_id: %s, frame_header_names: %s",
89
+ frame.headers["message-id"],
90
+ self.id,
91
+ frame.headers.keys(),
74
92
  )
93
+ return
94
+ await self._connection_manager.maybe_write_frame(NackFrame(headers={"id": ack_id, "subscription": self.id}))
75
95
 
76
96
  async def _ack(self, frame: MessageFrame) -> None:
77
- if self._active_subscriptions.contains_by_id(self.id) and (ack_id := frame.headers["ack"]):
78
- await self._connection_manager.maybe_write_frame(
79
- AckFrame(headers={"id": ack_id, "subscription": frame.headers["subscription"]})
97
+ if not self._active_subscriptions.contains_by_id(self.id):
98
+ LOGGER.warning(
99
+ "failed to ack message frame: subscription is not active. "
100
+ "message_id: %s, subscription_id: %s, active_subscriptions: %s",
101
+ frame.headers["message-id"],
102
+ self.id,
103
+ self._active_subscriptions.get_ids(),
104
+ )
105
+ return
106
+ if not (ack_id := frame.headers.get("ack")):
107
+ LOGGER.warning(
108
+ 'failed to ack message frame: it has no "ack" header. "'
109
+ "message_id: %s, subscription_id: %s, frame_header_names: %s",
110
+ frame.headers["message-id"],
111
+ self.id,
112
+ frame.headers.keys(),
80
113
  )
114
+ return
115
+ await self._connection_manager.maybe_write_frame(AckFrame(headers={"id": ack_id, "subscription": self.id}))
81
116
 
82
117
 
83
118
  @dataclass(kw_only=True, slots=True)
File without changes
File without changes
File without changes
File without changes