rabbitpy 3.0.2__tar.gz → 4.0.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.
Files changed (73) hide show
  1. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/PKG-INFO +2 -2
  2. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/docs/history.md +12 -0
  3. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/pyproject.toml +1 -1
  4. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/rabbitpy/__init__.py +1 -1
  5. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/rabbitpy/amqp_queue.py +2 -2
  6. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/rabbitpy/base.py +26 -81
  7. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/rabbitpy/channel.py +9 -4
  8. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/rabbitpy/channel0.py +15 -1
  9. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/rabbitpy/connection.py +96 -59
  10. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/rabbitpy/events.py +0 -6
  11. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/rabbitpy/io.py +24 -0
  12. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/rabbitpy/state.py +9 -1
  13. rabbitpy-4.0.0/tests/integration/test_lifecycle.py +212 -0
  14. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/test_channel.py +36 -0
  15. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/test_channel0.py +38 -0
  16. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/test_connection.py +98 -21
  17. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/test_integration.py +16 -14
  18. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/test_io.py +29 -0
  19. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/test_queue.py +4 -4
  20. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/uv.lock +30 -30
  21. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/.checkignore +0 -0
  22. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/.codeclimate.yml +0 -0
  23. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/.github/workflows/deploy.yaml +0 -0
  24. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/.github/workflows/docs.yaml +0 -0
  25. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/.github/workflows/testing.yaml +0 -0
  26. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/.gitignore +0 -0
  27. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/.pre-commit-config.yaml +0 -0
  28. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/CLAUDE.md +0 -0
  29. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/LICENSE +0 -0
  30. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/README.md +0 -0
  31. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/bootstrap +0 -0
  32. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/compose.yml +0 -0
  33. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/docs/api/connection.md +0 -0
  34. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/docs/api/exceptions.md +0 -0
  35. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/docs/examples/consumer.md +0 -0
  36. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/docs/examples/getter.md +0 -0
  37. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/docs/examples/publisher.md +0 -0
  38. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/docs/index.md +0 -0
  39. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/docs/threads.md +0 -0
  40. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/examples/consumer.py +0 -0
  41. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/examples/getter.py +0 -0
  42. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/examples/publisher.py +0 -0
  43. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/examples/transactional_publisher.py +0 -0
  44. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/mkdocs.yml +0 -0
  45. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/rabbitpy/amqp.py +0 -0
  46. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/rabbitpy/exceptions.py +0 -0
  47. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/rabbitpy/exchange.py +0 -0
  48. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/rabbitpy/heartbeat.py +0 -0
  49. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/rabbitpy/message.py +0 -0
  50. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/rabbitpy/py.typed +0 -0
  51. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/rabbitpy/simple.py +0 -0
  52. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/rabbitpy/tx.py +0 -0
  53. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/rabbitpy/url_parser.py +0 -0
  54. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/rabbitpy/utils.py +0 -0
  55. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/__init__.py +0 -0
  56. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/data/ca.crt +0 -0
  57. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/data/client.crt +0 -0
  58. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/data/client.key +0 -0
  59. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/data/server.crt +0 -0
  60. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/data/server.key +0 -0
  61. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/helpers.py +0 -0
  62. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/integration/__init__.py +0 -0
  63. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/integration/test_connection.py +0 -0
  64. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/mixins.py +0 -0
  65. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/test_amqp.py +0 -0
  66. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/test_base.py +0 -0
  67. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/test_events.py +0 -0
  68. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/test_exchange.py +0 -0
  69. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/test_heartbeat.py +0 -0
  70. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/test_message.py +0 -0
  71. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/test_tx.py +0 -0
  72. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/test_url_parser.py +0 -0
  73. {rabbitpy-3.0.2 → rabbitpy-4.0.0}/tests/test_utils.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: rabbitpy
3
- Version: 3.0.2
3
+ Version: 4.0.0
4
4
  Summary: A pure python, thread-safe, minimalistic and pythonic RabbitMQ client library
5
5
  Project-URL: Homepage, https://github.com/gmr/rabbitpy
6
6
  Project-URL: Documentation, https://rabbitpy.readthedocs.io
@@ -1,5 +1,17 @@
1
1
  # Version History
2
2
 
3
+ ## 4.0.0 — *2026-12-04*
4
+
5
+ - **Breaking:** `Queue` now defaults to `durable=True`. RabbitMQ 4.3 rejects transient non-exclusive queues. Pass `durable=False` with `exclusive=True` for a transient queue. (#164)
6
+ - Fixed hangs when a channel or the connection closes unexpectedly (#168):
7
+ - A channel that RabbitMQ closed now raises `ChannelClosedException` on the next call
8
+ - An exception in a `with connection.channel()` block now closes the channel on the server, so the next channel does not fail with `504 CHANNEL_ERROR`
9
+ - When the socket drops or RabbitMQ closes the connection, waiting consumers now raise and `Connection.closed` is `True`
10
+ - A reconnect now waits for the AMQP handshake
11
+ - `Connection.close()` now always stops the IO and heartbeat threads and waits for `Connection.CloseOk`
12
+ - Waiting calls now raise `ConnectionClosed` when the connection is closed, and do not return `None` (#168)
13
+ - Fixed integration tests for RabbitMQ 4.3 (#163)
14
+
3
15
  ## 3.0.0 — *2024-05-08*
4
16
 
5
17
  - Change to use `ssl.SSLContext` since `ssl.wrap_socket` was deprecated in Python 3.7 and removed in 3.12
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "rabbitpy"
7
- version = "3.0.2"
7
+ version = "4.0.0"
8
8
  description = "A pure python, thread-safe, minimalistic and pythonic RabbitMQ client library"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -3,7 +3,7 @@ rabbitpy, a pythonic RabbitMQ client
3
3
 
4
4
  """
5
5
 
6
- __version__ = '3.0.2'
6
+ __version__ = '4.0.0'
7
7
 
8
8
  import logging
9
9
 
@@ -72,7 +72,7 @@ class Queue(base.AMQPClass):
72
72
  auto_delete = False
73
73
  dead_letter_exchange = None
74
74
  dead_letter_routing_key = None
75
- durable = False
75
+ durable = True
76
76
  exclusive = False
77
77
  expires = None
78
78
  max_length = None
@@ -83,7 +83,7 @@ class Queue(base.AMQPClass):
83
83
  self,
84
84
  channel: chan.Channel,
85
85
  name: str = '',
86
- durable: bool = False,
86
+ durable: bool = True,
87
87
  exclusive: bool = False,
88
88
  auto_delete: bool = False,
89
89
  max_length: int | None = None,
@@ -13,7 +13,7 @@ import typing
13
13
 
14
14
  from pamqp import base, body, commands, header, heartbeat
15
15
 
16
- from rabbitpy import exceptions, utils
16
+ from rabbitpy import exceptions, state, utils
17
17
 
18
18
  if typing.TYPE_CHECKING:
19
19
  from rabbitpy import channel as chan
@@ -92,73 +92,7 @@ class AMQPClass(ChannelWriter): # pylint: disable=too-few-public-methods
92
92
  self.name = name
93
93
 
94
94
 
95
- class StatefulObject(utils.DebuggingOptimizationMixin):
96
- """Base object for rabbitpy classes that need to maintain state such as
97
- connection and channel.
98
-
99
- """
100
-
101
- CLOSED = 0
102
- CLOSING = 1
103
- OPEN = 2
104
- OPENING = 3
105
-
106
- STATES = {0: 'Closed', 1: 'Closing', 2: 'Open', 3: 'Opening'}
107
-
108
- def __init__(self):
109
- """Create a new instance of the object defaulting to a closed state."""
110
- super().__init__()
111
- self._state: int = self.CLOSED
112
-
113
- def _set_state(self, value: int) -> None:
114
- """Set the state to the specified value, validating it is a supported
115
- state value.
116
-
117
- :param value: The new state value
118
-
119
- """
120
- if value not in self.STATES.keys():
121
- raise ValueError(f'Invalid state value: {value!r}')
122
- if self._is_debugging:
123
- LOGGER.debug(
124
- '%s setting state to %r',
125
- self.__class__.__name__,
126
- self.STATES[value],
127
- )
128
- self._state = value
129
-
130
- @property
131
- def closed(self) -> bool:
132
- """Returns True if in the CLOSED runtime state"""
133
- return self._state == self.CLOSED
134
-
135
- @property
136
- def closing(self) -> bool:
137
- """Returns True if in the CLOSING runtime state"""
138
- return self._state == self.CLOSING
139
-
140
- @property
141
- def open(self) -> bool:
142
- """Returns True if in the OPEN runtime state"""
143
- return self._state == self.OPEN
144
-
145
- @property
146
- def opening(self) -> bool:
147
- """Returns True if in the OPENING runtime state"""
148
- return self._state == self.OPENING
149
-
150
- @property
151
- def state(self) -> int:
152
- """Return the runtime state value"""
153
- return self._state
154
-
155
- @property
156
- def state_description(self) -> str:
157
- """Returns the text based description of the runtime state"""
158
- return self.STATES[self._state]
159
-
160
-
161
- class AMQPChannel(StatefulObject):
95
+ class AMQPChannel(state.StatefulBase, utils.DebuggingOptimizationMixin):
162
96
  """Base AMQP Channel Object"""
163
97
 
164
98
  CLOSE_REQUEST_FRAME = commands.Channel.Close
@@ -166,6 +100,11 @@ class AMQPChannel(StatefulObject):
166
100
  DEFAULT_CLOSE_REASON = 'Normal Shutdown'
167
101
  REMOTE_CLOSED = 0x04
168
102
 
103
+ STATES: typing.ClassVar[dict[int, str]] = {
104
+ **state.StatefulBase.STATES,
105
+ REMOTE_CLOSED: 'Remotely Closed',
106
+ }
107
+
169
108
  def __init__(
170
109
  self,
171
110
  exception_queue: queue.Queue,
@@ -191,6 +130,11 @@ class AMQPChannel(StatefulObject):
191
130
  self._write_queue: queue.Queue | None = None
192
131
  self._write_trigger: socket.socket = write_trigger
193
132
 
133
+ @property
134
+ def is_closed(self) -> bool:
135
+ """Returns True if closed by the client or by RabbitMQ"""
136
+ return self._state in (self.CLOSED, self.REMOTE_CLOSED)
137
+
194
138
  def __int__(self) -> int:
195
139
  """Return the numeric channel ID"""
196
140
  if self._channel_id is None:
@@ -268,9 +212,7 @@ class AMQPChannel(StatefulObject):
268
212
  if self._can_write():
269
213
  if self._is_debugging:
270
214
  LOGGER.debug('Writing frame: %s', value.name)
271
- with self._write_lock:
272
- self._write_queue.put((self._channel_id, value))
273
- self._trigger_write()
215
+ self._enqueue(value)
274
216
 
275
217
  def write_frames(self, frames: list[base.Frame]) -> None:
276
218
  """Add a list of frames for the IOWriter object to write to the socket
@@ -284,10 +226,14 @@ class AMQPChannel(StatefulObject):
284
226
  LOGGER.debug(
285
227
  'Writing frames: %r', [frame.name for frame in frames]
286
228
  )
287
- with self._write_lock:
288
- for frame in frames:
289
- self._write_queue.put((self._channel_id, frame))
290
- self._trigger_write()
229
+ self._enqueue(*frames)
230
+
231
+ def _enqueue(self, *frames: base.Frame | heartbeat.Heartbeat) -> None:
232
+ """Put the frames in the write queue without the state checks."""
233
+ with self._write_lock:
234
+ for frame in frames:
235
+ self._write_queue.put((self._channel_id, frame))
236
+ self._trigger_write()
291
237
 
292
238
  def _build_close_frame(self) -> commands.Channel.Close:
293
239
  """Return the proper close frame for this object."""
@@ -330,12 +276,6 @@ class AMQPChannel(StatefulObject):
330
276
  LOGGER.debug('Channel closed')
331
277
  self._on_remote_close(value)
332
278
 
333
- def _force_close(self) -> None:
334
- """Force the channel to mark itself as closed"""
335
- self._set_state(self.CLOSED)
336
- if self._is_debugging:
337
- LOGGER.debug('Channel #%i closed', self._channel_id)
338
-
339
279
  def _interrupt_wait_on_frame(
340
280
  self, callback: typing.Callable, *args
341
281
  ) -> None:
@@ -377,6 +317,9 @@ class AMQPChannel(StatefulObject):
377
317
  :raises: exceptions.AMQPException
378
318
 
379
319
  """
320
+ # Reply with Channel.CloseOk so RabbitMQ frees the channel ID. Skip
321
+ # the write_frame checks: they raise once the channel is closing.
322
+ self._enqueue(commands.Channel.CloseOk())
380
323
  self._set_state(self.REMOTE_CLOSED)
381
324
  if value.reply_code in exceptions.AMQP:
382
325
  LOGGER.error(
@@ -496,3 +439,5 @@ class AMQPChannel(StatefulObject):
496
439
  # Clear here to ensure out of processing loop before proceeding
497
440
  if self._interrupt_is_set:
498
441
  self._on_interrupt_set()
442
+ elif self._connection.closed:
443
+ raise exceptions.ConnectionClosed()
@@ -71,9 +71,6 @@ class Channel(base.AMQPChannel):
71
71
 
72
72
  """
73
73
 
74
- STATES = base.AMQPChannel.STATES
75
- STATES[0x04] = 'Remotely Closed'
76
-
77
74
  def __init__(
78
75
  self,
79
76
  channel_id: int,
@@ -120,7 +117,15 @@ class Channel(base.AMQPChannel):
120
117
  """
121
118
  if exc_type and exc_val:
122
119
  LOGGER.debug('Exiting due to exception: %r', exc_val)
123
- self._set_state(self.CLOSED)
120
+ # Close on the server too, or RabbitMQ keeps the channel open
121
+ # and rejects the next Channel.Open for this ID (504).
122
+ if self.open and not self._connection.closed:
123
+ try:
124
+ self.close()
125
+ except Exception as error: # noqa: BLE001
126
+ LOGGER.debug('Error closing channel: %r', error)
127
+ if not self.closed: # Keep REMOTE_CLOSED if it is set
128
+ self._set_state(self.CLOSED)
124
129
  raise exc_val
125
130
  if self.open:
126
131
  self.close()
@@ -89,8 +89,13 @@ class Channel0(threading.Thread):
89
89
  return self._properties
90
90
 
91
91
  def close(self) -> None:
92
- """Send Connection.Close if the connection is currently open."""
92
+ """Send Connection.Close if the connection is currently open, then
93
+ wait for Connection.CloseOk so that the frame is sent before the
94
+ socket is closed.
95
+
96
+ """
93
97
  if self._open and self._io is not None:
98
+ self._events.set(ev_module.CHANNEL0_CLOSE)
94
99
  try:
95
100
  self._io.write_frame(
96
101
  0,
@@ -103,6 +108,10 @@ class Channel0(threading.Thread):
103
108
  )
104
109
  except OSError as exc:
105
110
  LOGGER.debug('Error sending Connection.Close: %r', exc)
111
+ if not self._events.wait(
112
+ ev_module.CHANNEL0_CLOSED, self._args['timeout']
113
+ ):
114
+ LOGGER.debug('Timeout waiting for Connection.CloseOk')
106
115
  self._open = False
107
116
 
108
117
  def send_heartbeat(self) -> None:
@@ -189,6 +198,7 @@ class Channel0(threading.Thread):
189
198
  if frame is None:
190
199
  break
191
200
  self._handle_runtime_frame(frame)
201
+ self._events.set(ev_module.CHANNEL0_CLOSED)
192
202
 
193
203
  def _handle_runtime_frame(self, frame: pamqp.frame.FrameTypes) -> None:
194
204
  """Dispatch a channel-0 frame received after connection is open."""
@@ -198,6 +208,8 @@ class Channel0(threading.Thread):
198
208
  elif isinstance(frame, commands.Connection.Unblocked):
199
209
  LOGGER.info('Connection is unblocked')
200
210
  self._events.clear(ev_module.CONNECTION_BLOCKED)
211
+ elif isinstance(frame, commands.Connection.CloseOk):
212
+ self._open = False
201
213
  elif isinstance(frame, commands.Connection.Close):
202
214
  LOGGER.error(
203
215
  'Server closed the connection (%s): %s',
@@ -210,6 +222,8 @@ class Channel0(threading.Thread):
210
222
  )
211
223
  self._exceptions.put(exc_cls(frame.reply_code, frame.reply_text))
212
224
  self._events.set(ev_module.EXCEPTION_RAISED)
225
+ # RabbitMQ closes the socket after it receives CloseOk
226
+ self._io.write_frame(0, commands.Connection.CloseOk())
213
227
 
214
228
  def _raise_if_server_close(self, frame: pamqp.frame.FrameTypes) -> None:
215
229
  """Raise the appropriate exception if the server sent Connection.Close.
@@ -129,16 +129,14 @@ class Connection(state.StatefulBase):
129
129
  ) -> bool | None:
130
130
  """Close the connection when the context exits"""
131
131
  if exc_type and exc_val:
132
- self._stop_io()
133
- self._set_state(self.CLOSED)
132
+ self._abort()
134
133
  return False # Re-raise the original exception
135
134
  try:
136
135
  exc = self._exceptions.get_nowait()
137
136
  except queue.Empty:
138
137
  pass
139
138
  else:
140
- self._stop_io()
141
- self._set_state(self.CLOSED)
139
+ self._abort()
142
140
  raise exc
143
141
  self.close()
144
142
  return None
@@ -215,31 +213,40 @@ class Connection(state.StatefulBase):
215
213
 
216
214
  def close(self) -> None:
217
215
  """Close the connection to RabbitMQ, including all open channels."""
218
- self._set_state(self.CLOSING)
219
- self._close_channels()
220
- if self._heartbeat is not None:
221
- self._heartbeat.stop()
222
- self._heartbeat = None
223
- if self._channel0 is not None:
224
- self._channel0.close()
225
- self._events.clear(events.CONNECTION_EVENT)
226
- self._events.clear(events.SOCKET_CLOSE)
227
- self._events.clear(events.SOCKET_CLOSED)
228
- self._events.clear(events.SOCKET_OPENED)
229
- self._stop_io()
230
- self._set_state(self.CLOSED)
216
+ try:
217
+ if not self.is_closed:
218
+ self._set_state(self.CLOSING)
219
+ self._close_channels()
220
+ if self._channel0 is not None:
221
+ self._channel0.close()
222
+ finally:
223
+ self._abort()
231
224
 
232
225
  def connect(self) -> None:
233
226
  """Connect to RabbitMQ and negotiate the AMQP connection."""
234
227
  self._set_state(self.OPENING)
235
228
 
229
+ # New objects for each connect, so that no event or exception from
230
+ # an earlier connection is seen as current (a stale CHANNEL0_OPENED
231
+ # skips the wait for the AMQP handshake).
232
+ self._events = events.Events()
233
+ self._exceptions = queue.Queue()
234
+
235
+ # Channels from an earlier connection use its queues and write
236
+ # trigger. Mark them closed and remove them, so that close() does
237
+ # not wait for their responses.
238
+ for ch in self._channels.values():
239
+ ch._set_state(ch.CLOSED)
240
+ self._channels = {}
241
+ self._freed_channel_ids = set()
242
+
236
243
  self._channel0 = channel0.Channel0(
237
244
  args=self._args,
238
245
  events=self._events,
239
246
  exceptions_queue=self._exceptions,
240
247
  )
241
248
 
242
- self._io = io.IO(
249
+ new_io = io.IO(
243
250
  self._args['host'],
244
251
  self._args['port'],
245
252
  self._args['ssl'],
@@ -247,48 +254,19 @@ class Connection(state.StatefulBase):
247
254
  self._events,
248
255
  self._exceptions,
249
256
  self._args['timeout'],
257
+ on_close=lambda: self._on_io_closed(new_io),
250
258
  )
259
+ self._io = new_io
251
260
  self._io.add_channel(0, self._channel0.pending_frames)
252
- self._io.start()
253
-
254
- # Wait for the TCP socket to open
255
- socket_opened = events.SOCKET_OPENED
256
- while self.is_opening and not self._events.is_set(socket_opened):
257
- if not self._exceptions.empty():
258
- exception = self._exceptions.get()
259
- raise exception
260
-
261
- self._events.wait(socket_opened, self._args['timeout'])
262
- if not self._events.is_set(socket_opened):
263
- raise RuntimeError('Timeout waiting for opening the socket')
264
-
265
- # If the socket could not be opened, clean up and return
266
- if self.is_closed:
267
- return self.close()
268
-
269
- # Start AMQP channel-0 negotiation in its own thread
270
- self._channel0.start(self._io)
271
-
272
- # Wait for the AMQP handshake to complete (#133, #124: proper timeout
273
- # prevents indefinite hang when the server comes up mid-retry or
274
- # returns an error such as an invalid vhost)
275
- negotiation_timeout = max(self._args['timeout'] * 5, 15)
276
- deadline = time.monotonic() + negotiation_timeout
277
- while time.monotonic() < deadline:
278
- if self._events.is_set(events.CHANNEL0_OPENED):
279
- break
280
- if not self._exceptions.empty():
281
- exception = self._exceptions.get()
282
- self._stop_io()
283
- self._set_state(self.CLOSED)
284
- raise exception
285
- time.sleep(0.01)
286
- else:
287
- self._stop_io()
288
- self._set_state(self.CLOSED)
289
- raise RuntimeError(
290
- 'Timeout waiting for AMQP connection negotiation'
291
- )
261
+ try:
262
+ self._io.start()
263
+ self._wait_for_socket()
264
+ # Start AMQP channel-0 negotiation in its own thread
265
+ self._channel0.start(self._io)
266
+ self._wait_for_handshake()
267
+ except BaseException:
268
+ self._abort()
269
+ raise
292
270
 
293
271
  # Start the heartbeat keeper if the server requires it
294
272
  if self._channel0.heartbeat_interval:
@@ -305,15 +283,50 @@ class Connection(state.StatefulBase):
305
283
  # Private helpers
306
284
  # -------------------------------------------------------------------------
307
285
 
286
+ def _abort(self) -> None:
287
+ """Stop the heartbeat and IO threads and mark the connection closed,
288
+ without the AMQP close handshake.
289
+
290
+ """
291
+ self._stop_heartbeat()
292
+ self._stop_io()
293
+ self._set_state(self.CLOSED)
294
+
308
295
  def _close_channels(self) -> None:
309
296
  """Close all open channels."""
310
297
  for ch in list(self._channels.values()):
311
298
  if not ch.closed:
312
299
  try:
313
300
  ch.close()
314
- except OSError as exc:
301
+ except (OSError, exceptions.RabbitpyException) as exc:
315
302
  LOGGER.debug('Error closing channel: %r', exc)
316
303
 
304
+ def _wait_for_socket(self) -> None:
305
+ """Wait for the TCP socket to open."""
306
+ socket_opened = events.SOCKET_OPENED
307
+ while self.is_opening and not self._events.is_set(socket_opened):
308
+ if not self._exceptions.empty():
309
+ raise self._exceptions.get()
310
+ self._events.wait(socket_opened, self._args['timeout'])
311
+ if not self._events.is_set(socket_opened):
312
+ raise RuntimeError('Timeout waiting for opening the socket')
313
+
314
+ def _wait_for_handshake(self) -> None:
315
+ """Wait for the AMQP handshake to complete (#133, #124: proper timeout
316
+ prevents indefinite hang when the server comes up mid-retry or
317
+ returns an error such as an invalid vhost).
318
+
319
+ """
320
+ negotiation_timeout = max(self._args['timeout'] * 5, 15)
321
+ deadline = time.monotonic() + negotiation_timeout
322
+ while time.monotonic() < deadline:
323
+ if self._events.is_set(events.CHANNEL0_OPENED):
324
+ return
325
+ if not self._exceptions.empty():
326
+ raise self._exceptions.get()
327
+ time.sleep(0.01)
328
+ raise RuntimeError('Timeout waiting for AMQP connection negotiation')
329
+
317
330
  def _get_next_channel_id(self) -> int:
318
331
  """Return the next available channel ID.
319
332
 
@@ -340,6 +353,30 @@ class Connection(state.StatefulBase):
340
353
  raise exceptions.TooManyChannelsError
341
354
  return next_id
342
355
 
356
+ def _on_io_closed(self, io_obj: io.IO) -> None:
357
+ """Invoked by the IO thread when the socket is closed.
358
+
359
+ A socket that closes while the connection is open means that the
360
+ connection is lost. Mark it as closed so that channels waiting for a
361
+ frame stop waiting. While opening, connect() handles the failure.
362
+ Ignore a close from an IO object of an earlier connect() attempt.
363
+
364
+ """
365
+ if io_obj is not self._io:
366
+ LOGGER.debug('Ignoring close from a previous IO object')
367
+ return
368
+ if self.is_open or self.is_closing:
369
+ LOGGER.debug('Socket closed, marking the connection as closed')
370
+ self._stop_heartbeat()
371
+ self._set_state(self.CLOSED)
372
+
373
+ def _stop_heartbeat(self) -> None:
374
+ """Stop the heartbeat timer, if it is running."""
375
+ heartbeat = self._heartbeat
376
+ self._heartbeat = None
377
+ if heartbeat is not None:
378
+ heartbeat.stop()
379
+
343
380
  def _stop_io(self) -> None:
344
381
  """Signal the IO thread to stop and wait for it to finish.
345
382
 
@@ -12,9 +12,7 @@ CHANNEL0_CLOSE = 0x01
12
12
  CHANNEL0_CLOSED = 0x02
13
13
  CHANNEL0_OPENED = 0x03
14
14
  CONNECTION_BLOCKED = 0x04
15
- CONNECTION_EVENT = 0x05
16
15
  EXCEPTION_RAISED = 0x06
17
- SOCKET_CLOSE = 0x07
18
16
  SOCKET_CLOSED = 0x08
19
17
  SOCKET_OPENED = 0x09
20
18
 
@@ -23,9 +21,7 @@ DESCRIPTIONS = {
23
21
  0x02: 'Channel 0 Closed',
24
22
  0x03: 'Channel 0 Opened',
25
23
  0x04: 'Connection is blocked',
26
- 0x05: 'Connection Event Occurred',
27
24
  0x06: 'Exception Raised',
28
- 0x07: 'Socket Close Requested',
29
25
  0x08: 'Socket Closed',
30
26
  0x09: 'Socket Connected',
31
27
  }
@@ -59,9 +55,7 @@ class Events:
59
55
  CHANNEL0_CLOSED,
60
56
  CHANNEL0_OPENED,
61
57
  CONNECTION_BLOCKED,
62
- CONNECTION_EVENT,
63
58
  EXCEPTION_RAISED,
64
- SOCKET_CLOSE,
65
59
  SOCKET_CLOSED,
66
60
  SOCKET_OPENED,
67
61
  ]:
@@ -9,6 +9,7 @@ import typing
9
9
 
10
10
  import pamqp.base
11
11
  import pamqp.body
12
+ import pamqp.commands
12
13
  import pamqp.exceptions
13
14
  import pamqp.frame
14
15
  import pamqp.header
@@ -18,6 +19,12 @@ import rabbitpy.events
18
19
  import rabbitpy.exceptions
19
20
  from rabbitpy.url_parser import SslOptions
20
21
 
22
+ # Frames after which the socket close is expected, not an error
23
+ _CONNECTION_CLOSE_FRAMES = (
24
+ pamqp.commands.Connection.Close,
25
+ pamqp.commands.Connection.CloseOk,
26
+ )
27
+
21
28
  LOGGER = logging.getLogger(__name__)
22
29
 
23
30
  # Convenience alias: pamqp 4 exposes FrameTypes as the canonical union.
@@ -41,9 +48,11 @@ class IO(threading.Thread):
41
48
  events: rabbitpy.events.Events,
42
49
  exceptions: queue.Queue[Exception],
43
50
  timeout: float = 0.01,
51
+ on_close: typing.Callable[[], None] | None = None,
44
52
  ) -> None:
45
53
  """Initialize the IO thread."""
46
54
  super().__init__(daemon=True, name='IO')
55
+ self._on_close = on_close
47
56
  self._events = events
48
57
  self._exceptions = exceptions
49
58
  self._host = host
@@ -100,6 +109,13 @@ class IO(threading.Thread):
100
109
  pass
101
110
  self._closed.set()
102
111
  self._events.set(rabbitpy.events.SOCKET_CLOSED)
112
+ read_queues = list(self._channels.values())
113
+ if self._on_close is not None:
114
+ self._on_close()
115
+ # Wake every reader that is blocked on its queue, so that it sees
116
+ # the closed connection.
117
+ for read_queue in read_queues:
118
+ read_queue.put(None)
103
119
 
104
120
  def stop(self) -> None:
105
121
  """Signal the I/O loop to stop from outside the IO thread.
@@ -189,6 +205,10 @@ class IO(threading.Thread):
189
205
 
190
206
  def _add_exception(self, exc: Exception) -> None:
191
207
  """Add an exception to the exception queue and signal the event."""
208
+ if self._events.is_set(rabbitpy.events.CHANNEL0_CLOSE):
209
+ # The AMQP connection is closing, so the socket closes next
210
+ LOGGER.debug('Ignoring exception while closing: %r', exc)
211
+ return
192
212
  LOGGER.debug('Adding exception %r', exc)
193
213
  self._exceptions.put(exc)
194
214
  self._events.set(rabbitpy.events.EXCEPTION_RAISED)
@@ -377,6 +397,10 @@ class IO(threading.Thread):
377
397
  self._buffer = remaining
378
398
  self._bytes_read += bytes_read
379
399
  if channel_id is not None:
400
+ if channel_id == 0 and isinstance(
401
+ frame_value, _CONNECTION_CLOSE_FRAMES
402
+ ):
403
+ self._events.set(rabbitpy.events.CHANNEL0_CLOSE)
380
404
  self._channels[channel_id].put(frame_value)
381
405
 
382
406
  def _on_write_ready(self) -> None:
@@ -1,7 +1,10 @@
1
1
  """Common base class for objects that need to maintain state."""
2
2
 
3
+ import logging
3
4
  import typing
4
5
 
6
+ LOGGER = logging.getLogger(__name__)
7
+
5
8
 
6
9
  class StatefulBase:
7
10
  """Base class for classes that need to maintain state such as
@@ -35,6 +38,11 @@ class StatefulBase:
35
38
  """
36
39
  if value not in self.STATES.keys():
37
40
  raise ValueError(f'Invalid state value: {value}')
41
+ LOGGER.debug(
42
+ '%s setting state to %r',
43
+ self.__class__.__name__,
44
+ self.STATES[value],
45
+ )
38
46
  self._state = value
39
47
 
40
48
  @property
@@ -45,7 +53,7 @@ class StatefulBase:
45
53
  @property
46
54
  def closed(self) -> bool:
47
55
  """Alias for is_closed for backward compatibility."""
48
- return self._state == self.CLOSED
56
+ return self.is_closed
49
57
 
50
58
  @property
51
59
  def is_closing(self) -> bool: