Skip to content

Commit 4fcb2fc

Browse files
committed
Release ZeroMQ resources during shutdown
1 parent f08a54a commit 4fcb2fc

2 files changed

Lines changed: 112 additions & 3 deletions

File tree

‎taskiq/brokers/zmq_broker.py‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,9 @@ async def startup(self) -> None:
5454
sockets. if current process is worker,
5555
it subscribes, otherwise it becomes publisher.
5656
"""
57+
if self.context.closed:
58+
self.context = Context()
59+
5760
if self.is_worker_process:
5861
self.socket = self.context.socket(zmq.SUB)
5962
self.socket.setsockopt(zmq.SUBSCRIBE, b"")
@@ -68,9 +71,14 @@ async def shutdown(self) -> None:
6871
6972
This function closes actual connections to sockets
7073
"""
71-
if not self.is_worker_process:
72-
self.socket.unbind(self.pub_host)
73-
return await super().shutdown()
74+
try:
75+
if not self.is_worker_process:
76+
# Unbind can start terminating TCP sessions with the current linger.
77+
self.socket.setsockopt(zmq.LINGER, 0)
78+
self.socket.unbind(self.pub_host)
79+
await super().shutdown()
80+
finally:
81+
self.context.destroy(linger=0)
7482

7583
async def kick(self, message: BrokerMessage) -> None:
7684
"""

‎tests/brokers/test_zmq_shutdown.py‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
import asyncio
2+
3+
import pytest
4+
5+
from taskiq.brokers import zmq_broker
6+
from taskiq.events import TaskiqEvents
7+
from taskiq.state import TaskiqState
8+
9+
pytestmark = [
10+
pytest.mark.anyio,
11+
pytest.mark.skipif(zmq_broker.zmq is None, reason="pyzmq is not installed"),
12+
]
13+
14+
15+
@pytest.mark.parametrize("is_worker", [False, True])
16+
@pytest.mark.parametrize("failure_stage", [None, "handler", "backend"])
17+
async def test_shutdown_releases_zmq_resources(
18+
monkeypatch: pytest.MonkeyPatch,
19+
is_worker: bool,
20+
failure_stage: str | None,
21+
) -> None:
22+
broker = zmq_broker.ZeroMQBroker(zmq_pub_host="inproc://taskiq-shutdown-test")
23+
broker.is_worker_process = is_worker
24+
event = TaskiqEvents.WORKER_SHUTDOWN if is_worker else TaskiqEvents.CLIENT_SHUTDOWN
25+
called = []
26+
27+
async def shutdown_handler(state: TaskiqState) -> None:
28+
called.append("handler")
29+
if failure_stage == "handler":
30+
raise RuntimeError("shutdown handler failed")
31+
32+
async def shutdown_backend() -> None:
33+
called.append("backend")
34+
if failure_stage == "backend":
35+
raise RuntimeError("shutdown backend failed")
36+
37+
broker.event_handlers[event].append(shutdown_handler)
38+
monkeypatch.setattr(broker.result_backend, "shutdown", shutdown_backend)
39+
40+
try:
41+
await broker.startup()
42+
assert not broker.socket.closed
43+
assert not broker.context.closed
44+
45+
if failure_stage is None:
46+
await broker.shutdown()
47+
else:
48+
with pytest.raises(RuntimeError, match=f"shutdown {failure_stage} failed"):
49+
await broker.shutdown()
50+
51+
assert called == (
52+
["handler"] if failure_stage == "handler" else ["handler", "backend"]
53+
)
54+
assert broker.socket.closed
55+
assert broker.context.closed
56+
finally:
57+
broker.context.destroy(linger=0)
58+
59+
60+
@pytest.mark.parametrize("is_worker", [False, True])
61+
async def test_zmq_broker_can_restart(is_worker: bool) -> None:
62+
broker = zmq_broker.ZeroMQBroker(zmq_pub_host="inproc://taskiq-restart-test")
63+
broker.is_worker_process = is_worker
64+
65+
try:
66+
for _ in range(2):
67+
await broker.startup()
68+
assert not broker.socket.closed
69+
assert not broker.context.closed
70+
await broker.shutdown()
71+
assert broker.socket.closed
72+
assert broker.context.closed
73+
finally:
74+
broker.context.destroy(linger=0)
75+
76+
77+
async def test_shutdown_closes_suspended_listener() -> None:
78+
broker = zmq_broker.ZeroMQBroker(
79+
zmq_sub_host="inproc://taskiq-listener-shutdown-test",
80+
)
81+
broker.is_worker_process = True
82+
await broker.startup()
83+
listener = broker.listen()
84+
pending = asyncio.create_task(anext(listener))
85+
86+
try:
87+
await asyncio.sleep(0)
88+
assert not pending.done()
89+
90+
await broker.shutdown()
91+
92+
with pytest.raises(asyncio.CancelledError):
93+
await pending
94+
await listener.aclose()
95+
assert broker.socket.closed
96+
assert broker.context.closed
97+
finally:
98+
pending.cancel()
99+
await asyncio.gather(pending, return_exceptions=True)
100+
await listener.aclose()
101+
broker.context.destroy(linger=0)

0 commit comments

Comments
 (0)