Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

queue: Fix Tornado resending buffered publishes on every reconnect.

Alex Vandiver9ebfa95c7c2e
diff --git a/zerver/lib/queue.py b/zerver/lib/queue.py
index 7af8c095307..89474175c42 100644
--- a/zerver/lib/queue.py
+++ b/zerver/lib/queue.py
@@ -274,7 +274,7 @@ class TornadoQueueClient(QueueClient[Channel]):
# the server, rather than an unbounded number.
prefetch=100,
)
- self._on_open_cbs: list[Callable[[Channel], None]] = []
+ self._pending_publishes: dict[str, list[bytes]] = defaultdict(list)
self._connection_failure_count = 0
@override
@@ -361,8 +361,8 @@ class TornadoQueueClient(QueueClient[Channel]):
self.channel = channel
self.channel.add_on_close_callback(self._on_channel_closed)
self.channel.basic_qos(prefetch_count=self.prefetch)
- for callback in self._on_open_cbs:
- callback(channel)
+ for queue_name in list(self._pending_publishes):
+ self._declare_queue_for_pending_publishes(queue_name)
self._reconnect_consumer_callbacks()
self.log.info("TornadoQueueClient connected")
@@ -378,19 +378,38 @@ class TornadoQueueClient(QueueClient[Channel]):
self.queues.add(queue_name)
callback(self.channel)
+ assert self.channel is not None
if queue_name not in self.queues:
- # If we're not connected yet, send this message
- # once we have created the channel
- if not self.ready():
- self._on_open_cbs.append(lambda channel: self.ensure_queue(queue_name, callback))
- return
-
- assert self.channel is not None
self.channel.queue_declare(queue=queue_name, durable=True, callback=finish)
else:
- assert self.channel is not None
callback(self.channel)
+ @override
+ def publish(self, queue_name: str, body: bytes) -> None:
+ if queue_name in self.queues:
+ super().publish(queue_name, body)
+ return
+
+ # Hold the message until the queue has been declared on the
+ # current channel, which may be waiting for a reconnect.
+ pending = self._pending_publishes[queue_name]
+ pending.append(body)
+ if len(pending) == 1 and self.ready():
+ self._declare_queue_for_pending_publishes(queue_name)
+
+ def _declare_queue_for_pending_publishes(self, queue_name: str) -> None:
+ assert self.channel is not None
+ self.channel.queue_declare(
+ queue=queue_name,
+ durable=True,
+ callback=lambda frame: self._send_pending_publishes(queue_name),
+ )
+
+ def _send_pending_publishes(self, queue_name: str) -> None:
+ self.queues.add(queue_name)
+ for body in self._pending_publishes.pop(queue_name):
+ super().publish(queue_name, body)
+
def start_json_consumer(
self,
queue_name: str,
diff --git a/zerver/tests/test_queue.py b/zerver/tests/test_queue.py
index 4478cb863cf..2afad3e99be 100644
--- a/zerver/tests/test_queue.py
+++ b/zerver/tests/test_queue.py
@@ -82,6 +82,84 @@ class TestTornadoQueueClient(ZulipTestCase):
],
)
+ @mock.patch("zerver.lib.queue.ioloop.IOLoop.current")
+ @mock.patch("zerver.lib.queue.ExceptionFreeTornadoConnection", autospec=True)
+ def test_publish_while_disconnected(
+ self, mock_cxn: mock.MagicMock, mock_ioloop: mock.MagicMock
+ ) -> None:
+ def open_channel(connection: TornadoQueueClient) -> mock.MagicMock:
+ channel = mock.MagicMock()
+ connection._on_channel_open(channel)
+ return channel
+
+ def declares(channel: mock.MagicMock) -> list[str]:
+ return [call.kwargs["queue"] for call in channel.queue_declare.call_args_list]
+
+ def declare_ok(channel: mock.MagicMock, queue_name: str) -> None:
+ [declare_callback] = [
+ call.kwargs["callback"]
+ for call in channel.queue_declare.call_args_list
+ if call.kwargs["queue"] == queue_name
+ ]
+ declare_callback(None)
+
+ def published(channel: mock.MagicMock) -> list[tuple[str, dict[str, str]]]:
+ return [
+ (call.kwargs["routing_key"], orjson.loads(call.kwargs["body"]))
+ for call in channel.basic_publish.call_args_list
+ ]
+
+ def reconnect(connection: TornadoQueueClient) -> mock.MagicMock:
+ connection._on_connection_closed(mock.MagicMock(), ConnectionClosed(320, "test"))
+ connection._reconnect()
+ return open_channel(connection)
+
+ with self.assertLogs("zulip.queue", "WARNING") as m:
+ connection = TornadoQueueClient()
+ connection.json_publish("test_suite", {"event": "first"})
+ connection.json_publish("test_suite", {"event": "second"})
+
+ # The connection is lost before the queue is declared, so
+ # nothing is published on this channel.
+ channel = open_channel(connection)
+ self.assertEqual(declares(channel), ["test_suite"])
+ channel = reconnect(connection)
+ self.assertEqual(declares(channel), ["test_suite"])
+
+ # Publishing to a new queue while connected declares it
+ # once, even if more publishes arrive before that completes.
+ connection.json_publish("other_queue", {"event": "other"})
+ connection.json_publish("other_queue", {"event": "another"})
+ self.assertEqual(declares(channel), ["test_suite", "other_queue"])
+ channel.basic_publish.assert_not_called()
+
+ declare_ok(channel, "test_suite")
+ declare_ok(channel, "other_queue")
+ connection.json_publish("test_suite", {"event": "third"})
+ self.assertEqual(declares(channel), ["test_suite", "other_queue"])
+ self.assertEqual(
+ published(channel),
+ [
+ ("test_suite", {"event": "first"}),
+ ("test_suite", {"event": "second"}),
+ ("other_queue", {"event": "other"}),
+ ("other_queue", {"event": "another"}),
+ ("test_suite", {"event": "third"}),
+ ],
+ )
+
+ channel = reconnect(connection)
+ channel.queue_declare.assert_not_called()
+ channel.basic_publish.assert_not_called()
+ self.assertEqual(
+ m.output,
+ [
+ "WARNING:zulip.queue:TornadoQueueClient lost connection to RabbitMQ, reconnecting in 2 secs...",
+ "WARNING:zulip.queue:TornadoQueueClient attempting to reconnect to RabbitMQ",
+ ]
+ * 2,
+ )
+
class TestQueueImplementation(ZulipTestCase):
@override_settings(USING_RABBITMQ=True)