acemq_amqp.sync
The same library, for programs that are not running an event loop.
Plenty of Python is not asyncio and has no reason to become asyncio because it sends a message. This is a blocking API for those programs::
with sync.connect("amqp://localhost/") as mq:
mq.publisher(routing_key="orders").send({"id": 7})
It is a facade rather than a second implementation. A loop runs on a thread of
its own and every call here is handed to it, so the envelope rules, the codec
negotiation and the retry engine are the ones in
acemq_amqp.connection — there is one set of retry arithmetic in this
library, and it is not this file's.
Handlers run on a worker thread rather than on the loop. A blocking handler called from the loop would stop every other consumer on the connection, and a blocking handler is exactly what somebody using this API has: that is why they are here.
1# Copyright 2026 AceMQ. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# https://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15"""The same library, for programs that are not running an event loop. 16 17Plenty of Python is not asyncio and has no reason to become asyncio because it 18sends a message. This is a blocking API for those programs:: 19 20 with sync.connect("amqp://localhost/") as mq: 21 mq.publisher(routing_key="orders").send({"id": 7}) 22 23It is a facade rather than a second implementation. A loop runs on a thread of 24its own and every call here is handed to it, so the envelope rules, the codec 25negotiation and the retry engine are the ones in 26:mod:`acemq_amqp.connection` — there is one set of retry arithmetic in this 27library, and it is not this file's. 28 29Handlers run on a worker thread rather than on the loop. A blocking handler 30called from the loop would stop every other consumer on the connection, and a 31blocking handler is exactly what somebody using this API has: that is why they 32are here. 33""" 34 35from __future__ import annotations 36 37import asyncio 38import threading 39from collections.abc import Callable, Coroutine, Iterable, Mapping 40from concurrent.futures import ThreadPoolExecutor 41from datetime import timedelta 42from typing import TYPE_CHECKING, Any, TypeAlias, TypeVar 43 44from .ack import Ack 45from .codec import Codec 46from .connection import ( 47 DEFAULT_CONFIRM_TIMEOUT, 48 DEFAULT_DRAIN_TIMEOUT, 49 DEFAULT_MAX_OUTSTANDING_PUBLISHES, 50 DEFAULT_PREFETCH, 51 Connection, 52 Consumer, 53 Message, 54 Publisher, 55) 56from .connection import connect as _connect_async 57from .envelope import Envelope 58from .retry import RetryPolicy 59from .security import Security 60from .topology import Topology 61from .transport import PublishResult 62 63if TYPE_CHECKING: 64 from .patterns.routingslip import Pipeline 65 66T = TypeVar("T") 67 68#: What a blocking handler is: a message in, a decision out. 69SyncHandler: TypeAlias = Callable[[Message], Ack] 70 71 72class _LoopThread: 73 """An event loop on a thread, and the way to get work onto it. 74 75 One per connection rather than one per process, so two connections cannot 76 starve each other and closing one does not take the other's loop with it. 77 """ 78 79 def __init__(self, name: str) -> None: 80 self._loop = asyncio.new_event_loop() 81 self._ready = threading.Event() 82 self._thread = threading.Thread(target=self._run, name=name, daemon=True) 83 self._thread.start() 84 self._ready.wait() 85 86 def _run(self) -> None: 87 asyncio.set_event_loop(self._loop) 88 self._loop.call_soon(self._ready.set) 89 self._loop.run_forever() 90 91 def run(self, work: Coroutine[Any, Any, T]) -> T: 92 """Runs a coroutine on the loop and waits for its answer here.""" 93 return asyncio.run_coroutine_threadsafe(work, self._loop).result() 94 95 def stop(self) -> None: 96 """Stops the loop and waits for its thread. 97 98 Joined rather than left to the daemon flag, so that a connection closed 99 in a test is really gone by the time the next test starts rather than 100 still holding a socket. 101 """ 102 self._loop.call_soon_threadsafe(self._loop.stop) 103 self._thread.join() 104 self._loop.close() 105 106 107class SyncPublisher: 108 """A :class:`~acemq_amqp.Publisher` you can call without awaiting.""" 109 110 def __init__(self, loop: _LoopThread, publisher: Publisher) -> None: 111 self._loop = loop 112 self._publisher = publisher 113 114 def send( 115 self, 116 payload: Any, 117 *, 118 envelope: Envelope | None = None, 119 routing_key: str | None = None, 120 ) -> PublishResult: 121 """Publishes one message and waits for the broker to answer. 122 123 :param payload: what to send 124 :param envelope: metadata to send instead of a fresh one 125 :param routing_key: what to publish under, overriding the publisher's 126 :returns: what the broker said 127 """ 128 return self._loop.run( 129 self._publisher.send(payload, envelope=envelope, routing_key=routing_key) 130 ) 131 132 def send_all(self, payloads: Iterable[Any]) -> list[PublishResult]: 133 """Publishes a batch and waits for every confirm. 134 135 Every message goes out before any confirm is awaited, which is the 136 whole point of it: a loop calling :meth:`send` pays a broker round trip 137 per message. See :meth:`acemq_amqp.Publisher.send_all` for what a 138 partial failure reports and why it is not atomic. 139 140 :param payloads: what to send, in order 141 :returns: what the broker said about each, in the order the payloads 142 were given 143 :raises PublishError: when any message was not confirmed 144 """ 145 return self._loop.run(self._publisher.send_all(payloads)) 146 147 148class SyncConsumer: 149 """A running subscription. Close it to stop.""" 150 151 def __init__( 152 self, connection: SyncConnection, consumer: Consumer, workers: ThreadPoolExecutor 153 ) -> None: 154 self._connection = connection 155 self._consumer = consumer 156 self._workers = workers 157 158 @property 159 def queue(self) -> str: 160 """The queue this consumer reads.""" 161 return self._consumer.queue 162 163 def close(self, *, timeout: float | None = DEFAULT_DRAIN_TIMEOUT) -> bool: 164 """Stops the consumer and waits, for up to ``timeout``, for the handlers 165 already running. 166 167 Delivery stops first, and a message that had been delivered but not 168 started is given back to the broker. A handler that finishes in time is 169 settled as usual — see :meth:`acemq_amqp.Consumer.close`. 170 171 **A handler still running at the deadline is abandoned, not stopped.** 172 Python cannot cancel a thread, so it keeps running until the handler 173 returns of its own accord, and whatever it returns is thrown away. Its 174 message is left unsettled — never acknowledged, never rejected, never 175 dead-lettered — so the broker hands it out again once the channel goes: 176 a handler that was cut off may have done its work, and the message may 177 be handled twice, which is the at-least-once promise and not a loss. 178 The settlement belongs to the consumer, not to the thread, so a thread 179 that finishes late has nothing to acknowledge with and cannot settle a 180 message on a channel that has closed or been replaced. 181 182 The abandoned thread is a normal, non-daemon thread: the interpreter 183 waits for it at exit. A handler that can hang should carry its own 184 timeout. 185 186 :param timeout: seconds to wait for every running handler together; 187 ``None`` waits for as long as they take 188 :returns: ``True`` if every handler finished, ``False`` if the time ran 189 out first and some were abandoned — the consumer is stopped either way 190 """ 191 try: 192 return self._connection._loop.run(self._consumer.close(timeout=timeout)) 193 finally: 194 # Not waited for: a thread still running here is one the deadline 195 # has already given up on. 196 self._workers.shutdown(wait=False, cancel_futures=True) 197 198 def __enter__(self) -> SyncConsumer: 199 return self 200 201 def __exit__(self, *_: object) -> None: 202 self.close() 203 204 205class SyncConnection: 206 """A connection to a broker, without an event loop in sight. 207 208 Everything on it blocks until the broker has answered, which is the point: 209 a program that is not running a loop should not have to start one to send a 210 message. 211 """ 212 213 def __init__(self, loop: _LoopThread, connection: Connection) -> None: 214 self._loop = loop 215 self._connection = connection 216 self._closed = False 217 self._workers: list[ThreadPoolExecutor] = [] 218 219 @property 220 def connection(self) -> Connection: 221 """The asyncio connection underneath, for code that has a loop after all.""" 222 return self._connection 223 224 def declare(self, topology: Topology) -> None: 225 """Applies a topology to this connection's broker.""" 226 self._loop.run(self._connection.declare(topology)) 227 228 def publisher( 229 self, 230 exchange: str = "", 231 routing_key: str = "", 232 *, 233 codec: Codec | None = None, 234 persistent: bool = True, 235 mandatory: bool = True, 236 ) -> SyncPublisher: 237 """Builds a publisher for an exchange and routing key. 238 239 Mandatory by default, as :meth:`acemq_amqp.Connection.publisher` is: 240 ``mandatory=False`` opts out of the unroutable error.""" 241 return SyncPublisher( 242 self._loop, 243 self._connection.publisher( 244 exchange, 245 routing_key, 246 codec=codec, 247 persistent=persistent, 248 mandatory=mandatory, 249 ), 250 ) 251 252 def consume( 253 self, 254 queue: str, 255 handler: SyncHandler, 256 *, 257 codec: Codec | None = None, 258 retry: RetryPolicy | None = None, 259 prefetch: int | None = None, 260 concurrency: int = 1, 261 tag: str = "", 262 args: Mapping[str, Any] | None = None, 263 declare: bool = True, 264 ) -> SyncConsumer: 265 """Reads messages from a queue until the returned consumer is closed. 266 267 The handler is called on a worker thread, not on the loop, so it may 268 block for as long as it needs to without stopping anything else. There 269 are ``concurrency`` threads and ``concurrency`` messages in flight, so 270 the number means the same thing here as it does on the async API. 271 272 :param queue: what to read 273 :param handler: what to do with a message 274 :param codec: a codec other than this connection's 275 :param retry: a policy other than this connection's 276 :param prefetch: how many unacknowledged messages to hold 277 :param concurrency: how many messages to work on at once 278 :param tag: what to call this consumer to the broker 279 :param args: broker-specific consumer arguments 280 :param declare: declare ``{queue}.dlq``, ``{queue}.parked`` and the 281 rungs before subscribing. On by default; see 282 :meth:`acemq_amqp.Connection.consume` 283 :returns: the running consumer 284 """ 285 workers = ThreadPoolExecutor( 286 max_workers=concurrency, thread_name_prefix=f"acemq-{queue}" 287 ) 288 self._workers.append(workers) 289 290 async def run_on_a_thread(message: Message) -> Ack: 291 loop = asyncio.get_running_loop() 292 return await loop.run_in_executor(workers, handler, message) 293 294 consumer = self._loop.run( 295 self._connection.consume( 296 queue, 297 run_on_a_thread, 298 codec=codec, 299 retry=retry, 300 prefetch=prefetch, 301 concurrency=concurrency, 302 tag=tag, 303 args=args, 304 declare=declare, 305 ) 306 ) 307 return SyncConsumer(self, consumer, workers) 308 309 def pipeline(self, name: str) -> SyncPipelineBuilder: 310 """Starts declaring a pipeline, as :meth:`acemq_amqp.Connection.pipeline`. 311 312 Each step's handler is a plain function, called on a worker thread so it 313 may block. 314 315 :param name: the pipeline's name, which is also its exchange 316 :returns: a builder; nothing is declared until its ``build()`` 317 """ 318 return SyncPipelineBuilder(self, name) 319 320 def queue_exists(self, queue: str) -> bool: 321 """Whether a queue is on the broker, creating nothing.""" 322 return self._loop.run(self._connection.queue_exists(queue)) 323 324 def message_count(self, queue: str) -> int: 325 """How many messages are waiting on a queue.""" 326 return self._loop.run(self._connection.message_count(queue)) 327 328 def delete_queue(self, queue: str) -> None: 329 """Removes a queue and every message still on it.""" 330 self._loop.run(self._connection.delete_queue(queue)) 331 332 def close(self, *, timeout: float | None = DEFAULT_DRAIN_TIMEOUT) -> bool: 333 """Stops every consumer, releases the connection and stops the loop. 334 335 Every consumer's running handlers share one deadline, ``timeout``. A 336 handler still running at it is abandoned exactly as 337 :meth:`SyncConsumer.close` describes: its thread keeps running, its 338 result is discarded and its message is left unsettled for the broker 339 to redeliver. 340 341 :param timeout: seconds to wait for the running handlers; ``None`` 342 waits for as long as they take 343 :returns: ``True`` if every handler finished, ``False`` if the time ran 344 out first. Closing again returns ``True`` 345 """ 346 if self._closed: 347 return True 348 self._closed = True 349 try: 350 return self._loop.run(self._connection.close(timeout=timeout)) 351 finally: 352 self._loop.stop() 353 for workers in self._workers: 354 workers.shutdown(wait=False, cancel_futures=True) 355 356 def __enter__(self) -> SyncConnection: 357 return self 358 359 def __exit__(self, *_: object) -> None: 360 self.close() 361 362 363def connect( 364 url: str, 365 *, 366 codec: Codec | None = None, 367 origin: str | None = None, 368 retry: RetryPolicy | None = None, 369 prefetch: int = DEFAULT_PREFETCH, 370 max_outstanding_publishes: int = DEFAULT_MAX_OUTSTANDING_PUBLISHES, 371 confirm_timeout: timedelta = DEFAULT_CONFIRM_TIMEOUT, 372 security: Security | None = None, 373 **transport_options: Any, 374) -> SyncConnection: 375 """Opens a connection to a broker, blocking until it is open. 376 377 Takes the same arguments as :func:`acemq_amqp.connect` and returns the 378 blocking shape of the same thing — including ``security``, because a program 379 that is not running an event loop has exactly the same broker to reach:: 380 381 with sync.connect( 382 "amqps://broker.internal:5671/", 383 security=Security( 384 certificate_authority="certs/ca.crt", 385 credentials=credentials_from_environment(), 386 ), 387 ) as mq: 388 ... 389 390 :param url: where the broker is 391 :param codec: what publishers and consumers use unless they say otherwise 392 :param origin: what to stamp on published messages 393 :param retry: what consumers use unless they say otherwise 394 :param prefetch: how many unacknowledged messages a consumer holds 395 :param max_outstanding_publishes: how many publishes may be waiting for the 396 broker at once, a thousand by default. See 397 :class:`acemq_amqp.Connection` 398 :param confirm_timeout: how long a publish waits for room before raising 399 :param security: how to verify the broker and who to log in as 400 :param transport_options: passed to the transport 401 :returns: the connection 402 """ 403 loop = _LoopThread(name="acemq-loop") 404 try: 405 connection = loop.run( 406 _connect_async( 407 url, 408 codec=codec, 409 origin=origin, 410 retry=retry, 411 prefetch=prefetch, 412 max_outstanding_publishes=max_outstanding_publishes, 413 confirm_timeout=confirm_timeout, 414 security=security, 415 **transport_options, 416 ) 417 ) 418 except BaseException: 419 # The loop outlives a failed connect otherwise, and a thread nobody has 420 # a reference to is a thread nobody can stop. 421 loop.stop() 422 raise 423 return SyncConnection(loop, connection) 424 425 426class SyncPipelineBuilder: 427 """:class:`~acemq_amqp.patterns.PipelineBuilder` without an event loop.""" 428 429 def __init__(self, connection: SyncConnection, name: str) -> None: 430 self._loop = connection._loop 431 self._builder = connection.connection.pipeline(name) 432 433 def step( 434 self, 435 name: str, 436 handler: Callable[[Message], Any], 437 *, 438 consumers: int = 1, 439 retry: RetryPolicy | None = None, 440 prefetch: int | None = None, 441 concurrency: int = 1, 442 ) -> SyncPipelineBuilder: 443 """Adds the next step; the options are 444 :meth:`~acemq_amqp.patterns.PipelineBuilder.step`'s.""" 445 446 def on_a_thread(message: Message) -> Any: 447 return asyncio.to_thread(handler, message) 448 449 self._builder.step( 450 name, 451 on_a_thread, 452 consumers=consumers, 453 retry=retry, 454 prefetch=prefetch, 455 concurrency=concurrency, 456 ) 457 return self 458 459 def build(self) -> SyncPipeline: 460 """Declares the pipeline and starts its steps.""" 461 return SyncPipeline(self._loop, self._loop.run(self._builder.build())) 462 463 464class SyncPipeline: 465 """A running :class:`~acemq_amqp.patterns.Pipeline`, without an event loop.""" 466 467 def __init__(self, loop: _LoopThread, pipeline: Pipeline) -> None: 468 self._loop = loop 469 self._pipeline = pipeline 470 471 @property 472 def pipeline(self) -> Pipeline: 473 """The asyncio pipeline underneath: ``name``, ``steps``, ``queue_for``.""" 474 return self._pipeline 475 476 def send( 477 self, payload: Any, *, envelope: Envelope | None = None, codec: Codec | None = None 478 ) -> str: 479 """Starts a run at the first step and returns its identifier.""" 480 return self._loop.run(self._pipeline.send(payload, envelope=envelope, codec=codec)) 481 482 def close(self) -> None: 483 """Stops every step's consumers, leaving the queues alone.""" 484 self._loop.run(self._pipeline.close()) 485 486 def __enter__(self) -> SyncPipeline: 487 return self 488 489 def __exit__(self, *_: object) -> None: 490 self.close()
108class SyncPublisher: 109 """A :class:`~acemq_amqp.Publisher` you can call without awaiting.""" 110 111 def __init__(self, loop: _LoopThread, publisher: Publisher) -> None: 112 self._loop = loop 113 self._publisher = publisher 114 115 def send( 116 self, 117 payload: Any, 118 *, 119 envelope: Envelope | None = None, 120 routing_key: str | None = None, 121 ) -> PublishResult: 122 """Publishes one message and waits for the broker to answer. 123 124 :param payload: what to send 125 :param envelope: metadata to send instead of a fresh one 126 :param routing_key: what to publish under, overriding the publisher's 127 :returns: what the broker said 128 """ 129 return self._loop.run( 130 self._publisher.send(payload, envelope=envelope, routing_key=routing_key) 131 ) 132 133 def send_all(self, payloads: Iterable[Any]) -> list[PublishResult]: 134 """Publishes a batch and waits for every confirm. 135 136 Every message goes out before any confirm is awaited, which is the 137 whole point of it: a loop calling :meth:`send` pays a broker round trip 138 per message. See :meth:`acemq_amqp.Publisher.send_all` for what a 139 partial failure reports and why it is not atomic. 140 141 :param payloads: what to send, in order 142 :returns: what the broker said about each, in the order the payloads 143 were given 144 :raises PublishError: when any message was not confirmed 145 """ 146 return self._loop.run(self._publisher.send_all(payloads))
A ~acemq_amqp.Publisher you can call without awaiting.
115 def send( 116 self, 117 payload: Any, 118 *, 119 envelope: Envelope | None = None, 120 routing_key: str | None = None, 121 ) -> PublishResult: 122 """Publishes one message and waits for the broker to answer. 123 124 :param payload: what to send 125 :param envelope: metadata to send instead of a fresh one 126 :param routing_key: what to publish under, overriding the publisher's 127 :returns: what the broker said 128 """ 129 return self._loop.run( 130 self._publisher.send(payload, envelope=envelope, routing_key=routing_key) 131 )
Publishes one message and waits for the broker to answer.
Parameters
- payload: what to send
- envelope: metadata to send instead of a fresh one
- routing_key: what to publish under, overriding the publisher's :returns: what the broker said
133 def send_all(self, payloads: Iterable[Any]) -> list[PublishResult]: 134 """Publishes a batch and waits for every confirm. 135 136 Every message goes out before any confirm is awaited, which is the 137 whole point of it: a loop calling :meth:`send` pays a broker round trip 138 per message. See :meth:`acemq_amqp.Publisher.send_all` for what a 139 partial failure reports and why it is not atomic. 140 141 :param payloads: what to send, in order 142 :returns: what the broker said about each, in the order the payloads 143 were given 144 :raises PublishError: when any message was not confirmed 145 """ 146 return self._loop.run(self._publisher.send_all(payloads))
Publishes a batch and waits for every confirm.
Every message goes out before any confirm is awaited, which is the
whole point of it: a loop calling send() pays a broker round trip
per message. See acemq_amqp.Publisher.send_all() for what a
partial failure reports and why it is not atomic.
Parameters
- payloads: what to send, in order :returns: what the broker said about each, in the order the payloads were given
Raises
- PublishError: when any message was not confirmed
149class SyncConsumer: 150 """A running subscription. Close it to stop.""" 151 152 def __init__( 153 self, connection: SyncConnection, consumer: Consumer, workers: ThreadPoolExecutor 154 ) -> None: 155 self._connection = connection 156 self._consumer = consumer 157 self._workers = workers 158 159 @property 160 def queue(self) -> str: 161 """The queue this consumer reads.""" 162 return self._consumer.queue 163 164 def close(self, *, timeout: float | None = DEFAULT_DRAIN_TIMEOUT) -> bool: 165 """Stops the consumer and waits, for up to ``timeout``, for the handlers 166 already running. 167 168 Delivery stops first, and a message that had been delivered but not 169 started is given back to the broker. A handler that finishes in time is 170 settled as usual — see :meth:`acemq_amqp.Consumer.close`. 171 172 **A handler still running at the deadline is abandoned, not stopped.** 173 Python cannot cancel a thread, so it keeps running until the handler 174 returns of its own accord, and whatever it returns is thrown away. Its 175 message is left unsettled — never acknowledged, never rejected, never 176 dead-lettered — so the broker hands it out again once the channel goes: 177 a handler that was cut off may have done its work, and the message may 178 be handled twice, which is the at-least-once promise and not a loss. 179 The settlement belongs to the consumer, not to the thread, so a thread 180 that finishes late has nothing to acknowledge with and cannot settle a 181 message on a channel that has closed or been replaced. 182 183 The abandoned thread is a normal, non-daemon thread: the interpreter 184 waits for it at exit. A handler that can hang should carry its own 185 timeout. 186 187 :param timeout: seconds to wait for every running handler together; 188 ``None`` waits for as long as they take 189 :returns: ``True`` if every handler finished, ``False`` if the time ran 190 out first and some were abandoned — the consumer is stopped either way 191 """ 192 try: 193 return self._connection._loop.run(self._consumer.close(timeout=timeout)) 194 finally: 195 # Not waited for: a thread still running here is one the deadline 196 # has already given up on. 197 self._workers.shutdown(wait=False, cancel_futures=True) 198 199 def __enter__(self) -> SyncConsumer: 200 return self 201 202 def __exit__(self, *_: object) -> None: 203 self.close()
A running subscription. Close it to stop.
159 @property 160 def queue(self) -> str: 161 """The queue this consumer reads.""" 162 return self._consumer.queue
The queue this consumer reads.
164 def close(self, *, timeout: float | None = DEFAULT_DRAIN_TIMEOUT) -> bool: 165 """Stops the consumer and waits, for up to ``timeout``, for the handlers 166 already running. 167 168 Delivery stops first, and a message that had been delivered but not 169 started is given back to the broker. A handler that finishes in time is 170 settled as usual — see :meth:`acemq_amqp.Consumer.close`. 171 172 **A handler still running at the deadline is abandoned, not stopped.** 173 Python cannot cancel a thread, so it keeps running until the handler 174 returns of its own accord, and whatever it returns is thrown away. Its 175 message is left unsettled — never acknowledged, never rejected, never 176 dead-lettered — so the broker hands it out again once the channel goes: 177 a handler that was cut off may have done its work, and the message may 178 be handled twice, which is the at-least-once promise and not a loss. 179 The settlement belongs to the consumer, not to the thread, so a thread 180 that finishes late has nothing to acknowledge with and cannot settle a 181 message on a channel that has closed or been replaced. 182 183 The abandoned thread is a normal, non-daemon thread: the interpreter 184 waits for it at exit. A handler that can hang should carry its own 185 timeout. 186 187 :param timeout: seconds to wait for every running handler together; 188 ``None`` waits for as long as they take 189 :returns: ``True`` if every handler finished, ``False`` if the time ran 190 out first and some were abandoned — the consumer is stopped either way 191 """ 192 try: 193 return self._connection._loop.run(self._consumer.close(timeout=timeout)) 194 finally: 195 # Not waited for: a thread still running here is one the deadline 196 # has already given up on. 197 self._workers.shutdown(wait=False, cancel_futures=True)
Stops the consumer and waits, for up to timeout, for the handlers
already running.
Delivery stops first, and a message that had been delivered but not
started is given back to the broker. A handler that finishes in time is
settled as usual — see acemq_amqp.Consumer.close().
A handler still running at the deadline is abandoned, not stopped. Python cannot cancel a thread, so it keeps running until the handler returns of its own accord, and whatever it returns is thrown away. Its message is left unsettled — never acknowledged, never rejected, never dead-lettered — so the broker hands it out again once the channel goes: a handler that was cut off may have done its work, and the message may be handled twice, which is the at-least-once promise and not a loss. The settlement belongs to the consumer, not to the thread, so a thread that finishes late has nothing to acknowledge with and cannot settle a message on a channel that has closed or been replaced.
The abandoned thread is a normal, non-daemon thread: the interpreter waits for it at exit. A handler that can hang should carry its own timeout.
Parameters
- timeout: seconds to wait for every running handler together;
Nonewaits for as long as they take :returns:Trueif every handler finished,Falseif the time ran out first and some were abandoned — the consumer is stopped either way
206class SyncConnection: 207 """A connection to a broker, without an event loop in sight. 208 209 Everything on it blocks until the broker has answered, which is the point: 210 a program that is not running a loop should not have to start one to send a 211 message. 212 """ 213 214 def __init__(self, loop: _LoopThread, connection: Connection) -> None: 215 self._loop = loop 216 self._connection = connection 217 self._closed = False 218 self._workers: list[ThreadPoolExecutor] = [] 219 220 @property 221 def connection(self) -> Connection: 222 """The asyncio connection underneath, for code that has a loop after all.""" 223 return self._connection 224 225 def declare(self, topology: Topology) -> None: 226 """Applies a topology to this connection's broker.""" 227 self._loop.run(self._connection.declare(topology)) 228 229 def publisher( 230 self, 231 exchange: str = "", 232 routing_key: str = "", 233 *, 234 codec: Codec | None = None, 235 persistent: bool = True, 236 mandatory: bool = True, 237 ) -> SyncPublisher: 238 """Builds a publisher for an exchange and routing key. 239 240 Mandatory by default, as :meth:`acemq_amqp.Connection.publisher` is: 241 ``mandatory=False`` opts out of the unroutable error.""" 242 return SyncPublisher( 243 self._loop, 244 self._connection.publisher( 245 exchange, 246 routing_key, 247 codec=codec, 248 persistent=persistent, 249 mandatory=mandatory, 250 ), 251 ) 252 253 def consume( 254 self, 255 queue: str, 256 handler: SyncHandler, 257 *, 258 codec: Codec | None = None, 259 retry: RetryPolicy | None = None, 260 prefetch: int | None = None, 261 concurrency: int = 1, 262 tag: str = "", 263 args: Mapping[str, Any] | None = None, 264 declare: bool = True, 265 ) -> SyncConsumer: 266 """Reads messages from a queue until the returned consumer is closed. 267 268 The handler is called on a worker thread, not on the loop, so it may 269 block for as long as it needs to without stopping anything else. There 270 are ``concurrency`` threads and ``concurrency`` messages in flight, so 271 the number means the same thing here as it does on the async API. 272 273 :param queue: what to read 274 :param handler: what to do with a message 275 :param codec: a codec other than this connection's 276 :param retry: a policy other than this connection's 277 :param prefetch: how many unacknowledged messages to hold 278 :param concurrency: how many messages to work on at once 279 :param tag: what to call this consumer to the broker 280 :param args: broker-specific consumer arguments 281 :param declare: declare ``{queue}.dlq``, ``{queue}.parked`` and the 282 rungs before subscribing. On by default; see 283 :meth:`acemq_amqp.Connection.consume` 284 :returns: the running consumer 285 """ 286 workers = ThreadPoolExecutor( 287 max_workers=concurrency, thread_name_prefix=f"acemq-{queue}" 288 ) 289 self._workers.append(workers) 290 291 async def run_on_a_thread(message: Message) -> Ack: 292 loop = asyncio.get_running_loop() 293 return await loop.run_in_executor(workers, handler, message) 294 295 consumer = self._loop.run( 296 self._connection.consume( 297 queue, 298 run_on_a_thread, 299 codec=codec, 300 retry=retry, 301 prefetch=prefetch, 302 concurrency=concurrency, 303 tag=tag, 304 args=args, 305 declare=declare, 306 ) 307 ) 308 return SyncConsumer(self, consumer, workers) 309 310 def pipeline(self, name: str) -> SyncPipelineBuilder: 311 """Starts declaring a pipeline, as :meth:`acemq_amqp.Connection.pipeline`. 312 313 Each step's handler is a plain function, called on a worker thread so it 314 may block. 315 316 :param name: the pipeline's name, which is also its exchange 317 :returns: a builder; nothing is declared until its ``build()`` 318 """ 319 return SyncPipelineBuilder(self, name) 320 321 def queue_exists(self, queue: str) -> bool: 322 """Whether a queue is on the broker, creating nothing.""" 323 return self._loop.run(self._connection.queue_exists(queue)) 324 325 def message_count(self, queue: str) -> int: 326 """How many messages are waiting on a queue.""" 327 return self._loop.run(self._connection.message_count(queue)) 328 329 def delete_queue(self, queue: str) -> None: 330 """Removes a queue and every message still on it.""" 331 self._loop.run(self._connection.delete_queue(queue)) 332 333 def close(self, *, timeout: float | None = DEFAULT_DRAIN_TIMEOUT) -> bool: 334 """Stops every consumer, releases the connection and stops the loop. 335 336 Every consumer's running handlers share one deadline, ``timeout``. A 337 handler still running at it is abandoned exactly as 338 :meth:`SyncConsumer.close` describes: its thread keeps running, its 339 result is discarded and its message is left unsettled for the broker 340 to redeliver. 341 342 :param timeout: seconds to wait for the running handlers; ``None`` 343 waits for as long as they take 344 :returns: ``True`` if every handler finished, ``False`` if the time ran 345 out first. Closing again returns ``True`` 346 """ 347 if self._closed: 348 return True 349 self._closed = True 350 try: 351 return self._loop.run(self._connection.close(timeout=timeout)) 352 finally: 353 self._loop.stop() 354 for workers in self._workers: 355 workers.shutdown(wait=False, cancel_futures=True) 356 357 def __enter__(self) -> SyncConnection: 358 return self 359 360 def __exit__(self, *_: object) -> None: 361 self.close()
A connection to a broker, without an event loop in sight.
Everything on it blocks until the broker has answered, which is the point: a program that is not running a loop should not have to start one to send a message.
220 @property 221 def connection(self) -> Connection: 222 """The asyncio connection underneath, for code that has a loop after all.""" 223 return self._connection
The asyncio connection underneath, for code that has a loop after all.
225 def declare(self, topology: Topology) -> None: 226 """Applies a topology to this connection's broker.""" 227 self._loop.run(self._connection.declare(topology))
Applies a topology to this connection's broker.
229 def publisher( 230 self, 231 exchange: str = "", 232 routing_key: str = "", 233 *, 234 codec: Codec | None = None, 235 persistent: bool = True, 236 mandatory: bool = True, 237 ) -> SyncPublisher: 238 """Builds a publisher for an exchange and routing key. 239 240 Mandatory by default, as :meth:`acemq_amqp.Connection.publisher` is: 241 ``mandatory=False`` opts out of the unroutable error.""" 242 return SyncPublisher( 243 self._loop, 244 self._connection.publisher( 245 exchange, 246 routing_key, 247 codec=codec, 248 persistent=persistent, 249 mandatory=mandatory, 250 ), 251 )
Builds a publisher for an exchange and routing key.
Mandatory by default, as acemq_amqp.Connection.publisher() is:
mandatory=False opts out of the unroutable error.
253 def consume( 254 self, 255 queue: str, 256 handler: SyncHandler, 257 *, 258 codec: Codec | None = None, 259 retry: RetryPolicy | None = None, 260 prefetch: int | None = None, 261 concurrency: int = 1, 262 tag: str = "", 263 args: Mapping[str, Any] | None = None, 264 declare: bool = True, 265 ) -> SyncConsumer: 266 """Reads messages from a queue until the returned consumer is closed. 267 268 The handler is called on a worker thread, not on the loop, so it may 269 block for as long as it needs to without stopping anything else. There 270 are ``concurrency`` threads and ``concurrency`` messages in flight, so 271 the number means the same thing here as it does on the async API. 272 273 :param queue: what to read 274 :param handler: what to do with a message 275 :param codec: a codec other than this connection's 276 :param retry: a policy other than this connection's 277 :param prefetch: how many unacknowledged messages to hold 278 :param concurrency: how many messages to work on at once 279 :param tag: what to call this consumer to the broker 280 :param args: broker-specific consumer arguments 281 :param declare: declare ``{queue}.dlq``, ``{queue}.parked`` and the 282 rungs before subscribing. On by default; see 283 :meth:`acemq_amqp.Connection.consume` 284 :returns: the running consumer 285 """ 286 workers = ThreadPoolExecutor( 287 max_workers=concurrency, thread_name_prefix=f"acemq-{queue}" 288 ) 289 self._workers.append(workers) 290 291 async def run_on_a_thread(message: Message) -> Ack: 292 loop = asyncio.get_running_loop() 293 return await loop.run_in_executor(workers, handler, message) 294 295 consumer = self._loop.run( 296 self._connection.consume( 297 queue, 298 run_on_a_thread, 299 codec=codec, 300 retry=retry, 301 prefetch=prefetch, 302 concurrency=concurrency, 303 tag=tag, 304 args=args, 305 declare=declare, 306 ) 307 ) 308 return SyncConsumer(self, consumer, workers)
Reads messages from a queue until the returned consumer is closed.
The handler is called on a worker thread, not on the loop, so it may
block for as long as it needs to without stopping anything else. There
are concurrency threads and concurrency messages in flight, so
the number means the same thing here as it does on the async API.
Parameters
- queue: what to read
- handler: what to do with a message
- codec: a codec other than this connection's
- retry: a policy other than this connection's
- prefetch: how many unacknowledged messages to hold
- concurrency: how many messages to work on at once
- tag: what to call this consumer to the broker
- args: broker-specific consumer arguments
- declare: declare
{queue}.dlq,{queue}.parkedand the rungs before subscribing. On by default; seeacemq_amqp.Connection.consume():returns: the running consumer
310 def pipeline(self, name: str) -> SyncPipelineBuilder: 311 """Starts declaring a pipeline, as :meth:`acemq_amqp.Connection.pipeline`. 312 313 Each step's handler is a plain function, called on a worker thread so it 314 may block. 315 316 :param name: the pipeline's name, which is also its exchange 317 :returns: a builder; nothing is declared until its ``build()`` 318 """ 319 return SyncPipelineBuilder(self, name)
Starts declaring a pipeline, as acemq_amqp.Connection.pipeline().
Each step's handler is a plain function, called on a worker thread so it may block.
Parameters
- name: the pipeline's name, which is also its exchange
:returns: a builder; nothing is declared until its
build()
321 def queue_exists(self, queue: str) -> bool: 322 """Whether a queue is on the broker, creating nothing.""" 323 return self._loop.run(self._connection.queue_exists(queue))
Whether a queue is on the broker, creating nothing.
325 def message_count(self, queue: str) -> int: 326 """How many messages are waiting on a queue.""" 327 return self._loop.run(self._connection.message_count(queue))
How many messages are waiting on a queue.
329 def delete_queue(self, queue: str) -> None: 330 """Removes a queue and every message still on it.""" 331 self._loop.run(self._connection.delete_queue(queue))
Removes a queue and every message still on it.
333 def close(self, *, timeout: float | None = DEFAULT_DRAIN_TIMEOUT) -> bool: 334 """Stops every consumer, releases the connection and stops the loop. 335 336 Every consumer's running handlers share one deadline, ``timeout``. A 337 handler still running at it is abandoned exactly as 338 :meth:`SyncConsumer.close` describes: its thread keeps running, its 339 result is discarded and its message is left unsettled for the broker 340 to redeliver. 341 342 :param timeout: seconds to wait for the running handlers; ``None`` 343 waits for as long as they take 344 :returns: ``True`` if every handler finished, ``False`` if the time ran 345 out first. Closing again returns ``True`` 346 """ 347 if self._closed: 348 return True 349 self._closed = True 350 try: 351 return self._loop.run(self._connection.close(timeout=timeout)) 352 finally: 353 self._loop.stop() 354 for workers in self._workers: 355 workers.shutdown(wait=False, cancel_futures=True)
Stops every consumer, releases the connection and stops the loop.
Every consumer's running handlers share one deadline, timeout. A
handler still running at it is abandoned exactly as
SyncConsumer.close() describes: its thread keeps running, its
result is discarded and its message is left unsettled for the broker
to redeliver.
Parameters
- timeout: seconds to wait for the running handlers;
Nonewaits for as long as they take :returns:Trueif every handler finished,Falseif the time ran out first. Closing again returnsTrue
364def connect( 365 url: str, 366 *, 367 codec: Codec | None = None, 368 origin: str | None = None, 369 retry: RetryPolicy | None = None, 370 prefetch: int = DEFAULT_PREFETCH, 371 max_outstanding_publishes: int = DEFAULT_MAX_OUTSTANDING_PUBLISHES, 372 confirm_timeout: timedelta = DEFAULT_CONFIRM_TIMEOUT, 373 security: Security | None = None, 374 **transport_options: Any, 375) -> SyncConnection: 376 """Opens a connection to a broker, blocking until it is open. 377 378 Takes the same arguments as :func:`acemq_amqp.connect` and returns the 379 blocking shape of the same thing — including ``security``, because a program 380 that is not running an event loop has exactly the same broker to reach:: 381 382 with sync.connect( 383 "amqps://broker.internal:5671/", 384 security=Security( 385 certificate_authority="certs/ca.crt", 386 credentials=credentials_from_environment(), 387 ), 388 ) as mq: 389 ... 390 391 :param url: where the broker is 392 :param codec: what publishers and consumers use unless they say otherwise 393 :param origin: what to stamp on published messages 394 :param retry: what consumers use unless they say otherwise 395 :param prefetch: how many unacknowledged messages a consumer holds 396 :param max_outstanding_publishes: how many publishes may be waiting for the 397 broker at once, a thousand by default. See 398 :class:`acemq_amqp.Connection` 399 :param confirm_timeout: how long a publish waits for room before raising 400 :param security: how to verify the broker and who to log in as 401 :param transport_options: passed to the transport 402 :returns: the connection 403 """ 404 loop = _LoopThread(name="acemq-loop") 405 try: 406 connection = loop.run( 407 _connect_async( 408 url, 409 codec=codec, 410 origin=origin, 411 retry=retry, 412 prefetch=prefetch, 413 max_outstanding_publishes=max_outstanding_publishes, 414 confirm_timeout=confirm_timeout, 415 security=security, 416 **transport_options, 417 ) 418 ) 419 except BaseException: 420 # The loop outlives a failed connect otherwise, and a thread nobody has 421 # a reference to is a thread nobody can stop. 422 loop.stop() 423 raise 424 return SyncConnection(loop, connection)
Opens a connection to a broker, blocking until it is open.
Takes the same arguments as acemq_amqp.connect() and returns the
blocking shape of the same thing — including security, because a program
that is not running an event loop has exactly the same broker to reach::
with sync.connect(
"amqps://broker.internal:5671/",
security=Security(
certificate_authority="certs/ca.crt",
credentials=credentials_from_environment(),
),
) as mq:
...
Parameters
- url: where the broker is
- codec: what publishers and consumers use unless they say otherwise
- origin: what to stamp on published messages
- retry: what consumers use unless they say otherwise
- prefetch: how many unacknowledged messages a consumer holds
- max_outstanding_publishes: how many publishes may be waiting for the
broker at once, a thousand by default. See
acemq_amqp.Connection - confirm_timeout: how long a publish waits for room before raising
- security: how to verify the broker and who to log in as
- transport_options: passed to the transport :returns: the connection
427class SyncPipelineBuilder: 428 """:class:`~acemq_amqp.patterns.PipelineBuilder` without an event loop.""" 429 430 def __init__(self, connection: SyncConnection, name: str) -> None: 431 self._loop = connection._loop 432 self._builder = connection.connection.pipeline(name) 433 434 def step( 435 self, 436 name: str, 437 handler: Callable[[Message], Any], 438 *, 439 consumers: int = 1, 440 retry: RetryPolicy | None = None, 441 prefetch: int | None = None, 442 concurrency: int = 1, 443 ) -> SyncPipelineBuilder: 444 """Adds the next step; the options are 445 :meth:`~acemq_amqp.patterns.PipelineBuilder.step`'s.""" 446 447 def on_a_thread(message: Message) -> Any: 448 return asyncio.to_thread(handler, message) 449 450 self._builder.step( 451 name, 452 on_a_thread, 453 consumers=consumers, 454 retry=retry, 455 prefetch=prefetch, 456 concurrency=concurrency, 457 ) 458 return self 459 460 def build(self) -> SyncPipeline: 461 """Declares the pipeline and starts its steps.""" 462 return SyncPipeline(self._loop, self._loop.run(self._builder.build()))
~acemq_amqp.patterns.PipelineBuilder without an event loop.
434 def step( 435 self, 436 name: str, 437 handler: Callable[[Message], Any], 438 *, 439 consumers: int = 1, 440 retry: RetryPolicy | None = None, 441 prefetch: int | None = None, 442 concurrency: int = 1, 443 ) -> SyncPipelineBuilder: 444 """Adds the next step; the options are 445 :meth:`~acemq_amqp.patterns.PipelineBuilder.step`'s.""" 446 447 def on_a_thread(message: Message) -> Any: 448 return asyncio.to_thread(handler, message) 449 450 self._builder.step( 451 name, 452 on_a_thread, 453 consumers=consumers, 454 retry=retry, 455 prefetch=prefetch, 456 concurrency=concurrency, 457 ) 458 return self
Adds the next step; the options are
~acemq_amqp.patterns.PipelineBuilder.step()'s.
465class SyncPipeline: 466 """A running :class:`~acemq_amqp.patterns.Pipeline`, without an event loop.""" 467 468 def __init__(self, loop: _LoopThread, pipeline: Pipeline) -> None: 469 self._loop = loop 470 self._pipeline = pipeline 471 472 @property 473 def pipeline(self) -> Pipeline: 474 """The asyncio pipeline underneath: ``name``, ``steps``, ``queue_for``.""" 475 return self._pipeline 476 477 def send( 478 self, payload: Any, *, envelope: Envelope | None = None, codec: Codec | None = None 479 ) -> str: 480 """Starts a run at the first step and returns its identifier.""" 481 return self._loop.run(self._pipeline.send(payload, envelope=envelope, codec=codec)) 482 483 def close(self) -> None: 484 """Stops every step's consumers, leaving the queues alone.""" 485 self._loop.run(self._pipeline.close()) 486 487 def __enter__(self) -> SyncPipeline: 488 return self 489 490 def __exit__(self, *_: object) -> None: 491 self.close()
A running ~acemq_amqp.patterns.Pipeline, without an event loop.
472 @property 473 def pipeline(self) -> Pipeline: 474 """The asyncio pipeline underneath: ``name``, ``steps``, ``queue_for``.""" 475 return self._pipeline
The asyncio pipeline underneath: name, steps, queue_for.
477 def send( 478 self, payload: Any, *, envelope: Envelope | None = None, codec: Codec | None = None 479 ) -> str: 480 """Starts a run at the first step and returns its identifier.""" 481 return self._loop.run(self._pipeline.send(payload, envelope=envelope, codec=codec))
Starts a run at the first step and returns its identifier.