stompman 3.1.0__tar.gz → 3.3.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.1.0
3
+ Version: 3.3.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>
@@ -56,7 +56,6 @@ async with stompman.Client(
56
56
  disconnect_confirmation_timeout=2,
57
57
  write_retry_attempts=3,
58
58
  check_server_alive_interval_factor=3,
59
- max_concurrent_consumed_messages=10,
60
59
  ) as client:
61
60
  ...
62
61
  ```
@@ -149,6 +148,7 @@ stompman takes care of cleaning up resources automatically. When you leave the c
149
148
 
150
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.
151
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.
152
152
 
153
153
  ### ...and caveats
154
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
  ]
@@ -42,17 +42,15 @@ class Client:
42
42
  disconnect_confirmation_timeout: int = 2
43
43
  check_server_alive_interval_factor: int = 3
44
44
  """Client will check if server alive `server heartbeat interval` times `interval factor`"""
45
- max_concurrent_consumed_messages: int = 10
46
45
 
47
46
  connection_class: type[AbstractConnection] = Connection
48
47
 
49
48
  _connection_manager: ConnectionManager = field(init=False)
50
- _active_subscriptions: ActiveSubscriptions = field(default_factory=ActiveSubscriptions, init=False, repr=False)
49
+ _active_subscriptions: ActiveSubscriptions = field(default_factory=ActiveSubscriptions, init=False)
51
50
  _active_transactions: set[Transaction] = field(default_factory=set, init=False)
52
51
  _exit_stack: AsyncExitStack = field(default_factory=AsyncExitStack, init=False)
53
52
  _listen_task: asyncio.Task[None] = field(init=False, repr=False)
54
53
  _task_group: asyncio.TaskGroup = field(init=False, repr=False)
55
- _message_frame_semaphore: asyncio.Semaphore = field(init=False, repr=False)
56
54
 
57
55
  def __post_init__(self) -> None:
58
56
  self._connection_manager = ConnectionManager(
@@ -75,7 +73,6 @@ class Client:
75
73
  check_server_alive_interval_factor=self.check_server_alive_interval_factor,
76
74
  ssl=self.ssl,
77
75
  )
78
- self._message_frame_semaphore = asyncio.Semaphore(self.max_concurrent_consumed_messages)
79
76
 
80
77
  async def __aenter__(self) -> Self:
81
78
  self._task_group = await self._exit_stack.enter_async_context(asyncio.TaskGroup())
@@ -99,17 +96,16 @@ class Client:
99
96
  async for frame in self._connection_manager.read_frames_reconnecting():
100
97
  match frame:
101
98
  case MessageFrame():
102
- if not (subscription := self._active_subscriptions.get_by_id(frame.headers["subscription"])):
103
- continue
104
- await self._message_frame_semaphore.acquire()
105
- created_task = task_group.create_task(
106
- subscription._run_handler(frame=frame) # noqa: SLF001
107
- if isinstance(subscription, AutoAckSubscription)
108
- else subscription.handler(
109
- AckableMessageFrame(headers=frame.headers, body=frame.body, _subscription=subscription)
99
+ if subscription := self._active_subscriptions.get_by_id(frame.headers["subscription"]):
100
+ task_group.create_task(
101
+ subscription._run_handler(frame=frame) # noqa: SLF001
102
+ if isinstance(subscription, AutoAckSubscription)
103
+ else subscription.handler(
104
+ AckableMessageFrame(
105
+ headers=frame.headers, body=frame.body, _subscription=subscription
106
+ )
107
+ )
110
108
  )
111
- )
112
- created_task.add_done_callback(lambda _: self._message_frame_semaphore.release())
113
109
  case ErrorFrame():
114
110
  if self.on_error_frame:
115
111
  self.on_error_frame(frame)
@@ -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
@@ -54,21 +55,18 @@ class ConnectionManager:
54
55
  _reconnect_lock: asyncio.Lock = field(init=False, default_factory=asyncio.Lock)
55
56
  _task_group: asyncio.TaskGroup = field(init=False, default_factory=asyncio.TaskGroup)
56
57
  _send_heartbeat_task: asyncio.Task[None] = field(init=False, repr=False)
57
- _check_server_heartbeat_task: asyncio.Task[None] = field(init=False, repr=False)
58
58
 
59
59
  async def __aenter__(self) -> Self:
60
60
  await self._task_group.__aenter__()
61
61
  self._send_heartbeat_task = self._task_group.create_task(asyncio.sleep(0))
62
- self._check_server_heartbeat_task = self._task_group.create_task(asyncio.sleep(0))
63
- self._active_connection_state = await self._get_active_connection_state()
62
+ self._active_connection_state = await self._get_active_connection_state(is_initial_call=True)
64
63
  return self
65
64
 
66
65
  async def __aexit__(
67
66
  self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None
68
67
  ) -> None:
69
68
  self._send_heartbeat_task.cancel()
70
- self._check_server_heartbeat_task.cancel()
71
- await asyncio.wait([self._send_heartbeat_task, self._check_server_heartbeat_task])
69
+ await asyncio.wait([self._send_heartbeat_task])
72
70
  await self._task_group.__aexit__(exc_type, exc_value, traceback)
73
71
 
74
72
  if not self._active_connection_state:
@@ -79,15 +77,11 @@ class ConnectionManager:
79
77
  return
80
78
  await self._active_connection_state.connection.close()
81
79
 
82
- def _restart_heartbeat_tasks(self, server_heartbeat: Heartbeat) -> None:
80
+ def _restart_heartbeat_task(self, server_heartbeat: Heartbeat) -> None:
83
81
  self._send_heartbeat_task.cancel()
84
- self._check_server_heartbeat_task.cancel()
85
82
  self._send_heartbeat_task = self._task_group.create_task(
86
83
  self._send_heartbeats_forever(server_heartbeat.want_to_receive_interval_ms)
87
84
  )
88
- self._check_server_heartbeat_task = self._task_group.create_task(
89
- self._check_server_heartbeat_forever(server_heartbeat.will_send_interval_ms)
90
- )
91
85
 
92
86
  async def _send_heartbeats_forever(self, send_heartbeat_interval_ms: int) -> None:
93
87
  send_heartbeat_interval_seconds = send_heartbeat_interval_ms / 1000
@@ -95,15 +89,6 @@ class ConnectionManager:
95
89
  await self.write_heartbeat_reconnecting()
96
90
  await asyncio.sleep(send_heartbeat_interval_seconds)
97
91
 
98
- async def _check_server_heartbeat_forever(self, receive_heartbeat_interval_ms: int) -> None:
99
- receive_heartbeat_interval_seconds = receive_heartbeat_interval_ms / 1000
100
- while True:
101
- await asyncio.sleep(receive_heartbeat_interval_seconds * self.check_server_alive_interval_factor)
102
- if not self._active_connection_state:
103
- continue
104
- if not self._active_connection_state.is_alive(self.check_server_alive_interval_factor):
105
- self._active_connection_state = None
106
-
107
92
  async def _create_connection_to_one_server(
108
93
  self, server: ConnectionParameters
109
94
  ) -> tuple[AbstractConnection, ConnectionParameters] | None:
@@ -134,13 +119,13 @@ class ConnectionManager:
134
119
  lifespan = self.lifespan_factory(
135
120
  connection=connection,
136
121
  connection_parameters=connection_parameters,
137
- set_heartbeat_interval=self._restart_heartbeat_tasks,
122
+ set_heartbeat_interval=self._restart_heartbeat_task,
138
123
  )
139
124
 
140
125
  try:
141
126
  connection_result = await lifespan.enter()
142
127
  except ConnectionLostError:
143
- return ConnectionLost()
128
+ return ConnectionLostOnLifespanEnter()
144
129
 
145
130
  return (
146
131
  ActiveConnectionState(
@@ -150,7 +135,7 @@ class ConnectionManager:
150
135
  else connection_result
151
136
  )
152
137
 
153
- async def _get_active_connection_state(self) -> ActiveConnectionState:
138
+ async def _get_active_connection_state(self, *, is_initial_call: bool = False) -> ActiveConnectionState:
154
139
  if self._active_connection_state:
155
140
  return self._active_connection_state
156
141
 
@@ -165,6 +150,11 @@ class ConnectionManager:
165
150
 
166
151
  if isinstance(connection_result, ActiveConnectionState):
167
152
  self._active_connection_state = connection_result
153
+ if not is_initial_call:
154
+ LOGGER.warning(
155
+ "reconnected after failure connection failure. connection_parameters: %s",
156
+ connection_result.lifespan.connection_parameters,
157
+ )
168
158
  return connection_result
169
159
 
170
160
  connection_issues.append(connection_result)
@@ -173,6 +163,12 @@ class ConnectionManager:
173
163
  raise FailedAllConnectAttemptsError(retry_attempts=self.connect_retry_attempts, issues=connection_issues)
174
164
 
175
165
  def _clear_active_connection_state(self) -> None:
166
+ if not self._active_connection_state:
167
+ return
168
+ LOGGER.warning(
169
+ "connection lost. connection_parameters: %s",
170
+ self._active_connection_state.lifespan.connection_parameters,
171
+ )
176
172
  self._active_connection_state = None
177
173
 
178
174
  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")
@@ -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.get("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
File without changes
File without changes