Skip to content

Brokers

The broker is the main entry point. It wires the registry, pipeline, and transport.

Import paths

# Recommended — top-level re-export
from rabbitkit import AsyncBroker, SyncBroker

# Also fine — canonical submodule path
from rabbitkit.async_ import AsyncBroker
from rabbitkit.sync import SyncBroker

# Full path
from rabbitkit.async_.broker import AsyncBroker
from rabbitkit.sync.broker import SyncBroker

rabbitkit.aio is a deprecated alias for rabbitkit.async_ — importing it emits a DeprecationWarning; use rabbitkit.async_ instead.

AsyncBroker

AsyncBroker

Async broker — wires registry + pipeline + AsyncTransportImpl.

Usage::

config = RabbitConfig(connection=ConnectionConfig(host="localhost"))
broker = AsyncBroker(config)

@broker.subscriber(queue="orders", exchange="events")
async def handle_order(body: bytes) -> None:
    ...

await broker.start()
Source code in src/rabbitkit/async_/broker.py
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
class AsyncBroker:
    """Async broker — wires registry + pipeline + AsyncTransportImpl.

    Usage::

        config = RabbitConfig(connection=ConnectionConfig(host="localhost"))
        broker = AsyncBroker(config)

        @broker.subscriber(queue="orders", exchange="events")
        async def handle_order(body: bytes) -> None:
            ...

        await broker.start()
    """

    # L14: liveness heartbeat tick interval -- well under any reasonable
    # health.broker_liveness(wedged_timeout=...) so idle-but-healthy periods
    # never spuriously trip liveness.
    _HEARTBEAT_INTERVAL: float = 5.0

    def __init__(
        self,
        config: RabbitConfig | None = None,
        *,
        serializer: Serializer[Any] | None = None,
        di_resolver: Any | None = None,
        context_repo: Any | None = None,
        batch_config: BatchPublishConfig | None = None,
        middlewares: list[BaseMiddleware] | None = None,
    ) -> None:
        self._config = config or RabbitConfig()
        # Private mutable view of consumer config — brokers may apply a
        # prefetch override derived from WorkerConfig.prefetch_per_worker.
        # Stored separately so the caller's frozen RabbitConfig is never mutated.
        self._consumer_config = self._config.consumer

        self._registry = SubscriberRegistry(broker_retry=self._config.retry)
        # The client library's connection/channel errors classify as
        # INFRASTRUCTURE (retried) — core/ cannot import them itself.
        register_infrastructure_errors(*get_infrastructure_errors())
        # verify a route's DLQ exists before dead-lettering into it.
        self._dead_letter_guard = DeadLetterGuard(self._queue_exists_for_guard)
        # a confirmed, metadata-stamped DLQ copy for failures that
        # bypass RetryMiddleware (SafetyConfig.dead_letter_with_metadata).
        self._dead_letter_sanitizers: dict[str, ErrorSanitizer] = {}
        self._dead_letter_copier: DeadLetterCopier | None = (
            DeadLetterCopier(
                self._flow_controlled_internal_publish,
                self._dead_letter_guard.target_for,
                sanitizer_for=self._dead_letter_sanitizer,
                retry_header_for=self._dead_letter_retry_header,
            )
            if self._config.safety.dead_letter_with_metadata
            else None
        )
        self._pipeline = HandlerPipeline(
            serializer=serializer,
            di_resolver=di_resolver,
            context_repo=context_repo,
            reject_transient_on_redelivery=self._config.consumer.reject_transient_on_redelivery,
            manual_settle_on_error=self._config.consumer.manual_settle_on_error,
            processing_timeout=self._config.consumer.processing_timeout,
            dead_letter_check=self._dead_letter_guard.check,
            max_body_bytes=self._config.consumer.max_body_bytes,
            dead_letter_copy=self._dead_letter_copier.copy if self._dead_letter_copier is not None else None,
        )

        # C3: middlewares applied to every broker.publish() call — the primary
        # producer API. Distinct from @subscriber(middlewares=[...]), which
        # only wraps a route's HANDLER-RESULT publishes (Contract 5); without
        # this, e.g. SigningMiddleware never signed anything published via
        # broker.publish() directly. The composed chain is cached by this
        # list's identity (see HandlerPipeline.compose_broker_publish_async), so
        # set the full list via this constructor param — mutating it in place
        # after the first publish() call would silently reuse the stale
        # pre-mutation chain.
        self._publish_middlewares: list[BaseMiddleware] = middlewares or []
        # PublisherConfig.strip_reserved_headers (None = off).
        self._reserved_header_stripper: ReservedHeaderStripper | None = (
            ReservedHeaderStripper(extra=(self._config.retry.retry_header,) if self._config.retry is not None else ())
            if self._config.publisher.strip_reserved_headers
            else None
        )

        self._batch_config = batch_config
        self._batch_publisher: Any | None = None  # BatchPublisher, started lazily in start()
        self._transport: Any | None = None  # AsyncTransportImpl
        self._worker_pool: AsyncWorkerPool | None = None
        self._started = False
        # set by stop() once publisher shutdown begins; publish() then
        # raises BrokerNotStartedError instead of silently reconnecting.
        self._publish_closed = False
        self._rpc_client: Any | None = None

        # L14: liveness heartbeat (see health.broker_liveness). None until
        # start() -- see the start() docstring for why it's set there rather
        # than only on delivery/tick.
        self.last_heartbeat: float | None = None
        self._heartbeat_task: asyncio.Task[None] | None = None
        # I-16: optional callback invoked from the signal handler so an embedding
        # RabbitApp's shutdown event is also set (prevents the double-install hang
        # where the broker's handler overwrites the app's). Wire
        # ``broker.on_app_shutdown = app.request_shutdown`` before ``app.run_async()``.
        self.on_app_shutdown: Callable[[], None] | None = None
        # optional hooks called with the queue name when the BROKER
        # cancels a route's consumer (queue deleted, quorum leader change, ...)
        # and when it is consuming again. The transport re-subscribes on its
        # own; the route reports as not consuming in health checks meanwhile.
        self.on_consumer_cancelled: Callable[[str], None] | None = None
        self.on_consumer_resumed: Callable[[str], None] | None = None
        self._consumer_state_wired: Any = None  # the transport the state callbacks are on
        # connection/channel/flow-control metrics, built at start() from
        # the first MetricsMiddleware with a collector (None = no metrics).
        self._broker_metrics: BrokerMetrics | None = None

        # Bounded graceful drain (C-2): inline in-flight counter guarded by an
        # asyncio.Condition (R-Condition). ``_in_flight`` stays a plain int so
        # health checks that read it directly keep working (backward compat).
        self._in_flight = 0
        self._in_flight_cond: asyncio.Condition | None = None  # lazily created in loop
        # Task/message pairs for in-flight INLINE consumption (no worker pool
        # configured -- the default). Mirrors AsyncWorkerPool._task_messages so
        # a drain-deadline timeout can cancel + nack the still-running ones
        # with delivery-tag logging, the same as the pooled path already does,
        # instead of silently abandoning them unacked.
        self._inflight_tasks: dict[asyncio.Task[None], RabbitMessage] = {}

        # Stream routes: per-route offset tracker (route name -> tracker).
        # Kept across reconnects and stop()/start() so a restarted consumer
        # resumes from its processed position.
        self._stream_trackers: dict[str, StreamOffsetTracker] = {}

        # Optional publish-side flow control (C-6).
        self._flow_controller: Any | None = None

        # Signal-handler bookkeeping (H-SRE5). _signal_prev: the
        # Python-level handler each loop-installed signal replaced, restored
        # by stop(); _original_handlers: the signal.signal() fallback's.
        self._signal_prev: dict[signal.Signals, Any] = {}
        self._original_handlers: dict[signal.Signals, Any] = {}
        self._installed_loop_handlers = False
        self._loop: asyncio.AbstractEventLoop | None = None

        # H11: shutdown event awaited by run() so the drain triggered by a
        # signal (or request_shutdown()) is joined instead of fire-and-forget.
        # _run_waiting is True only while run() is actually awaiting the
        # event, so a signal received under bare start() usage still falls
        # back to the pre-H11 fire-and-forget stop() task.
        self._shutdown_event: asyncio.Event = asyncio.Event()
        self._run_waiting = False

    @property
    def flow_controller(self) -> Any | None:
        """Optional FlowController used to throttle the publish path."""
        return self._flow_controller

    @flow_controller.setter
    def flow_controller(self, value: Any | None) -> None:
        self._flow_controller = value
        if self._transport is not None and value is not None:
            self._transport.on_blocked(value.on_blocked)
            self._transport.on_unblocked(value.on_unblocked)

    def _ensure_inflight_cond(self) -> asyncio.Condition:
        if self._in_flight_cond is None:
            self._in_flight_cond = asyncio.Condition()
        return self._in_flight_cond

    def _mark_heartbeat(self) -> None:
        """Refresh the liveness heartbeat (I-4/L14).

        Called both per delivered message (``on_message`` in
        :meth:`_start_consumer`) and periodically by ``_heartbeat_loop`` --
        the latter is what keeps a healthy but message-idle consumer from
        being mistaken for a wedged one by :func:`health.broker_liveness`.
        """
        self.last_heartbeat = time.monotonic()

    async def _heartbeat_loop(self) -> None:
        """L14: periodic liveness heartbeat -- the async analogue of the sync
        broker's per-``start_consuming()``-tick heartbeat.

        aio-pika has no exposed manual I/O-loop-tick to hook (unlike pika's
        ``process_data_events``); this task ticking on its own interval is
        itself the liveness signal instead -- if the event loop were
        genuinely wedged (blocked, not just disconnected), this task would
        not get scheduled and the heartbeat would correctly go stale. A
        transient disconnect during reconnect is intentionally NOT
        distinguished from "healthy but idle" here: ``broker_liveness``
        documents that a transient disconnect is not itself a liveness
        failure, and a reconnect attempt completes well within
        ``wedged_timeout`` in practice -- only a reconnect loop stuck for the
        full timeout window would (correctly) trip liveness.
        """
        try:
            while True:
                await asyncio.sleep(self._HEARTBEAT_INTERVAL)
                self._mark_heartbeat()
                self._sample_metrics()
        except asyncio.CancelledError:
            pass

    async def _in_flight_inc(self) -> None:
        async with self._ensure_inflight_cond():
            self._in_flight += 1

    async def _in_flight_dec(self) -> None:
        cond = self._ensure_inflight_cond()
        async with cond:
            if self._in_flight > 0:
                self._in_flight -= 1
            if self._in_flight == 0:
                cond.notify_all()

    @property
    def started(self) -> bool:
        """True between a successful ``start()`` and ``stop()``.

        Public counterpart of ``_started`` — health checks
        (:func:`rabbitkit.health.broker_health_check`) read this instead of
        falling back to the private attribute (which emits a
        DeprecationWarning).
        """
        return self._started

    @property
    def config(self) -> RabbitConfig:
        return self._config

    @property
    def publish_middlewares(self) -> list[BaseMiddleware]:
        """Middlewares applied to every ``broker.publish()`` call (e.g. signing).

        Set via the constructor's ``middlewares=`` param. See the comment on
        ``self._publish_middlewares`` for why reassigning (not mutating) is
        required to change this after construction.
        """
        return self._publish_middlewares

    @property
    def routes(self) -> list[RouteDefinition]:
        return self._registry.routes

    @property
    def worker_pool(self) -> AsyncWorkerPool | None:
        """Return the worker pool (if configured)."""
        return self._worker_pool

    @property
    def consumer_config(self) -> ConsumerConfig:
        """Effective consumer config (may reflect WorkerConfig.prefetch override)."""
        return self._consumer_config

    # ── Registration (decorator API) ──────────────────────────────────────

    def subscriber(
        self,
        queue: RabbitQueue | str,
        exchange: RabbitExchange | str | None = None,
        routing_key: str = "",
        ack_policy: AckPolicy = AckPolicy.AUTO,
        middlewares: list[BaseMiddleware] | None = None,
        serializer: Serializer[Any] | None = None,
        retry: RetryConfig | RetryDisabled | None = None,
        tags: frozenset[str] | set[str] | None = None,
        description: str = "",
        name: str | None = None,
        prefetch_count: int | None = None,
        filter_fn: Callable[[RabbitMessage], bool] | None = None,
        reject_without_dlx: str | None = None,
        reply_to_allow: tuple[str, ...] | None = None,
        stream: StreamConsumerConfig | None = None,
        stream_offset: StreamOffsetLike | None = None,
    ) -> Callable[[HandlerT], HandlerT]:
        """Register a subscriber handler."""
        return self._registry.subscriber(
            queue=queue,
            exchange=exchange,
            routing_key=routing_key,
            ack_policy=ack_policy,
            middlewares=middlewares,
            serializer=serializer,
            retry=retry,
            tags=tags,
            description=description,
            name=name,
            prefetch_count=prefetch_count,
            filter_fn=filter_fn,
            reject_without_dlx=reject_without_dlx,
            reply_to_allow=reply_to_allow,
            stream=stream,
            stream_offset=stream_offset,
        )

    def publisher(
        self,
        exchange: RabbitExchange | str | None = None,
        routing_key: str = "",
    ) -> Callable[[HandlerT], HandlerT]:
        """Register a result publisher."""
        return self._registry.publisher(exchange=exchange, routing_key=routing_key)

    def include_router(self, router: RabbitRouter, prefix: str = "") -> None:
        """Include routes from a RabbitRouter."""
        self._registry.include_router(router, prefix=prefix)

    # ── Lifecycle ─────────────────────────────────────────────────────────

    def _dead_letter_sanitizer(self, route: RouteDefinition) -> ErrorSanitizer:
        """The error-header sanitizer for *route*'s metadata-stamped DLQ copies: its retry
        config's ``error_detail`` (the same policy RetryMiddleware applies),
        else the sanitized default."""
        retry = route.effective_retry_config(self._config.retry)
        policy = retry.error_detail if retry is not None else "sanitized"
        sanitizer = self._dead_letter_sanitizers.get(policy)
        if sanitizer is None:
            sanitizer = self._dead_letter_sanitizers[policy] = ErrorSanitizer(
                policy=policy, max_summary_len=ERROR_MESSAGE_MAX_LEN
            )
        return sanitizer

    def _dead_letter_retry_header(self, route: RouteDefinition) -> str:
        retry = route.effective_retry_config(self._config.retry)
        return retry.retry_header if retry is not None else DEFAULT_RETRY_HEADER

    async def __aenter__(self) -> AsyncBroker:
        """``async with AsyncBroker(config) as broker:`` starts the broker and
        stops it when the block exits (also on an exception or cancellation).

        Entering calls ``start(install_signal_handlers=False)``: a ``with``
        block is a scope owned by the surrounding code (a script, a test, an
        application that embeds the broker), so the broker leaves SIGINT and
        SIGTERM to that code. A standalone consumer process should use
        ``await broker.run()`` instead, which owns the signals and drains on
        SIGTERM. To pass a ``WorkerConfig``, call ``start()`` yourself and
        ``stop()`` in a ``finally``; ``start()`` on a started broker is a no-op.
        """
        await self.start(install_signal_handlers=False)
        return self

    async def __aexit__(self, *_exc_info: object) -> None:
        await self.stop()

    async def start(
        self,
        worker_config: WorkerConfig | None = None,
        *,
        install_signal_handlers: bool = True,
    ) -> None:
        """Start the broker - connect, declare topology, start consuming.

        1. Connect to RabbitMQ
        2. Declare exchanges, queues, bindings per TopologyMode
        3. Declare retry topology (delay queues, DLQ)
        4. Optionally create a worker pool for concurrent processing
        5. Start consuming from all registered queues

        When ``install_signal_handlers`` is True (default), SIGINT/SIGTERM are
        trapped so the common ``await broker.start()`` pattern drains gracefully
        instead of hard-dying (H-SRE5). Pass ``False`` when an outer lifecycle
        manager (e.g. ``RabbitApp``) owns signal handling.

        L14: ``last_heartbeat`` is initialized here (not left ``None`` until
        the first message/tick) so a broker that is wedged from the very
        start -- before it ever processes a message or a periodic heartbeat
        tick -- is still caught by :func:`health.broker_liveness`'s
        staleness check, instead of bypassing it entirely (a ``None``
        heartbeat is treated as "no signal available" there, which
        previously meant "always alive").

        all or nothing. If any step raises (or the call is cancelled),
        everything this call created is undone before the error propagates:
        consumers already started are cancelled, the worker pool, batch
        publisher and heartbeat are stopped, and both connections are closed.
        ``start()`` can then simply be called again.

        a refused login or vhost, or a TLS verification failure, raises a
        :class:`~rabbitkit.core.errors.PermanentConnectionError` at once
        instead of retrying.
        """
        if self._started:
            return
        try:
            await self._start_unguarded(worker_config, install_signal_handlers=install_signal_handlers)
        except BaseException:
            await self._abort_failed_start()
            raise

    async def _abort_failed_start(self) -> None:
        """Undo a ``start()`` that raised part-way. Best effort and bounded."""
        self._restore_signal_handlers()
        if self._heartbeat_task is not None:
            self._heartbeat_task.cancel()
            with contextlib.suppress(BaseException):
                await self._heartbeat_task
            self._heartbeat_task = None
        transport, self._transport = self._transport, None
        bound = self._config.connection.socket_timeout
        if transport is not None:
            for route in self._registry.routes:
                tag = route.consumer_tag
                if tag:
                    with contextlib.suppress(Exception):
                        async with asyncio.timeout(bound):
                            await transport.cancel_consumer(tag)
                    route.runtime_state.consumer_tag = None
        if self._worker_pool is not None:
            pool, self._worker_pool = self._worker_pool, None
            with contextlib.suppress(Exception):
                await pool.stop(timeout=0)
        # Handlers of consumers that started before the failure: cancel and
        # nack them now (an immediate drain deadline).
        with contextlib.suppress(Exception):
            await self._wait_in_flight(time.monotonic())
        if self._batch_publisher is not None:
            batch, self._batch_publisher = self._batch_publisher, None
            with contextlib.suppress(Exception):
                async with asyncio.timeout(bound):
                    await batch.stop()
        if transport is not None:
            with contextlib.suppress(Exception):
                async with asyncio.timeout(bound):
                    await transport.disconnect()
            # disconnect() is a no-op unless connect() finished; connect()
            # cleans up after itself, this covers a connect() that succeeded.
        self._started = False
        self._set_lifecycle_gauges(connected=False)

    async def _start_unguarded(self, worker_config: WorkerConfig | None, *, install_signal_handlers: bool) -> None:
        self.last_heartbeat = time.monotonic()

        # Configure structured logging if enabled
        if self._config.logging is not None:
            from rabbitkit.core.logging import configure_structlog

            configure_structlog(self._config.logging, override_existing=self._config.logging.override_existing)

        # SocketConfig is sync-only: pika accepts tcp_options, but
        # aio-pika/aiormq exposes no socket-tuning knobs, and applying
        # setsockopt to the live socket wouldn't survive connect_robust's
        # automatic reconnects (each reconnect is a fresh, untuned socket).
        # Warn instead of silently ignoring a config the user set.
        if self._config.socket != SocketConfig():
            import warnings

            warnings.warn(
                "RabbitConfig.socket (SocketConfig) is not applied by AsyncBroker: "
                "aio-pika manages its own sockets and provides no TCP-tuning "
                "options, and per-socket tuning would be silently lost on every "
                "automatic reconnect. SocketConfig only affects SyncBroker; tune "
                "the async side via ConnectionConfig (heartbeat, timeouts) or at "
                "the OS level.",
                RuntimeWarning,
                stacklevel=2,
            )

        # Create transport
        self._transport = AsyncTransportImpl(
            connection_config=self._config.connection,
            security_config=self._config.security,
            pool_config=self._config.pool,
            topology_mode=self._config.topology_mode,
            confirm_delivery=self._config.publisher.confirm_delivery,
            confirm_timeout=self._config.publisher.confirm_timeout,
            on_topology_conflict=self._config.safety.on_topology_conflict,
            max_in_flight_bytes=self._config.publisher.max_in_flight_bytes,
        )
        self._publish_closed = False
        self._transport.on_connection_failed(self._on_connection_failed)
        # Before connect(), so the connection-up events and the first
        # channels are counted too.
        self._wire_reconnect_metric()

        await self._transport.connect()

        # Wire an opt-in FlowController's blocked/unblocked callbacks to the
        # transport now that it exists (C-6).
        if self._flow_controller is not None:
            self._transport.on_blocked(self._flow_controller.on_blocked)
            self._transport.on_unblocked(self._flow_controller.on_unblocked)

        # M-P5: warn when confirms are on and the publisher channel pool is
        # small relative to expected concurrency (default unchanged).
        if self._config.publisher.confirm_delivery:
            pool_size = self._config.pool.channel_pool_size
            # Publisher concurrency ~ worker_count (handlers that publish) or 1.
            expected = worker_config.worker_count if worker_config and worker_config.worker_count > 1 else 1
            if pool_size < max(4, expected):
                import warnings

                warnings.warn(
                    f"confirm_delivery=True with channel_pool_size={pool_size} "
                    f"(expected publisher concurrency ~{expected}). Concurrent confirms "
                    "are capped by the pool size; increase PoolConfig.channel_pool_size "
                    "if publish throughput matters.",
                    RuntimeWarning,
                    stacklevel=2,
                )

        # Start batch publisher if configured (must come before topology so
        # the flush task is alive when the first publish arrives).
        if self._batch_config is not None:
            import dataclasses
            import warnings

            from rabbitkit.async_.batch import AsyncBatchPublisher

            batch_cfg = self._batch_config
            pool_size = self._config.pool.channel_pool_size
            if batch_cfg.flush_workers == 0:
                # Auto-compute workers but cap at half the pool so at least
                # half the channels remain available for retry/direct publishes.
                # Batch workers hold their channels permanently; exhausting the
                # pool deadlocks any non-batch transport.publish() call (e.g. retry).
                auto = min(16, max(1, batch_cfg.max_in_flight // batch_cfg.batch_size))
                safe = min(auto, max(1, pool_size // 2))
                batch_cfg = dataclasses.replace(batch_cfg, flush_workers=safe)
            elif batch_cfg.flush_workers > pool_size // 2:
                warnings.warn(
                    f"BatchPublishConfig.flush_workers={batch_cfg.flush_workers} > "
                    f"channel_pool_size({pool_size}) // 2. Batch workers hold pool "
                    "channels permanently; retry/direct publish calls may exhaust "
                    "the remaining slots and deadlock. "
                    "Increase PoolConfig.channel_pool_size to at least flush_workers * 2.",
                    RuntimeWarning,
                    stacklevel=2,
                )
            self._batch_publisher = AsyncBatchPublisher(
                self._transport,
                batch_cfg,
                admission_timeout=self._config.pool.channel_acquire_timeout,
                confirm_timeout=self._config.publisher.confirm_timeout,
                byte_limiter=self._transport.byte_limiter,
            )
            await self._batch_publisher.start()

        # Declare topology
        await self._declare_topology()
        self._notify_passive_only()

        # Install RetryMiddleware on retry-enabled routes (topology alone does
        # not retry — the middleware routes failures into the delay queues).
        self._wire_retry_middleware()

        # Create worker pool if requested
        if worker_config is not None and worker_config.worker_count > 1:
            # Warn if worker_count exceeds channel_pool_size — all workers
            # publishing simultaneously will exhaust the channel pool and
            # block until acquire_timeout, risking deadlock under load.
            if worker_config.worker_count > self._config.pool.channel_pool_size:
                import warnings

                warnings.warn(
                    f"worker_count={worker_config.worker_count} exceeds "
                    f"channel_pool_size={self._config.pool.channel_pool_size}. "
                    "Concurrent publishes may exhaust the channel pool and deadlock. "
                    "Increase PoolConfig.channel_pool_size to at least worker_count.",
                    RuntimeWarning,
                    stacklevel=2,
                )
            # Override prefetch_count if prefetch_per_worker is set
            if worker_config.prefetch_per_worker is not None:
                self._consumer_config = replace(
                    self._config.consumer,
                    prefetch_count=worker_config.worker_count * worker_config.prefetch_per_worker,
                )
            self._worker_pool = AsyncWorkerPool(config=worker_config)
            self._worker_pool.start()

        # Start consuming
        for route in self._registry.routes:
            await self._start_consumer(route)

        # L14: periodic liveness heartbeat -- keeps a healthy, message-idle
        # consumer from going stale between deliveries. See _heartbeat_loop.
        self._heartbeat_task = asyncio.ensure_future(self._heartbeat_loop())

        self._started = True
        self._set_lifecycle_gauges(connected=True)
        logger.info(
            "AsyncBroker started with %d routes",
            len(self._registry.routes),
        )

        # H11: clear any shutdown request left over from a previous
        # start()/stop() cycle so run() doesn't return immediately.
        self._shutdown_event.clear()

        if install_signal_handlers:
            self._install_signal_handlers()

    async def run(self, worker_config: WorkerConfig | None = None) -> None:
        """Start, wait for a shutdown signal, then stop (H11).

        ``await broker.start()`` alone installs signal handlers whose drain is
        fire-and-forget — nothing joins the ``stop()`` task they create, so
        whether in-flight messages actually finish draining depends on
        incidental event-loop lifetime (e.g. it can be cut short by
        ``asyncio.run()`` cancelling outstanding tasks once the awaited
        coroutine returns). ``run()`` is the direct-use equivalent of
        ``RabbitApp.run_async()``: it does not return until the drain
        triggered by SIGINT/SIGTERM (or :meth:`request_shutdown`) has fully
        completed, so awaiting it end-to-end guarantees in-flight messages are
        settled before the process exits::

            broker = AsyncBroker(config)

            @broker.subscriber(queue="orders")
            async def handle_order(body: bytes) -> None: ...

            asyncio.run(broker.run())

        Use plain ``start()``/``stop()`` instead when an outer lifecycle
        manager (``RabbitApp``) owns the run loop.
        """
        await self.start(worker_config=worker_config)
        self._run_waiting = True
        try:
            await self._shutdown_event.wait()
        finally:
            self._run_waiting = False
            await self.stop()
        failure = self._connection_failure()
        if failure is not None:
            raise failure

    def _connection_failure(self) -> TerminalConnectionError | None:
        transport = self._transport
        failure = getattr(transport, "connection_failure", None) if transport is not None else None
        return failure if isinstance(failure, TerminalConnectionError) else None

    def _on_connection_failed(self, error: TerminalConnectionError) -> None:
        """A connection stopped reconnecting for good after startup.

        The broker stays started (``stop()`` still drains and closes), but
        readiness and liveness go false. Under :meth:`run` this also ends the
        run: it stops the broker and raises *error*, so the process exits and
        its supervisor restarts it.
        """
        logger.critical(
            "RabbitMQ connection failed for good (%s); readiness and liveness are now false: %s",
            error.reason,
            error,
        )
        self._set_lifecycle_gauges(connected=False)
        if self._run_waiting:
            self._shutdown_event.set()

    def _install_signal_handlers(self) -> None:
        """Install SIGINT/SIGTERM handlers that drain via stop() (H-SRE5).

        Prefers ``loop.add_signal_handler``; falls back to ``signal.signal`` on
        platforms/threads where the loop API is unavailable. Idempotent.

        an embedding application's handlers are not clobbered.

        * The Python-level handler in place (``signal.getsignal``) is captured
          and put back by ``stop()``. A custom one (anything but the default,
          ``SIG_DFL`` or ``asyncio.run()``'s own SIGINT handler) is replaced
          for the broker's lifetime, with a WARNING.
        * A handler registered with ``loop.add_signal_handler`` cannot be read
          back through asyncio's public API, so it could not be restored.
          The broker leaves such a signal alone (WARNING): the application's
          handler stays in charge and should call ``broker.request_shutdown()``
          or ``await broker.stop()``.

        Embedding applications should pass ``install_signal_handlers=False``.
        """
        try:
            loop = asyncio.get_running_loop()
        except RuntimeError:  # pragma: no cover
            return  # no running loop - nothing to install
        self._loop = loop
        for sig in (signal.SIGINT, signal.SIGTERM):
            if sig in self._signal_prev or sig in self._original_handlers:
                continue  # already ours
            prev = signal.getsignal(sig)
            if _is_loop_signal_handler(prev):
                logger.warning(
                    "AsyncBroker: an asyncio handler for %s is already installed (e.g. by the "
                    "application or RabbitApp); not replacing it, because asyncio cannot hand it back "
                    "after stop(). That handler should call broker.request_shutdown() or await "
                    "broker.stop(). Pass start(install_signal_handlers=False) to silence this.",
                    sig.name,
                )
                continue
            if not _is_default_signal_handler(sig, prev):
                logger.warning(
                    "AsyncBroker: replacing the existing %s handler %r until stop(), which restores it. "
                    "Pass start(install_signal_handlers=False) if the application owns signal handling.",
                    sig.name,
                    prev,
                )
            try:
                loop.add_signal_handler(sig, self._on_signal)
            except (NotImplementedError, RuntimeError, ValueError):  # pragma: no cover - Windows / non-main thread
                try:  # pragma: no cover
                    self._original_handlers[sig] = signal.signal(sig, self._on_signal_sync)  # pragma: no cover
                except (ValueError, OSError):  # pragma: no cover - not main thread
                    pass
                continue  # pragma: no cover
            self._signal_prev[sig] = prev
            self._installed_loop_handlers = True

    def _owns_loop_signal(self, loop: asyncio.AbstractEventLoop, sig: signal.Signals) -> bool:
        """Whether *loop*'s handler for *sig* is still this broker's.

        Reads asyncio's private handler table when it exists (the standard
        Unix loop), so an application handler installed after ``start()`` is
        not removed by ``stop()``. Without it (e.g. uvloop) the broker
        assumes the handler is still its own, as before.
        """
        return loop_signal_handler_is(loop, sig, self._on_signal)

    def _trigger_shutdown(self) -> None:
        """Set the shutdown event so an in-progress ``run()`` joins the drain
        (H11). If nothing is awaiting it via ``run()``, falls back to the
        pre-H11 fire-and-forget ``stop()`` task so bare ``await
        broker.start()`` usage still drains on signal.
        """
        self._shutdown_event.set()
        if not self._run_waiting and self._loop is not None:
            self._loop.create_task(self.stop())

    def _on_signal(self) -> None:
        logger.info("Received shutdown signal; initiating graceful drain")
        self._trigger_shutdown()
        if self.on_app_shutdown is not None:
            try:
                self.on_app_shutdown()
            except Exception:  # pragma: no cover - never block shutdown on the callback
                logger.warning("on_app_shutdown callback raised", exc_info=True)

    def _on_signal_sync(self, signum: int, frame: Any) -> None:  # pragma: no cover
        logger.info("Received shutdown signal %d", signum)
        if self._loop is not None:
            self._loop.call_soon_threadsafe(self._trigger_shutdown)
        if self.on_app_shutdown is not None:
            try:
                self.on_app_shutdown()
            except Exception:  # pragma: no cover
                logger.warning("on_app_shutdown callback raised", exc_info=True)

    def request_shutdown(self) -> None:
        """Request a graceful shutdown from any context — e.g. a failing
        health check or a management command (H11). Equivalent to receiving
        SIGINT/SIGTERM: if ``run()`` is awaiting shutdown it performs the
        drain; otherwise this schedules a fire-and-forget ``stop()``.
        """
        self._trigger_shutdown()

    def _restore_signal_handlers(self) -> None:
        """Remove this broker's handlers and put back what was there before."""
        loop = self._loop
        for sig, prev in self._signal_prev.items():
            if loop is None or not self._owns_loop_signal(loop, sig):
                logger.info("AsyncBroker: %s handler was replaced after start(); leaving it in place", sig.name)
                continue
            try:
                loop.remove_signal_handler(sig)
            except (NotImplementedError, RuntimeError, ValueError):  # pragma: no cover
                continue
            if prev is None:
                continue  # installed outside Python: nothing we can put back
            try:
                signal.signal(sig, prev)
            except (ValueError, OSError, TypeError):
                logger.warning("AsyncBroker: could not restore the previous %s handler", sig.name, exc_info=True)
        self._signal_prev.clear()
        self._installed_loop_handlers = False
        for sig, prev in self._original_handlers.items():  # pragma: no cover
            try:  # pragma: no cover
                signal.signal(sig, prev)  # pragma: no cover
            except (ValueError, OSError):  # pragma: no cover
                pass  # pragma: no cover
        self._original_handlers.clear()

    async def _queue_exists_for_guard(self, queue: str) -> bool:
        transport = self._transport
        if transport is None:
            return False
        return bool(await transport.queue_exists(queue))

    async def _wait_in_flight(self, deadline: float | None) -> None:
        cond = self._ensure_inflight_cond()
        async with cond:
            if self._in_flight == 0:
                return
            while self._in_flight > 0:
                if deadline is None:
                    await cond.wait()
                    continue
                remaining = max(0.0, deadline - time.monotonic())
                if remaining <= 0:
                    break
                # R-timeout: use asyncio.timeout instead of asyncio.wait_for to
                # avoid the wrapper-task overhead and let the wait be cancelled
                # cleanly when the deadline expires.
                try:
                    async with asyncio.timeout(remaining):
                        await cond.wait()
                except TimeoutError:
                    break
        # Deadline elapsed with handlers still running: cancel + nack them
        # explicitly (delivery-tag logged) instead of silently abandoning
        # them unacked -- matches AsyncWorkerPool.stop()'s behavior for the
        # pooled path. Outside the `async with cond:` block since we're no
        # longer touching `_in_flight`/the condition itself here, and
        # cancelling a task can re-enter this broker (e.g. its `finally`
        # decrementing `_in_flight`), which would deadlock re-acquiring cond.
        if self._in_flight > 0:
            logger.warning(
                "AsyncBroker.stop: %d in-flight handler(s) still running after "
                "graceful drain deadline; disconnecting anyway",
                self._in_flight,
            )
            tasks = dict(self._inflight_tasks)
            for task in tasks:
                task.cancel()
            if tasks:
                # bounded even when a handler swallows CancelledError
                # (an unbounded gather here let stop() overrun graceful_timeout
                # by however long the misbehaving handler kept running).
                _done, still_running = await asyncio.wait(tasks, timeout=_CANCEL_JOIN_TIMEOUT)
                for task in still_running:
                    stuck = tasks[task]
                    logger.error(
                        "AsyncBroker.stop: handler for delivery_tag=%s message_id=%s ignored cancellation "
                        "for %.1fs; abandoning it (it may still run, and its side effects may still "
                        "happen). The delivery is nacked for redelivery below.",
                        stuck.delivery_tag,
                        stuck.message_id,
                        _CANCEL_JOIN_TIMEOUT,
                    )
            for message in tasks.values():
                if message.is_settled:
                    continue  # handler reached its own ack/nack before being cut off
                logger.warning(
                    "AsyncBroker.stop: handler for delivery_tag=%s message_id=%s did not "
                    "complete within graceful_timeout; abandoning (task cancelled) and "
                    "nacking for redelivery — ensure handlers are idempotent under "
                    "at-least-once delivery",
                    message.delivery_tag,
                    message.message_id,
                )
                try:
                    await message.nack_async(requeue=True)
                except Exception:
                    logger.warning("nack on abandoned handler's message raised", exc_info=True)

    @staticmethod
    def _remaining(deadline: float | None) -> float | None:
        return None if deadline is None else max(0.0, deadline - time.monotonic())

    async def stop(self, timeout: float | None = None) -> None:
        """Stop the broker - cancel consumers, drain pool, drain in-flight, disconnect.

        ``timeout`` defaults to ``ConsumerConfig.graceful_timeout`` (C-2). The
        whole sequence is bounded by an overall deadline.

        C5: consumers are cancelled FIRST, before the worker pool is drained.
        Draining the pool before cancelling left the consumer active for the
        entire (potentially graceful_timeout-long) drain wait — a message
        delivered in that window was submitted via ``AsyncWorkerPool.submit()``,
        which creates a task unconditionally (it never checks ``_running``) and
        adds it to ``_tasks``. If that submit happens after ``.stop()`` already
        cleared ``_tasks``, the new task is never awaited by anything — an
        orphaned background task racing the event loop's shutdown, with the
        message never cleanly settled before ``disconnect()``, so it is
        redelivered (duplicate-processing risk) on the next connection.
        Cancelling first stops new deliveries outright, so the pool only ever
        drains work that was already in flight.
        """
        if not self._started:
            return

        self._restore_signal_handlers()

        effective = timeout if timeout is not None else self._consumer_config.graceful_timeout
        deadline = None if effective is None else time.monotonic() + effective

        # Stream routes: from here a nack/reject hands a delivery back (pool
        # hand-back, cancelled handler), so its offset must not advance.
        for tracker in self._stream_trackers.values():
            tracker.begin_shutdown()

        # L14: stop the periodic heartbeat first, alongside cancelling consumers.
        if self._heartbeat_task is not None:
            self._heartbeat_task.cancel()
            with contextlib.suppress(asyncio.CancelledError):
                await self._heartbeat_task
            self._heartbeat_task = None

        # Cancel all consumers FIRST — stop new deliveries before draining
        # anything, so nothing new arrives while the pool/in-flight drain runs.
        if self._transport is None:  # pragma: no cover — defensive (assert was stripped under -O)
            return
        # Every step below is bounded by the overall deadline, including the
        # ones that talk to the broker: during a partition a cancel or a close
        # is never answered, and stop() used to wait for the network to heal.
        for route in self._registry.routes:
            if route.consumer_tag:
                await self._transport.cancel_consumer(route.consumer_tag, timeout=self._remaining(deadline))

        # Drain the worker pool (let in-flight pooled tasks finish), bounded by
        # the outer deadline.
        if self._worker_pool is not None:
            remaining = None if deadline is None else max(0.0, deadline - time.monotonic())
            await self._worker_pool.stop(timeout=remaining)
            self._worker_pool = None

        # Drain inline in-flight handlers (C-2).
        await self._wait_in_flight(deadline)

        # Every handler has settled or been handed back: commit the stream
        # offsets, so the next start resumes right after the last processed one.
        await self._flush_stream_offsets(deadline)

        # Publisher shutdown. After the consumer drain, so a handler
        # finishing inside the grace period can still publish its result or
        # retry handoff. Then, within what is left of the deadline:
        # 1. close admission (publish() now raises BrokerNotStartedError and
        #    never reconnects); 2. flush the batch queue and wait for
        #    in-flight confirms; 3. resolve the rest (queued: NOT_SENT,
        #    on the wire: UNKNOWN) and release every waiter; then disconnect.
        self._publish_closed = True
        if self._batch_publisher is not None:
            await self._batch_publisher.stop(timeout=self._remaining(deadline))
            self._batch_publisher = None
        await self._transport.close_publishing(timeout=self._remaining(deadline))

        # Close RPC client if used
        if self._rpc_client is not None:
            with contextlib.suppress(TimeoutError):
                async with asyncio.timeout(self._remaining(deadline)):
                    await self._rpc_client.close()
            self._rpc_client = None

        # Disconnect
        if self._transport:
            await self._transport.disconnect(timeout=self._remaining(deadline))

        self._started = False
        self._set_lifecycle_gauges(connected=False)
        logger.info("AsyncBroker stopped")

    # ── Publishing ────────────────────────────────────────────────────────

    async def publish(
        self,
        envelope: MessageEnvelope | None = None,
        *,
        exchange: str = "",
        routing_key: str = "",
        body: bytes | str | dict[str, Any] | None = None,
        headers: dict[str, Any] | None = None,
        content_type: str = "application/json",
        correlation_id: str | None = None,
        reply_to: str | None = None,
        message_id: str | None = None,
        timeout: float | None = None,
    ) -> PublishOutcome:
        """Publish a message.

        Accepts either a pre-built ``MessageEnvelope`` or individual kwargs::

            # Envelope form (full control):
            await broker.publish(MessageEnvelope(routing_key="orders.created", body=b"..."))

            # Kwargs form (convenient):
            await broker.publish(
                exchange="orders",
                routing_key="orders.created",
                body={"order_id": 123},
                headers={"x-tenant": "acme"},
            )

        When ``body`` is a dict or str it is JSON-encoded automatically.

        When an opt-in ``FlowController`` is configured (``broker.flow_controller
        = fc``), a publish slot is acquired/released around the transport publish
        so backpressure/rate-limiting applies to the hot path. Without a
        controller this is a plain pass-through.

        When ``middlewares=[...]`` was passed to the constructor, each
        middleware's ``publish_scope_async`` wraps this call (e.g.
        ``SigningMiddleware`` signs the envelope) — see ``publish_middlewares``.
        Middleware wraps OUTSIDE both flow control and batching, so a
        middleware-transformed envelope is what gets rate-limited/batched, and
        what actually reaches the wire.

        ``message_id`` (kwargs form only) sets the AMQP message id instead of
        a fresh uuid4, so an application can republish the SAME logical
        message after an ``UNKNOWN`` outcome and let consumers deduplicate.
        With an envelope, set ``MessageEnvelope.message_id`` instead.

        ``timeout`` bounds this call end to end: admission (flow control,
        byte budget, a free channel), send and confirm. On expiry the outcome
        is ``NOT_SENT`` (``admission_timeout``) if nothing was sent, else
        ``TIMEOUT`` (``publish_timeout``), which is an unknown outcome.
        ``None`` keeps the configured bounds (``channel_acquire_timeout``,
        ``confirm_timeout``).

        Outcomes are returned, not raised (see :class:`PublishStatus`).
        Raises ``BrokerNotStartedError`` before ``start()`` and once
        ``stop()`` has begun closing the publisher — a publish never
        reconnects a stopped broker.
        """
        if timeout is not None and not timeout > 0:
            raise ValueError(f"publish timeout must be > 0, got {timeout}")
        if envelope is not None and message_id is not None:
            raise ValueError("message_id applies to the kwargs form; set MessageEnvelope.message_id instead")
        if envelope is None:
            import json as _json

            if body is None:
                raw_body = b""
            elif isinstance(body, bytes):
                raw_body = body
            elif isinstance(body, str):
                raw_body = body.encode()
            else:
                raw_body = _json.dumps(body).encode()
            # M2: honor PublisherConfig defaults for the kwargs form (they were
            # previously dead config). Envelope-form callers keep full control.
            envelope = MessageEnvelope(
                routing_key=routing_key,
                body=raw_body,
                exchange=exchange,
                headers=headers or {},
                content_type=content_type,
                correlation_id=correlation_id,
                reply_to=reply_to,
                mandatory=self._config.publisher.mandatory,
                delivery_mode=2 if self._config.publisher.persistent else 1,
            )
            if message_id is not None:
                envelope = replace(envelope, message_id=message_id)

        # an application publish cannot carry rabbitkit's retry/DLQ
        # bookkeeping headers (opt-in; the library's own republishes bypass this).
        if self._reserved_header_stripper is not None:
            envelope = self._reserved_header_stripper(envelope)

        # M10: reject oversized bodies at publish time (see sync broker).
        max_bytes = self._config.publisher.max_message_bytes
        if max_bytes and len(envelope.body) > max_bytes:
            raise MessageTooLargeError(
                f"Message body ({len(envelope.body)} bytes) exceeds "
                f"PublisherConfig.max_message_bytes ({max_bytes}). Large messages are a "
                "RabbitMQ anti-pattern — store the payload externally and publish a "
                "reference, or raise the limit if this is intentional."
            )

        if self._transport is None:
            raise BrokerNotStartedError("Broker not started. Call start() first.")
        if self._publish_closed:
            raise BrokerNotStartedError("Broker is stopping or stopped; publishing is closed. Call start() first.")

        publish_fn = self._batch_publisher.publish if self._batch_publisher is not None else self._transport.publish
        if timeout is None and self._flow_controller is None and not self._publish_middlewares:
            # Hot path: nothing to wrap, so skip the per-call closures and the
            # extra coroutine layers below (measurable at ~10k msg/s).
            return await publish_fn(envelope)  # type: ignore[no-any-return]
        loop = asyncio.get_running_loop()
        deadline = None if timeout is None else loop.time() + timeout

        async def send(env: MessageEnvelope) -> PublishOutcome:
            if deadline is None:
                return await publish_fn(env)  # type: ignore[no-any-return]
            remaining = deadline - loop.time()
            if remaining <= 0:
                return _not_sent(env, PublishReason.ADMISSION_TIMEOUT)
            return await publish_fn(env, timeout=remaining)  # type: ignore[no-any-return]

        async def do_publish(env: MessageEnvelope) -> PublishOutcome:
            fc = self._flow_controller
            if fc is not None:
                if deadline is None:
                    acquired = await fc.acquire_async()
                else:
                    acquired = await fc.acquire_async(timeout=max(0.0, deadline - loop.time()))
                if not acquired:
                    return _not_sent(
                        env,
                        PublishReason.BACKPRESSURE_DROPPED,
                        BackpressureError("publish dropped by backpressure policy"),
                    )
                try:
                    return await send(env)
                finally:
                    await fc.release_async()
            return await send(env)

        if self._publish_middlewares:
            chain = self._pipeline.compose_broker_publish_async(self._publish_middlewares)
            outcome: PublishOutcome = await chain(envelope, do_publish)
            return outcome
        return await do_publish(envelope)

    # ── Bulk operations: metrics plumbing (plan §11) ─────────────────────

    def _bulk_metrics(self) -> tuple[Any, Any] | None:
        """``(collector, MetricsConfig)`` from the first MetricsMiddleware with a
        collector — publish-middlewares first, then any route. None = no metrics."""
        from rabbitkit.middleware.metrics import MetricsMiddleware

        candidates: list[Any] = list(self._publish_middlewares)
        for route in self._registry.routes:
            candidates.extend(route.route_middlewares)
        for mw in candidates:
            if isinstance(mw, MetricsMiddleware) and mw.collector is not None:
                return mw.collector, mw.config
        return None

    def _record_bulk_item(self, item: BulkPublishItem) -> None:
        found = self._bulk_metrics()
        if found is None:
            return
        collector, cfg = found
        collector.inc_counter(cfg.bulk_publish_items_total, {"status": item.status.value, "reason": item.reason})

    def _record_bulk_batch(self, size: int) -> None:
        found = self._bulk_metrics()
        if found is None:
            return
        collector, cfg = found
        collector.observe_histogram(cfg.bulk_publish_batch_size, {}, float(size))

    def _settlement_item_hook(self, action: SettlementAction) -> Callable[[SettlementItem], None] | None:
        found = self._bulk_metrics()
        if found is None:
            return None
        collector, cfg = found

        def _hook(item: SettlementItem) -> None:
            collector.inc_counter(cfg.settlement_items_total, {"action": action.value, "status": item.status.value})

        return _hook

    def _set_lifecycle_gauges(self, *, connected: bool) -> None:
        """Emit the declared-but-previously-missing lifecycle gauges:
        ``broker_connected``, ``consumer_active`` and ``worker_pool_pending``.

        ``connected=True`` (start) then samples every broker gauge, so
        ``broker_connected`` reflects the connections' real state; it follows
        drops and reconnects from then on. ``connected=False`` (stop,
        failed start, terminal failure) zeroes the sampled gauges.
        """
        found = self._bulk_metrics()
        if found is None:
            return
        collector, cfg = found
        set_gauge = getattr(collector, "set_gauge", None)
        if set_gauge is None:
            return
        set_gauge(cfg.broker_connected, {}, 1.0 if connected else 0.0)
        set_gauge(cfg.consumer_active, {}, float(len(self._registry.routes)) if connected else 0.0)
        pool = self._worker_pool
        set_gauge(cfg.worker_pool_pending, {}, float(pool.pending_count) if pool is not None else 0.0)
        metrics = self._broker_metrics
        if metrics is None:
            return
        if connected:
            self._sample_metrics()
        else:
            metrics.stopped(route.queue.name for route in self._registry.routes)

    def _sample_metrics(self) -> None:
        """Refresh the sampled broker gauges: connection state, open
        channels, publishes and bytes in flight, publisher channels in use,
        blocked state, per-route consuming and the worker-pool backlog. Runs
        at start and on every heartbeat tick (``_HEARTBEAT_INTERVAL``), never
        on the publish or consume hot path."""
        metrics, transport = self._broker_metrics, self._transport
        if metrics is None or transport is None:
            return
        try:
            metrics.set_states(transport.connection_states())
            limiter = transport.byte_limiter
            metrics.sample(
                channels_active=transport.channels_active,
                publish_in_flight=transport.publishes_in_flight,
                publish_in_flight_bytes=limiter.used if limiter is not None else None,
                publish_channels_in_use=transport.publish_channels_in_use,
                connection_blocked=transport.is_blocked,
                connection_blocked_reason=transport.blocked_reason,
                consuming={
                    route.queue.name: bool(route.consumer_tag) and not route.runtime_state.consumer_cancelled
                    for route in self._registry.routes
                },
            )
            pool = self._worker_pool
            if pool is not None:
                metrics.sample_worker_pool(pool.pending_count)
        except Exception:  # a metrics sample must never stop the heartbeat loop
            logger.warning("Sampling broker metrics failed", exc_info=True)

    def preflight(
        self,
        profile: ReliabilityProfile | str = ReliabilityProfile.STANDARD,
        *,
        management_client: Any | None = None,
        vhost: str = "/",
    ) -> PreflightReport:
        """Verify reliability-profile prerequisites for this broker's config
        and registered routes (plan §9). Broker-side policy checks need a
        read-only management client; without one they are reported
        ``UNVERIFIED`` — never silently green. Pure inspection; no I/O on
        the AMQP connection and no policy mutation."""
        return run_preflight(
            self._config,
            profile,
            routes=self._registry.routes,
            management_client=management_client,
            vhost=vhost,
        )

    # ── Bulk publishing (plan §7) ────────────────────────────────────────

    def iter_publish(
        self,
        envelopes: Iterable[MessageEnvelope] | AsyncIterator[MessageEnvelope],
        options: BulkPublishOptions | None = None,
    ) -> AsyncIterator[BulkPublishItem]:
        """Publish a (possibly unbounded, possibly async) iterable with bounded
        concurrency, yielding one :class:`~rabbitkit.core.bulk.BulkPublishItem`
        per input as it settles — in COMPLETION order (use ``item.index``).

        Every item goes through the SAME path as :meth:`publish` — publish
        middlewares, flow control, size limit, the batch publisher when one
        is configured, the transport — so single and bulk publishing share
        every safeguard. Admission is bounded by ``options.max_in_flight``
        and ``options.max_buffer_bytes``; waiting by ``admission_timeout``;
        the whole operation by ``overall_timeout`` (in-flight items past the
        deadline are reported ``UNKNOWN``, never dropped).
        """
        if self._transport is None or self._publish_closed:
            raise BrokerNotStartedError("Broker not started. Call start() first.")
        opts = options or BulkPublishOptions()
        # Without a batch publisher every in-flight publish holds one pooled
        # channel, so admitting more than ``PoolConfig.channel_pool_size`` only
        # queues callers on the pool (with "pool exhausted" warnings) instead of
        # adding concurrency. Cap the effective in-flight bound to the pool.
        # With AsyncBatchPublisher configured, publishes share channels and
        # the batch queue has its own bound, so the caller's value stands.
        if self._batch_publisher is None:
            pool_size = self._config.pool.channel_pool_size
            if opts.max_in_flight > pool_size:
                opts = replace(opts, max_in_flight=pool_size)
        preparer = PublishPreparer(
            max_message_bytes=self._config.publisher.max_message_bytes,
            max_buffer_bytes=opts.max_buffer_bytes,
        )
        return iter_publish_async(
            envelopes,
            self.publish,
            options=opts,
            preparer=preparer,
            on_item=self._record_bulk_item,
        )

    async def publish_many(
        self,
        envelopes: Sequence[MessageEnvelope],
        options: BulkPublishOptions | None = None,
    ) -> BulkPublishResult:
        """Publish a bounded collection concurrently and return input-ordered
        per-item outcomes.

        Never raises for a failed item — inspect ``result.items`` (or call
        ``result.raise_for_status()``). Raises ``ValueError`` before publishing
        anything if ``len(envelopes)`` exceeds ``options.max_items``; use
        :meth:`iter_publish` for streams. ``UNKNOWN`` items may have reached
        the broker: reconcile by ``message_id``/``attempt_id`` with stable IDs
        and deduplication — do not blindly replay the batch.
        """
        opts = options or BulkPublishOptions()
        if len(envelopes) > opts.max_items:
            raise ValueError(
                f"publish_many received {len(envelopes)} envelopes, more than BulkPublishOptions.max_items "
                f"({opts.max_items}); use iter_publish() for large or unbounded inputs."
            )
        started = datetime.now(UTC)
        items: list[BulkPublishItem] = []
        async for item in self.iter_publish(envelopes, opts):
            items.append(item)
        self._record_bulk_batch(len(envelopes))
        return BulkPublishResult(
            items=tuple(sorted(items, key=lambda it: it.index)),
            started_at=started,
            finished_at=datetime.now(UTC),
        )

    # ── Selected settlement (plan §8) ────────────────────────────────────

    async def ack_many(self, messages: Iterable[RabbitMessage], *, fail_fast: bool = True) -> SettlementReport:
        """Ack exactly the given deliveries — each with its own ``multiple=False``
        frame. Never a cumulative ack: an unselected, still-running sibling on
        the same channel is untouched.

        Validation runs before any I/O: duplicates, already-settled messages,
        no-ack deliveries and STALE handles (channel rebuilt since delivery)
        are reported per item. With ``fail_fast=True`` (default) any problem
        aborts the whole call with every valid item ``NOT_ATTEMPTED``.

        The report says ``DISPATCHED``, not "confirmed" — RabbitMQ sends no
        acknowledgement for a consumer ack.
        """
        return await settle_many_async(
            messages,
            SettlementAction.ACK,
            fail_fast=fail_fast,
            on_item=self._settlement_item_hook(SettlementAction.ACK),
        )

    async def nack_many(
        self,
        messages: Iterable[RabbitMessage],
        *,
        requeue: bool = True,
        fail_fast: bool = True,
    ) -> SettlementReport:
        """Nack exactly the given deliveries (individually — see :meth:`ack_many`).

        ``requeue=False`` dead-letters (or, without a DLX, DISCARDS) each
        message; for ordinary handler failures prefer the retry/terminal
        path (``RetryConfig``) over raw nacks.
        """
        return await settle_many_async(
            messages,
            SettlementAction.NACK,
            requeue=requeue,
            fail_fast=fail_fast,
            on_item=self._settlement_item_hook(SettlementAction.NACK),
        )

    async def _flow_controlled_internal_publish(self, env: MessageEnvelope) -> PublishOutcome:
        """M18: async mirror of ``SyncBroker._flow_controlled_internal_publish``
        — see its docstring. Used as the ``publish_fn`` for ``RetryMiddleware``'s
        delay-queue republish and the pipeline's result/RPC-reply publish so
        the broker's ``FlowController`` (if configured) applies to these
        internal publishes too. Never lets ``BackpressureError`` escape as an
        exception — a blocked/dropped slot always resolves as a failed
        ``PublishOutcome`` so existing nack+requeue handling applies
        regardless of the configured ``on_blocked`` policy.
        """
        if self._transport is None:  # pragma: no cover — defensive; callers only run while consuming
            raise BrokerNotStartedError("Broker not started. Call start() first.")
        transport = self._transport
        fc = self._flow_controller
        if fc is None:
            return await transport.publish(env)  # type: ignore[no-any-return]
        try:
            acquired = await fc.acquire_async()
        except BackpressureError as exc:
            return _not_sent(env, PublishReason.BACKPRESSURE_DROPPED, exc)
        if not acquired:
            return _not_sent(
                env, PublishReason.BACKPRESSURE_DROPPED, BackpressureError("publish dropped by backpressure policy")
            )
        try:
            return await transport.publish(env)  # type: ignore[no-any-return]
        finally:
            await fc.release_async()

    async def request(
        self,
        routing_key: str,
        body: bytes,
        *,
        timeout: float = 5.0,
        exchange: str = "",
        headers: dict[str, Any] | None = None,
    ) -> RabbitMessage:
        """Send an RPC request and wait for a response.

        Lazily initializes an AsyncRPCClient on first call.
        The client is shared across calls and closed in stop().

        Args:
            routing_key: Target queue/routing key.
            body: Request body as bytes.
            timeout: Max seconds to wait for response.
            exchange: Exchange to publish to (default "").
            headers: Optional AMQP headers.

        Returns:
            RabbitMessage containing the response.

        Raises:
            RuntimeError: If broker is not started.
            RPCTimeoutError: If no response within timeout.
        """
        if self._transport is None:
            raise BrokerNotStartedError("Broker not started. Call start() first.")
        if self._rpc_client is None:
            from rabbitkit.rpc import AsyncRPCClient

            self._rpc_client = AsyncRPCClient(self._transport)
        return await self._rpc_client.call(routing_key, body, timeout=timeout, exchange=exchange, headers=headers)

    # ── Internal ──────────────────────────────────────────────────────────

    def _wire_retry_middleware(self) -> None:
        """Install ``RetryMiddleware`` on routes whose retry is enabled.

        ``_declare_topology`` declares the retry/DLQ *topology* (delay queues +
        source-queue DLX), but the ``RetryMiddleware`` that actually routes a
        failed message into the delay queues must also run in the route's
        middleware chain. Without it, ``retry=RetryConfig(...)`` would build the
        topology while transient failures ``nack(requeue=True)`` in a hot loop —
        the delay queues would never receive anything and ``max_retries`` would
        never be enforced. This wires both halves from the single retry switch
        (``RabbitConfig.retry`` / ``@subscriber(retry=...)``).

        Placed outer of ordinary user middlewares (e.g. ``TimeoutMiddleware``) so
        retry can classify and re-queue exceptions they raise, but inner of any
        ``ExceptionMiddleware`` (the documented true-outermost layer) — see
        :func:`rabbitkit.middleware.retry.retry_middleware_insertion_index`.

        Idempotent: routes that already carry a ``RetryMiddleware`` — supplied
        explicitly via ``middlewares=[...]`` or auto-wired on a previous start —
        are left untouched (no double-retry, no stacking on reconnect).
        """
        if self._transport is None:
            return

        from rabbitkit.middleware.metrics import MetricsMiddleware
        from rabbitkit.middleware.retry import (
            RetryMiddleware,
            retry_middleware_insertion_index,
            warn_retry_middleware_without_topology,
            warn_retry_without_confirms,
        )
        from rabbitkit.middleware.signing import check_signing_retry_conflict

        wired = False
        for route in self._registry.routes:
            retry_config = route.effective_retry_config(self._config.retry)
            has_retry_mw = any(isinstance(mw, RetryMiddleware) for mw in route.route_middlewares)
            if retry_config is None:
                if has_retry_mw:
                    # Half-configured: a RetryMiddleware runs but no retry topology
                    # was declared, so its delay-queue publishes target non-existent
                    # queues and are silently dropped. Surface it loudly.
                    warn_retry_middleware_without_topology(route.name)
                continue
            # H1: signing + retry destroys every retried message — fail fast.
            check_signing_retry_conflict(route.name, route.route_middlewares)
            if has_retry_mw:
                # User-constructed RetryMiddleware: inject the broker's
                # confirmed publish fn if none was passed (see sync broker).
                for mw in route.route_middlewares:
                    if isinstance(mw, RetryMiddleware):
                        mw.ensure_publish_fns(publish_async_fn=self._flow_controlled_internal_publish)
                continue
            # (No confirms warning for the RETRY context: retry envelopes are
            # published mandatory=True, which forces per-publish confirm mode
            # on both transports even when confirm_delivery=False — the
            # ack-after-confirmed-outcome invariant holds regardless.)
            index = retry_middleware_insertion_index(route.route_middlewares)
            # M2: if a MetricsMiddleware is already on this route, wire it into
            # RetryMiddleware too so messages_retried_total/dead_lettered_total
            # are observable (RetryMiddleware settles messages the pipeline
            # itself never sees settle, so it must record these itself).
            metrics_mw = next((mw for mw in route.route_middlewares if isinstance(mw, MetricsMiddleware)), None)
            route.route_middlewares.insert(
                index,
                RetryMiddleware(
                    retry_config,
                    publish_async_fn=self._flow_controlled_internal_publish,  # M18
                    metrics_collector=metrics_mw.collector if metrics_mw else None,
                    metrics_config=metrics_mw.config if metrics_mw else None,
                ),
            )
            wired = True

        if not self._config.publisher.confirm_delivery:
            for route in self._registry.routes:
                if route.result_publisher is not None:
                    warn_retry_without_confirms(route.name, context="result")  # M4

        if wired:
            # Drop any middleware chains cached before the retry mw was installed.
            self._pipeline.clear_caches()

    def _wire_reconnect_metric(self) -> None:
        """Wire the broker metrics (:class:`BrokerMetrics`) to the transport's
        hooks via the first ``MetricsMiddleware`` with a collector: publish
        middlewares first, then any route (a publish-only broker gets
        connection and channel metrics too). No-op without metrics.

        Wires ``reconnects_total`` like the sync broker. 0.14 removed
        it on a measurement that said aio-pika never fires
        ``reconnect_callbacks`` for a broker-closed connection; re-measured in
        0.19.2 (aio-pika 9.6.2 and 10.1.0), it does, once per connection and
        after the consumers are restored, and a real-broker test now covers it.

        ``on_reconnect`` fires for a broker-closed connection and whenever
        rabbitkit REPLACES a connection (a rebuilt publisher connection, a
        lazy re-create).
        """
        self._broker_metrics = None
        transport = self._transport
        if transport is None:
            return
        found = self._bulk_metrics()
        if found is None:
            return
        collector, cfg = found
        metrics = BrokerMetrics(collector, cfg, roles=("publisher", "consumer"))
        self._broker_metrics = metrics
        transport.on_reconnect(metrics.reconnected)
        transport.on_channel_opened(metrics.channel_opened)
        transport.on_channel_rebuilt(metrics.channel_rebuilt)
        transport.on_connection_state(metrics.connection_state)
        transport.on_reconnect_attempt(lambda attempt: metrics.reconnect_failed(attempt.role, attempt.error))
        transport.on_connection_failed(metrics.connection_failed)
        transport.on_blocked(lambda: metrics.blocked(True, transport.blocked_reason))
        transport.on_unblocked(lambda: metrics.blocked(False))
        transport.on_publish_outcome(metrics.publish_outcome)
        metrics.take_over_confirm_latency(
            [*self._publish_middlewares, *(mw for route in self._registry.routes for mw in route.route_middlewares)]
        )

    async def _declare_topology(self) -> None:
        """Declare exchanges, queues, and bindings for all routes."""
        if self._transport is None:
            return

        for route in self._registry.routes:
            # Declare exchange
            if route.exchange is not None:
                await self._transport.declare_exchange(route.exchange)

                # Exchange-to-exchange binding
                bind_kwargs = route.exchange.to_bind_kwargs()
                if bind_kwargs is not None:
                    await self._transport.bind_exchange(
                        destination=bind_kwargs["destination"],
                        source=bind_kwargs["source"],
                        routing_key=bind_kwargs["routing_key"],
                        arguments=bind_kwargs["arguments"],
                    )

            # Determine retry config early so source queue can include DLQ routing
            retry_config = route.effective_retry_config(self._config.retry)
            # C3: a route with no dead-letter path can reject(requeue=False)
            # (permanent errors, filter_fn, RejectMessage) and RabbitMQ would
            # DISCARD the message. Apply SafetyConfig.reject_without_dlx:
            # auto-provision "<queue>.dlq" (default), fail startup, or warn
            # and allow discard. Only under AUTO_DECLARE — in passive/manual
            # modes rabbitkit does not own the queue's arguments.
            safety_dlq_name: str | None = None
            if self._config.topology_mode is TopologyMode.AUTO_DECLARE:
                safety_dlq_name = route.resolve_safety_dlq(self._config.safety, self._config.retry)
            # A queue that IS another route's DLQ is terminal — consuming your
            # own DLQ is a legitimate pattern (inspect/replay consumers), and
            # auto-chaining more topology onto it (safety DLX injection, or
            # BROKER-DEFAULT retry inherited by the DLQ-consumer route) would
            # re-declare the DLQ with different arguments than the retry/
            # safety topology already declared it with — a 406 inequivalent-
            # arg startup failure, caught by the real-broker CI suite. An
            # EXPLICIT per-route retry= on a DLQ consumer still wins.
            is_anothers_dlq = any(
                other is not route and route.queue.name == f"{other.queue.name}.dlq" for other in self._registry.routes
            )
            if is_anothers_dlq:
                safety_dlq_name = None
                if route.retry_override is None:
                    retry_config = None  # don't inherit broker-default retry

            if retry_config is not None:
                retry_router = RetryRouter(retry_config)
                dlq_name = retry_router.get_dlq_name(route.queue.name)
                # Re-declare source queue with x-dead-letter fields so RabbitMQ
                # automatically routes nacked/rejected messages to the DLQ.
                import dataclasses

                source_queue = dataclasses.replace(
                    route.queue,
                    dead_letter_exchange="",
                    dead_letter_routing_key=dlq_name,
                )
            elif safety_dlq_name is not None:
                import dataclasses

                logger.info(
                    "Auto-provisioned DLQ %r for queue %r (reject_without_dlx=auto_provision)",
                    safety_dlq_name,
                    route.queue.name,
                )
                source_queue = dataclasses.replace(
                    route.queue,
                    dead_letter_exchange="",
                    dead_letter_routing_key=safety_dlq_name,
                )
            else:
                source_queue = route.queue

            self._dead_letter_guard.set_target(
                route.queue.name, source_queue.dead_letter_exchange, source_queue.dead_letter_routing_key
            )

            # Declare queue (with DLQ routing arguments if retry/safety DLX applies)
            if source_queue is route.queue and is_anothers_dlq and route.queue.queue_type == QueueType.QUORUM:
                # Consuming another route's quorum DLQ: declare it exactly as
                # that route's retry/safety topology does, or the two
                # declarations disagree on x-delivery-limit (406).
                await self._declare_dlq(
                    replace(
                        route.queue,
                        delivery_limit=(
                            route.queue.delivery_limit
                            if route.queue.delivery_limit is not None
                            else dlq_delivery_limit(self._broker_server_version())
                        ),
                    )
                )
            else:
                await self._transport.declare_queue(source_queue)

            # Bind queue to exchange (C4: bind_arguments matter for headers exchanges)
            if route.exchange is not None:
                await self._transport.bind_queue(
                    queue=route.queue.name,
                    exchange=route.exchange.name,
                    routing_key=to_binding_key(route.queue.routing_key),
                    arguments=route.queue.bind_arguments or None,
                )

            # Declare retry/DLQ topology if retry is enabled
            if retry_config is not None:
                exchange_name = route.exchange.name if route.exchange else ""
                delay_queues = retry_router.get_delay_queue_definitions(
                    route.queue.name,
                    exchange_name,
                    source_queue_type=route.queue.queue_type,
                    broker_version=self._broker_server_version(),
                )
                dlq_name = retry_router.get_dlq_name(route.queue.name)
                for delay_queue in delay_queues:
                    if delay_queue.name == dlq_name:
                        await self._declare_dlq(delay_queue)
                    else:
                        await self._transport.declare_queue(delay_queue)
            elif safety_dlq_name is not None:
                # Inherit quorum from a quorum source (see RetryRouter DLQ
                # note): the DLQ stores failures indefinitely.
                await self._declare_dlq(
                    dlq_queue_definition(
                        safety_dlq_name,
                        quorum=route.queue.queue_type == QueueType.QUORUM,
                        broker_version=self._broker_server_version(),
                    )
                )

    def _notify_passive_only(self) -> None:
        """[retry/topology hook] PASSIVE_ONLY startup notice (see topology_validation)."""
        from rabbitkit.core.topology_validation import log_passive_only_limits

        log_passive_only_limits(self._config.topology_mode, self._registry.routes)

    def _broker_server_version(self) -> str | None:
        version = getattr(self._transport, "server_version", None)
        return version if isinstance(version, str) else None

    async def _declare_dlq(self, dlq: RabbitQueue) -> None:
        """Declare a DLQ, leaving an existing one exactly as it is.

        A quorum DLQ on RabbitMQ 4.x carries ``x-delivery-limit: -1`` (see
        ``dlq_queue_definition``). RabbitMQ refuses to add that argument to
        a queue declared without it, and refuses to drop it from one declared
        with it (406 either way). So a DLQ that already exists is not
        redeclared at all; its delivery limit is the operator's to fix, with
        a policy, and ``DLQInspector`` refuses to browse it until they do.
        """
        if dlq.queue_type is QueueType.QUORUM and self._config.topology_mode is TopologyMode.AUTO_DECLARE:
            # Probe whatever the version: an existing DLQ may carry the
            # argument (created by 0.19 on 4.x) even when this connection
            # can't tell which broker version it is talking to.
            assert self._transport is not None
            if await self._transport.queue_exists(dlq.name) is True:
                logger.debug("DLQ %r already exists; not redeclaring it", dlq.name)
                return
        assert self._transport is not None
        await self._transport.declare_queue(dlq)

    async def _start_consumer(self, route: RouteDefinition) -> None:
        """Start consuming for a single route."""
        if self._transport is None:
            return

        pool = self._worker_pool

        async def on_message(message: RabbitMessage) -> None:
            """Process incoming message through the pipeline."""
            # Track inline in-flight so stop() can drain gracefully (C-2).
            # Also register this task/message pair so a drain-deadline timeout
            # can cancel + nack it explicitly (with delivery-tag logging),
            # matching AsyncWorkerPool.stop()'s behavior for the pooled path,
            # instead of silently abandoning it unacked.
            await self._in_flight_inc()
            task = asyncio.current_task()
            if task is not None:
                self._inflight_tasks[task] = message
            self._mark_heartbeat()
            try:
                # Set the original queue in headers for retry routing.
                # H2 (spoofing): ALWAYS overwrite — a legitimate retry round-trip
                # returns to this same queue, so the overwrite is always
                # correct, while honoring a producer-set value would let a
                # malicious/buggy publisher steer retries into another
                # route's delay ladder (cross-queue injection) or a
                # nonexistent queue (requeue hot loop).
                message.headers["x-rabbitkit-original-queue"] = route.queue.name

                # Populate named routing-key segments for Path() DI
                message.path = extract_path(message.routing_key, route.queue.routing_key)

                await self._pipeline.process_async(
                    route,
                    message,
                    publish_fn=self._flow_controlled_internal_publish,  # M18
                )
            finally:
                if task is not None:
                    self._inflight_tasks.pop(task, None)
                await self._in_flight_dec()

        if pool is not None:

            async def on_message_pooled(message: RabbitMessage) -> None:
                await pool.submit(on_message, message)

            callback = on_message_pooled
        else:
            callback = on_message

        consume_kwargs: dict[str, Any] = {}
        tracker = await self._stream_tracker(route)
        if tracker is not None:
            # Record each delivery's offset in arrival order, before a worker
            # pool can reorder handling; the live consume arguments make a
            # reconnect resume at the processed position.
            untracked = callback

            async def on_stream_message(message: RabbitMessage) -> None:
                tracker.track(message)
                await untracked(message)

            callback = on_stream_message
            consume_kwargs["arguments"] = tracker.consume_arguments

        effective_prefetch = route.prefetch_count or self._consumer_config.prefetch_count
        self._wire_consumer_state()
        route.runtime_state.consumer_cancelled = False
        consumer_tag = await self._transport.consume(
            queue=route.queue.name,
            callback=callback,
            prefetch=effective_prefetch,
            **consume_kwargs,
        )
        route.runtime_state.consumer_tag = consumer_tag
        if tracker is not None:
            tracker.subscribed()

    async def _stream_tracker(self, route: RouteDefinition) -> StreamOffsetTracker | None:
        """The offset tracker of a stream route (created on first use), else None.

        Creating one loads the stored offset; a configured store is read off
        the event loop.
        """
        config = route.stream_config
        if config is None:
            return None
        tracker = self._stream_trackers.get(route.name)
        if tracker is None:
            if config.offset_store is None:
                tracker = StreamOffsetTracker(route_name=route.name, queue=route.queue.name, config=config)
            else:
                tracker = await asyncio.to_thread(
                    StreamOffsetTracker, route_name=route.name, queue=route.queue.name, config=config
                )
            self._stream_trackers[route.name] = tracker
        return tracker

    async def _flush_stream_offsets(self, deadline: float | None) -> None:
        """Commit every stream route's processed offset (stop()), within the deadline."""
        for name, tracker in self._stream_trackers.items():
            try:
                async with asyncio.timeout(self._remaining(deadline)):
                    await tracker.flush_async()
            except TimeoutError:
                logger.warning(
                    "Stream route %r: committing the final offset did not finish before the stop deadline; "
                    "the next start replays from offset %s",
                    name,
                    tracker.committed_offset,
                )

    def _wire_consumer_state(self) -> None:
        """Mirror broker-initiated consumer cancels into route state and the hooks."""
        transport: Any = self._transport  # set: _start_consumer returns early without one
        if self._consumer_state_wired is transport:
            return
        self._consumer_state_wired = transport
        transport.on_consumer_cancelled(lambda queue: self._consumer_state_changed(queue, cancelled=True))
        transport.on_consumer_resumed(lambda queue: self._consumer_state_changed(queue, cancelled=False))

    def _consumer_state_changed(self, queue: str, *, cancelled: bool) -> None:
        for route in self._registry.routes:
            if route.queue.name == queue:
                route.runtime_state.consumer_cancelled = cancelled
        metrics = self._broker_metrics
        if metrics is not None:
            if cancelled:
                metrics.consumer_cancelled(queue)
            else:
                metrics.consumer_resumed(queue)
        hook = self.on_consumer_cancelled if cancelled else self.on_consumer_resumed
        if hook is None:
            return
        try:
            hook(queue)
        except Exception:
            event = "cancelled" if cancelled else "resumed"
            logger.warning("on_consumer_%s hook raised (queue=%s)", event, queue, exc_info=True)

    # ── Public topology API (16.6) — additive, retry/topology owner ─────

    async def declare_exchange(self, exchange: RabbitExchange) -> None:
        """Declare *exchange* — for publish-only services that own their exchange.

        Allowed only under ``TopologyMode.AUTO_DECLARE`` (or, under
        ``PASSIVE_ONLY``, a ``passive=True`` existence check); otherwise
        raises :class:`~rabbitkit.core.errors.ConfigurationError`. A conflicting
        existing exchange raises with the conflicting argument named.
        """
        from rabbitkit.core.topology_dispatch import check_public_topology_write

        check_public_topology_write(self._config.topology_mode, "declare_exchange", passive=exchange.passive)
        await self._started_transport().declare_exchange(exchange)

    async def declare_queue(self, queue: RabbitQueue) -> None:
        """Declare *queue* exactly as given (no retry/safety arguments added).

        Same topology-mode rules as :meth:`declare_exchange`."""
        from rabbitkit.core.topology_dispatch import check_public_topology_write

        check_public_topology_write(self._config.topology_mode, "declare_queue", passive=queue.passive)
        await self._started_transport().declare_queue(queue)

    async def bind_queue(
        self, queue: str, exchange: str, routing_key: str = "", arguments: dict[str, Any] | None = None
    ) -> None:
        """Bind *queue* to *exchange*. ``AUTO_DECLARE`` only (a binding is always a write)."""
        from rabbitkit.core.topology_dispatch import check_public_topology_write

        check_public_topology_write(self._config.topology_mode, "bind_queue")
        await self._started_transport().bind_queue(
            queue=queue, exchange=exchange, routing_key=routing_key, arguments=arguments
        )

    async def bind_exchange(
        self, destination: str, source: str, routing_key: str = "", arguments: dict[str, Any] | None = None
    ) -> None:
        """Bind exchange *destination* to *source*. ``AUTO_DECLARE`` only."""
        from rabbitkit.core.topology_dispatch import check_public_topology_write

        check_public_topology_write(self._config.topology_mode, "bind_exchange")
        await self._started_transport().bind_exchange(
            destination=destination, source=source, routing_key=routing_key, arguments=arguments
        )

    async def verify_topology(self, management_client: Any | None = None, *, vhost: str | None = None) -> Any:
        """Check the broker's topology against this application's routes
        (type, durability, arguments, dead-letter path, bindings). Read-only
        in every mode; runs the management client off the event loop. Without
        a client, every check AMQP cannot make is reported ``UNVERIFIED``.

        Returns a :class:`~rabbitkit.core.topology_validation.TopologyReport`;
        call ``report.raise_for_failures()`` to fail startup on drift.
        """
        from rabbitkit.core.topology_validation import verify_topology

        return await asyncio.to_thread(
            verify_topology,
            list(self._registry.routes),
            management_client=management_client,
            vhost=vhost if vhost is not None else self._config.connection.vhost,
            broker_retry=self._config.retry,
        )

    def _started_transport(self) -> Any:
        if self._transport is None:
            raise BrokerNotStartedError("Broker not started. Call start() first.")
        return self._transport

Attributes

flow_controller: Any | None property writable

Optional FlowController used to throttle the publish path.

started: bool property

True between a successful start() and stop().

Public counterpart of _started — health checks (:func:rabbitkit.health.broker_health_check) read this instead of falling back to the private attribute (which emits a DeprecationWarning).

publish_middlewares: list[BaseMiddleware] property

Middlewares applied to every broker.publish() call (e.g. signing).

Set via the constructor's middlewares= param. See the comment on self._publish_middlewares for why reassigning (not mutating) is required to change this after construction.

worker_pool: AsyncWorkerPool | None property

Return the worker pool (if configured).

consumer_config: ConsumerConfig property

Effective consumer config (may reflect WorkerConfig.prefetch override).

Methods:

subscriber(queue: RabbitQueue | str, exchange: RabbitExchange | str | None = None, routing_key: str = '', ack_policy: AckPolicy = AckPolicy.AUTO, middlewares: list[BaseMiddleware] | None = None, serializer: Serializer[Any] | None = None, retry: RetryConfig | RetryDisabled | None = None, tags: frozenset[str] | set[str] | None = None, description: str = '', name: str | None = None, prefetch_count: int | None = None, filter_fn: Callable[[RabbitMessage], bool] | None = None, reject_without_dlx: str | None = None, reply_to_allow: tuple[str, ...] | None = None, stream: StreamConsumerConfig | None = None, stream_offset: StreamOffsetLike | None = None) -> Callable[[HandlerT], HandlerT]

Register a subscriber handler.

Source code in src/rabbitkit/async_/broker.py
def subscriber(
    self,
    queue: RabbitQueue | str,
    exchange: RabbitExchange | str | None = None,
    routing_key: str = "",
    ack_policy: AckPolicy = AckPolicy.AUTO,
    middlewares: list[BaseMiddleware] | None = None,
    serializer: Serializer[Any] | None = None,
    retry: RetryConfig | RetryDisabled | None = None,
    tags: frozenset[str] | set[str] | None = None,
    description: str = "",
    name: str | None = None,
    prefetch_count: int | None = None,
    filter_fn: Callable[[RabbitMessage], bool] | None = None,
    reject_without_dlx: str | None = None,
    reply_to_allow: tuple[str, ...] | None = None,
    stream: StreamConsumerConfig | None = None,
    stream_offset: StreamOffsetLike | None = None,
) -> Callable[[HandlerT], HandlerT]:
    """Register a subscriber handler."""
    return self._registry.subscriber(
        queue=queue,
        exchange=exchange,
        routing_key=routing_key,
        ack_policy=ack_policy,
        middlewares=middlewares,
        serializer=serializer,
        retry=retry,
        tags=tags,
        description=description,
        name=name,
        prefetch_count=prefetch_count,
        filter_fn=filter_fn,
        reject_without_dlx=reject_without_dlx,
        reply_to_allow=reply_to_allow,
        stream=stream,
        stream_offset=stream_offset,
    )

publisher(exchange: RabbitExchange | str | None = None, routing_key: str = '') -> Callable[[HandlerT], HandlerT]

Register a result publisher.

Source code in src/rabbitkit/async_/broker.py
def publisher(
    self,
    exchange: RabbitExchange | str | None = None,
    routing_key: str = "",
) -> Callable[[HandlerT], HandlerT]:
    """Register a result publisher."""
    return self._registry.publisher(exchange=exchange, routing_key=routing_key)

include_router(router: RabbitRouter, prefix: str = '') -> None

Include routes from a RabbitRouter.

Source code in src/rabbitkit/async_/broker.py
def include_router(self, router: RabbitRouter, prefix: str = "") -> None:
    """Include routes from a RabbitRouter."""
    self._registry.include_router(router, prefix=prefix)

__aenter__() -> AsyncBroker async

async with AsyncBroker(config) as broker: starts the broker and stops it when the block exits (also on an exception or cancellation).

Entering calls start(install_signal_handlers=False): a with block is a scope owned by the surrounding code (a script, a test, an application that embeds the broker), so the broker leaves SIGINT and SIGTERM to that code. A standalone consumer process should use await broker.run() instead, which owns the signals and drains on SIGTERM. To pass a WorkerConfig, call start() yourself and stop() in a finally; start() on a started broker is a no-op.

Source code in src/rabbitkit/async_/broker.py
async def __aenter__(self) -> AsyncBroker:
    """``async with AsyncBroker(config) as broker:`` starts the broker and
    stops it when the block exits (also on an exception or cancellation).

    Entering calls ``start(install_signal_handlers=False)``: a ``with``
    block is a scope owned by the surrounding code (a script, a test, an
    application that embeds the broker), so the broker leaves SIGINT and
    SIGTERM to that code. A standalone consumer process should use
    ``await broker.run()`` instead, which owns the signals and drains on
    SIGTERM. To pass a ``WorkerConfig``, call ``start()`` yourself and
    ``stop()`` in a ``finally``; ``start()`` on a started broker is a no-op.
    """
    await self.start(install_signal_handlers=False)
    return self

start(worker_config: WorkerConfig | None = None, *, install_signal_handlers: bool = True) -> None async

Start the broker - connect, declare topology, start consuming.

  1. Connect to RabbitMQ
  2. Declare exchanges, queues, bindings per TopologyMode
  3. Declare retry topology (delay queues, DLQ)
  4. Optionally create a worker pool for concurrent processing
  5. Start consuming from all registered queues

When install_signal_handlers is True (default), SIGINT/SIGTERM are trapped so the common await broker.start() pattern drains gracefully instead of hard-dying (H-SRE5). Pass False when an outer lifecycle manager (e.g. RabbitApp) owns signal handling.

L14: last_heartbeat is initialized here (not left None until the first message/tick) so a broker that is wedged from the very start -- before it ever processes a message or a periodic heartbeat tick -- is still caught by :func:health.broker_liveness's staleness check, instead of bypassing it entirely (a None heartbeat is treated as "no signal available" there, which previously meant "always alive").

all or nothing. If any step raises (or the call is cancelled), everything this call created is undone before the error propagates: consumers already started are cancelled, the worker pool, batch publisher and heartbeat are stopped, and both connections are closed. start() can then simply be called again.

a refused login or vhost, or a TLS verification failure, raises a :class:~rabbitkit.core.errors.PermanentConnectionError at once instead of retrying.

Source code in src/rabbitkit/async_/broker.py
async def start(
    self,
    worker_config: WorkerConfig | None = None,
    *,
    install_signal_handlers: bool = True,
) -> None:
    """Start the broker - connect, declare topology, start consuming.

    1. Connect to RabbitMQ
    2. Declare exchanges, queues, bindings per TopologyMode
    3. Declare retry topology (delay queues, DLQ)
    4. Optionally create a worker pool for concurrent processing
    5. Start consuming from all registered queues

    When ``install_signal_handlers`` is True (default), SIGINT/SIGTERM are
    trapped so the common ``await broker.start()`` pattern drains gracefully
    instead of hard-dying (H-SRE5). Pass ``False`` when an outer lifecycle
    manager (e.g. ``RabbitApp``) owns signal handling.

    L14: ``last_heartbeat`` is initialized here (not left ``None`` until
    the first message/tick) so a broker that is wedged from the very
    start -- before it ever processes a message or a periodic heartbeat
    tick -- is still caught by :func:`health.broker_liveness`'s
    staleness check, instead of bypassing it entirely (a ``None``
    heartbeat is treated as "no signal available" there, which
    previously meant "always alive").

    all or nothing. If any step raises (or the call is cancelled),
    everything this call created is undone before the error propagates:
    consumers already started are cancelled, the worker pool, batch
    publisher and heartbeat are stopped, and both connections are closed.
    ``start()`` can then simply be called again.

    a refused login or vhost, or a TLS verification failure, raises a
    :class:`~rabbitkit.core.errors.PermanentConnectionError` at once
    instead of retrying.
    """
    if self._started:
        return
    try:
        await self._start_unguarded(worker_config, install_signal_handlers=install_signal_handlers)
    except BaseException:
        await self._abort_failed_start()
        raise

run(worker_config: WorkerConfig | None = None) -> None async

Start, wait for a shutdown signal, then stop (H11).

await broker.start() alone installs signal handlers whose drain is fire-and-forget — nothing joins the stop() task they create, so whether in-flight messages actually finish draining depends on incidental event-loop lifetime (e.g. it can be cut short by asyncio.run() cancelling outstanding tasks once the awaited coroutine returns). run() is the direct-use equivalent of RabbitApp.run_async(): it does not return until the drain triggered by SIGINT/SIGTERM (or :meth:request_shutdown) has fully completed, so awaiting it end-to-end guarantees in-flight messages are settled before the process exits::

broker = AsyncBroker(config)

@broker.subscriber(queue="orders")
async def handle_order(body: bytes) -> None: ...

asyncio.run(broker.run())

Use plain start()/stop() instead when an outer lifecycle manager (RabbitApp) owns the run loop.

Source code in src/rabbitkit/async_/broker.py
async def run(self, worker_config: WorkerConfig | None = None) -> None:
    """Start, wait for a shutdown signal, then stop (H11).

    ``await broker.start()`` alone installs signal handlers whose drain is
    fire-and-forget — nothing joins the ``stop()`` task they create, so
    whether in-flight messages actually finish draining depends on
    incidental event-loop lifetime (e.g. it can be cut short by
    ``asyncio.run()`` cancelling outstanding tasks once the awaited
    coroutine returns). ``run()`` is the direct-use equivalent of
    ``RabbitApp.run_async()``: it does not return until the drain
    triggered by SIGINT/SIGTERM (or :meth:`request_shutdown`) has fully
    completed, so awaiting it end-to-end guarantees in-flight messages are
    settled before the process exits::

        broker = AsyncBroker(config)

        @broker.subscriber(queue="orders")
        async def handle_order(body: bytes) -> None: ...

        asyncio.run(broker.run())

    Use plain ``start()``/``stop()`` instead when an outer lifecycle
    manager (``RabbitApp``) owns the run loop.
    """
    await self.start(worker_config=worker_config)
    self._run_waiting = True
    try:
        await self._shutdown_event.wait()
    finally:
        self._run_waiting = False
        await self.stop()
    failure = self._connection_failure()
    if failure is not None:
        raise failure

request_shutdown() -> None

Request a graceful shutdown from any context — e.g. a failing health check or a management command (H11). Equivalent to receiving SIGINT/SIGTERM: if run() is awaiting shutdown it performs the drain; otherwise this schedules a fire-and-forget stop().

Source code in src/rabbitkit/async_/broker.py
def request_shutdown(self) -> None:
    """Request a graceful shutdown from any context — e.g. a failing
    health check or a management command (H11). Equivalent to receiving
    SIGINT/SIGTERM: if ``run()`` is awaiting shutdown it performs the
    drain; otherwise this schedules a fire-and-forget ``stop()``.
    """
    self._trigger_shutdown()

stop(timeout: float | None = None) -> None async

Stop the broker - cancel consumers, drain pool, drain in-flight, disconnect.

timeout defaults to ConsumerConfig.graceful_timeout (C-2). The whole sequence is bounded by an overall deadline.

C5: consumers are cancelled FIRST, before the worker pool is drained. Draining the pool before cancelling left the consumer active for the entire (potentially graceful_timeout-long) drain wait — a message delivered in that window was submitted via AsyncWorkerPool.submit(), which creates a task unconditionally (it never checks _running) and adds it to _tasks. If that submit happens after .stop() already cleared _tasks, the new task is never awaited by anything — an orphaned background task racing the event loop's shutdown, with the message never cleanly settled before disconnect(), so it is redelivered (duplicate-processing risk) on the next connection. Cancelling first stops new deliveries outright, so the pool only ever drains work that was already in flight.

Source code in src/rabbitkit/async_/broker.py
async def stop(self, timeout: float | None = None) -> None:
    """Stop the broker - cancel consumers, drain pool, drain in-flight, disconnect.

    ``timeout`` defaults to ``ConsumerConfig.graceful_timeout`` (C-2). The
    whole sequence is bounded by an overall deadline.

    C5: consumers are cancelled FIRST, before the worker pool is drained.
    Draining the pool before cancelling left the consumer active for the
    entire (potentially graceful_timeout-long) drain wait — a message
    delivered in that window was submitted via ``AsyncWorkerPool.submit()``,
    which creates a task unconditionally (it never checks ``_running``) and
    adds it to ``_tasks``. If that submit happens after ``.stop()`` already
    cleared ``_tasks``, the new task is never awaited by anything — an
    orphaned background task racing the event loop's shutdown, with the
    message never cleanly settled before ``disconnect()``, so it is
    redelivered (duplicate-processing risk) on the next connection.
    Cancelling first stops new deliveries outright, so the pool only ever
    drains work that was already in flight.
    """
    if not self._started:
        return

    self._restore_signal_handlers()

    effective = timeout if timeout is not None else self._consumer_config.graceful_timeout
    deadline = None if effective is None else time.monotonic() + effective

    # Stream routes: from here a nack/reject hands a delivery back (pool
    # hand-back, cancelled handler), so its offset must not advance.
    for tracker in self._stream_trackers.values():
        tracker.begin_shutdown()

    # L14: stop the periodic heartbeat first, alongside cancelling consumers.
    if self._heartbeat_task is not None:
        self._heartbeat_task.cancel()
        with contextlib.suppress(asyncio.CancelledError):
            await self._heartbeat_task
        self._heartbeat_task = None

    # Cancel all consumers FIRST — stop new deliveries before draining
    # anything, so nothing new arrives while the pool/in-flight drain runs.
    if self._transport is None:  # pragma: no cover — defensive (assert was stripped under -O)
        return
    # Every step below is bounded by the overall deadline, including the
    # ones that talk to the broker: during a partition a cancel or a close
    # is never answered, and stop() used to wait for the network to heal.
    for route in self._registry.routes:
        if route.consumer_tag:
            await self._transport.cancel_consumer(route.consumer_tag, timeout=self._remaining(deadline))

    # Drain the worker pool (let in-flight pooled tasks finish), bounded by
    # the outer deadline.
    if self._worker_pool is not None:
        remaining = None if deadline is None else max(0.0, deadline - time.monotonic())
        await self._worker_pool.stop(timeout=remaining)
        self._worker_pool = None

    # Drain inline in-flight handlers (C-2).
    await self._wait_in_flight(deadline)

    # Every handler has settled or been handed back: commit the stream
    # offsets, so the next start resumes right after the last processed one.
    await self._flush_stream_offsets(deadline)

    # Publisher shutdown. After the consumer drain, so a handler
    # finishing inside the grace period can still publish its result or
    # retry handoff. Then, within what is left of the deadline:
    # 1. close admission (publish() now raises BrokerNotStartedError and
    #    never reconnects); 2. flush the batch queue and wait for
    #    in-flight confirms; 3. resolve the rest (queued: NOT_SENT,
    #    on the wire: UNKNOWN) and release every waiter; then disconnect.
    self._publish_closed = True
    if self._batch_publisher is not None:
        await self._batch_publisher.stop(timeout=self._remaining(deadline))
        self._batch_publisher = None
    await self._transport.close_publishing(timeout=self._remaining(deadline))

    # Close RPC client if used
    if self._rpc_client is not None:
        with contextlib.suppress(TimeoutError):
            async with asyncio.timeout(self._remaining(deadline)):
                await self._rpc_client.close()
        self._rpc_client = None

    # Disconnect
    if self._transport:
        await self._transport.disconnect(timeout=self._remaining(deadline))

    self._started = False
    self._set_lifecycle_gauges(connected=False)
    logger.info("AsyncBroker stopped")

publish(envelope: MessageEnvelope | None = None, *, exchange: str = '', routing_key: str = '', body: bytes | str | dict[str, Any] | None = None, headers: dict[str, Any] | None = None, content_type: str = 'application/json', correlation_id: str | None = None, reply_to: str | None = None, message_id: str | None = None, timeout: float | None = None) -> PublishOutcome async

Publish a message.

Accepts either a pre-built MessageEnvelope or individual kwargs::

# Envelope form (full control):
await broker.publish(MessageEnvelope(routing_key="orders.created", body=b"..."))

# Kwargs form (convenient):
await broker.publish(
    exchange="orders",
    routing_key="orders.created",
    body={"order_id": 123},
    headers={"x-tenant": "acme"},
)

When body is a dict or str it is JSON-encoded automatically.

When an opt-in FlowController is configured (broker.flow_controller = fc), a publish slot is acquired/released around the transport publish so backpressure/rate-limiting applies to the hot path. Without a controller this is a plain pass-through.

When middlewares=[...] was passed to the constructor, each middleware's publish_scope_async wraps this call (e.g. SigningMiddleware signs the envelope) — see publish_middlewares. Middleware wraps OUTSIDE both flow control and batching, so a middleware-transformed envelope is what gets rate-limited/batched, and what actually reaches the wire.

message_id (kwargs form only) sets the AMQP message id instead of a fresh uuid4, so an application can republish the SAME logical message after an UNKNOWN outcome and let consumers deduplicate. With an envelope, set MessageEnvelope.message_id instead.

timeout bounds this call end to end: admission (flow control, byte budget, a free channel), send and confirm. On expiry the outcome is NOT_SENT (admission_timeout) if nothing was sent, else TIMEOUT (publish_timeout), which is an unknown outcome. None keeps the configured bounds (channel_acquire_timeout, confirm_timeout).

Outcomes are returned, not raised (see :class:PublishStatus). Raises BrokerNotStartedError before start() and once stop() has begun closing the publisher — a publish never reconnects a stopped broker.

Source code in src/rabbitkit/async_/broker.py
async def publish(
    self,
    envelope: MessageEnvelope | None = None,
    *,
    exchange: str = "",
    routing_key: str = "",
    body: bytes | str | dict[str, Any] | None = None,
    headers: dict[str, Any] | None = None,
    content_type: str = "application/json",
    correlation_id: str | None = None,
    reply_to: str | None = None,
    message_id: str | None = None,
    timeout: float | None = None,
) -> PublishOutcome:
    """Publish a message.

    Accepts either a pre-built ``MessageEnvelope`` or individual kwargs::

        # Envelope form (full control):
        await broker.publish(MessageEnvelope(routing_key="orders.created", body=b"..."))

        # Kwargs form (convenient):
        await broker.publish(
            exchange="orders",
            routing_key="orders.created",
            body={"order_id": 123},
            headers={"x-tenant": "acme"},
        )

    When ``body`` is a dict or str it is JSON-encoded automatically.

    When an opt-in ``FlowController`` is configured (``broker.flow_controller
    = fc``), a publish slot is acquired/released around the transport publish
    so backpressure/rate-limiting applies to the hot path. Without a
    controller this is a plain pass-through.

    When ``middlewares=[...]`` was passed to the constructor, each
    middleware's ``publish_scope_async`` wraps this call (e.g.
    ``SigningMiddleware`` signs the envelope) — see ``publish_middlewares``.
    Middleware wraps OUTSIDE both flow control and batching, so a
    middleware-transformed envelope is what gets rate-limited/batched, and
    what actually reaches the wire.

    ``message_id`` (kwargs form only) sets the AMQP message id instead of
    a fresh uuid4, so an application can republish the SAME logical
    message after an ``UNKNOWN`` outcome and let consumers deduplicate.
    With an envelope, set ``MessageEnvelope.message_id`` instead.

    ``timeout`` bounds this call end to end: admission (flow control,
    byte budget, a free channel), send and confirm. On expiry the outcome
    is ``NOT_SENT`` (``admission_timeout``) if nothing was sent, else
    ``TIMEOUT`` (``publish_timeout``), which is an unknown outcome.
    ``None`` keeps the configured bounds (``channel_acquire_timeout``,
    ``confirm_timeout``).

    Outcomes are returned, not raised (see :class:`PublishStatus`).
    Raises ``BrokerNotStartedError`` before ``start()`` and once
    ``stop()`` has begun closing the publisher — a publish never
    reconnects a stopped broker.
    """
    if timeout is not None and not timeout > 0:
        raise ValueError(f"publish timeout must be > 0, got {timeout}")
    if envelope is not None and message_id is not None:
        raise ValueError("message_id applies to the kwargs form; set MessageEnvelope.message_id instead")
    if envelope is None:
        import json as _json

        if body is None:
            raw_body = b""
        elif isinstance(body, bytes):
            raw_body = body
        elif isinstance(body, str):
            raw_body = body.encode()
        else:
            raw_body = _json.dumps(body).encode()
        # M2: honor PublisherConfig defaults for the kwargs form (they were
        # previously dead config). Envelope-form callers keep full control.
        envelope = MessageEnvelope(
            routing_key=routing_key,
            body=raw_body,
            exchange=exchange,
            headers=headers or {},
            content_type=content_type,
            correlation_id=correlation_id,
            reply_to=reply_to,
            mandatory=self._config.publisher.mandatory,
            delivery_mode=2 if self._config.publisher.persistent else 1,
        )
        if message_id is not None:
            envelope = replace(envelope, message_id=message_id)

    # an application publish cannot carry rabbitkit's retry/DLQ
    # bookkeeping headers (opt-in; the library's own republishes bypass this).
    if self._reserved_header_stripper is not None:
        envelope = self._reserved_header_stripper(envelope)

    # M10: reject oversized bodies at publish time (see sync broker).
    max_bytes = self._config.publisher.max_message_bytes
    if max_bytes and len(envelope.body) > max_bytes:
        raise MessageTooLargeError(
            f"Message body ({len(envelope.body)} bytes) exceeds "
            f"PublisherConfig.max_message_bytes ({max_bytes}). Large messages are a "
            "RabbitMQ anti-pattern — store the payload externally and publish a "
            "reference, or raise the limit if this is intentional."
        )

    if self._transport is None:
        raise BrokerNotStartedError("Broker not started. Call start() first.")
    if self._publish_closed:
        raise BrokerNotStartedError("Broker is stopping or stopped; publishing is closed. Call start() first.")

    publish_fn = self._batch_publisher.publish if self._batch_publisher is not None else self._transport.publish
    if timeout is None and self._flow_controller is None and not self._publish_middlewares:
        # Hot path: nothing to wrap, so skip the per-call closures and the
        # extra coroutine layers below (measurable at ~10k msg/s).
        return await publish_fn(envelope)  # type: ignore[no-any-return]
    loop = asyncio.get_running_loop()
    deadline = None if timeout is None else loop.time() + timeout

    async def send(env: MessageEnvelope) -> PublishOutcome:
        if deadline is None:
            return await publish_fn(env)  # type: ignore[no-any-return]
        remaining = deadline - loop.time()
        if remaining <= 0:
            return _not_sent(env, PublishReason.ADMISSION_TIMEOUT)
        return await publish_fn(env, timeout=remaining)  # type: ignore[no-any-return]

    async def do_publish(env: MessageEnvelope) -> PublishOutcome:
        fc = self._flow_controller
        if fc is not None:
            if deadline is None:
                acquired = await fc.acquire_async()
            else:
                acquired = await fc.acquire_async(timeout=max(0.0, deadline - loop.time()))
            if not acquired:
                return _not_sent(
                    env,
                    PublishReason.BACKPRESSURE_DROPPED,
                    BackpressureError("publish dropped by backpressure policy"),
                )
            try:
                return await send(env)
            finally:
                await fc.release_async()
        return await send(env)

    if self._publish_middlewares:
        chain = self._pipeline.compose_broker_publish_async(self._publish_middlewares)
        outcome: PublishOutcome = await chain(envelope, do_publish)
        return outcome
    return await do_publish(envelope)

preflight(profile: ReliabilityProfile | str = ReliabilityProfile.STANDARD, *, management_client: Any | None = None, vhost: str = '/') -> PreflightReport

Verify reliability-profile prerequisites for this broker's config and registered routes (plan §9). Broker-side policy checks need a read-only management client; without one they are reported UNVERIFIED — never silently green. Pure inspection; no I/O on the AMQP connection and no policy mutation.

Source code in src/rabbitkit/async_/broker.py
def preflight(
    self,
    profile: ReliabilityProfile | str = ReliabilityProfile.STANDARD,
    *,
    management_client: Any | None = None,
    vhost: str = "/",
) -> PreflightReport:
    """Verify reliability-profile prerequisites for this broker's config
    and registered routes (plan §9). Broker-side policy checks need a
    read-only management client; without one they are reported
    ``UNVERIFIED`` — never silently green. Pure inspection; no I/O on
    the AMQP connection and no policy mutation."""
    return run_preflight(
        self._config,
        profile,
        routes=self._registry.routes,
        management_client=management_client,
        vhost=vhost,
    )

iter_publish(envelopes: Iterable[MessageEnvelope] | AsyncIterator[MessageEnvelope], options: BulkPublishOptions | None = None) -> AsyncIterator[BulkPublishItem]

Publish a (possibly unbounded, possibly async) iterable with bounded concurrency, yielding one :class:~rabbitkit.core.bulk.BulkPublishItem per input as it settles — in COMPLETION order (use item.index).

Every item goes through the SAME path as :meth:publish — publish middlewares, flow control, size limit, the batch publisher when one is configured, the transport — so single and bulk publishing share every safeguard. Admission is bounded by options.max_in_flight and options.max_buffer_bytes; waiting by admission_timeout; the whole operation by overall_timeout (in-flight items past the deadline are reported UNKNOWN, never dropped).

Source code in src/rabbitkit/async_/broker.py
def iter_publish(
    self,
    envelopes: Iterable[MessageEnvelope] | AsyncIterator[MessageEnvelope],
    options: BulkPublishOptions | None = None,
) -> AsyncIterator[BulkPublishItem]:
    """Publish a (possibly unbounded, possibly async) iterable with bounded
    concurrency, yielding one :class:`~rabbitkit.core.bulk.BulkPublishItem`
    per input as it settles — in COMPLETION order (use ``item.index``).

    Every item goes through the SAME path as :meth:`publish` — publish
    middlewares, flow control, size limit, the batch publisher when one
    is configured, the transport — so single and bulk publishing share
    every safeguard. Admission is bounded by ``options.max_in_flight``
    and ``options.max_buffer_bytes``; waiting by ``admission_timeout``;
    the whole operation by ``overall_timeout`` (in-flight items past the
    deadline are reported ``UNKNOWN``, never dropped).
    """
    if self._transport is None or self._publish_closed:
        raise BrokerNotStartedError("Broker not started. Call start() first.")
    opts = options or BulkPublishOptions()
    # Without a batch publisher every in-flight publish holds one pooled
    # channel, so admitting more than ``PoolConfig.channel_pool_size`` only
    # queues callers on the pool (with "pool exhausted" warnings) instead of
    # adding concurrency. Cap the effective in-flight bound to the pool.
    # With AsyncBatchPublisher configured, publishes share channels and
    # the batch queue has its own bound, so the caller's value stands.
    if self._batch_publisher is None:
        pool_size = self._config.pool.channel_pool_size
        if opts.max_in_flight > pool_size:
            opts = replace(opts, max_in_flight=pool_size)
    preparer = PublishPreparer(
        max_message_bytes=self._config.publisher.max_message_bytes,
        max_buffer_bytes=opts.max_buffer_bytes,
    )
    return iter_publish_async(
        envelopes,
        self.publish,
        options=opts,
        preparer=preparer,
        on_item=self._record_bulk_item,
    )

publish_many(envelopes: Sequence[MessageEnvelope], options: BulkPublishOptions | None = None) -> BulkPublishResult async

Publish a bounded collection concurrently and return input-ordered per-item outcomes.

Never raises for a failed item — inspect result.items (or call result.raise_for_status()). Raises ValueError before publishing anything if len(envelopes) exceeds options.max_items; use :meth:iter_publish for streams. UNKNOWN items may have reached the broker: reconcile by message_id/attempt_id with stable IDs and deduplication — do not blindly replay the batch.

Source code in src/rabbitkit/async_/broker.py
async def publish_many(
    self,
    envelopes: Sequence[MessageEnvelope],
    options: BulkPublishOptions | None = None,
) -> BulkPublishResult:
    """Publish a bounded collection concurrently and return input-ordered
    per-item outcomes.

    Never raises for a failed item — inspect ``result.items`` (or call
    ``result.raise_for_status()``). Raises ``ValueError`` before publishing
    anything if ``len(envelopes)`` exceeds ``options.max_items``; use
    :meth:`iter_publish` for streams. ``UNKNOWN`` items may have reached
    the broker: reconcile by ``message_id``/``attempt_id`` with stable IDs
    and deduplication — do not blindly replay the batch.
    """
    opts = options or BulkPublishOptions()
    if len(envelopes) > opts.max_items:
        raise ValueError(
            f"publish_many received {len(envelopes)} envelopes, more than BulkPublishOptions.max_items "
            f"({opts.max_items}); use iter_publish() for large or unbounded inputs."
        )
    started = datetime.now(UTC)
    items: list[BulkPublishItem] = []
    async for item in self.iter_publish(envelopes, opts):
        items.append(item)
    self._record_bulk_batch(len(envelopes))
    return BulkPublishResult(
        items=tuple(sorted(items, key=lambda it: it.index)),
        started_at=started,
        finished_at=datetime.now(UTC),
    )

ack_many(messages: Iterable[RabbitMessage], *, fail_fast: bool = True) -> SettlementReport async

Ack exactly the given deliveries — each with its own multiple=False frame. Never a cumulative ack: an unselected, still-running sibling on the same channel is untouched.

Validation runs before any I/O: duplicates, already-settled messages, no-ack deliveries and STALE handles (channel rebuilt since delivery) are reported per item. With fail_fast=True (default) any problem aborts the whole call with every valid item NOT_ATTEMPTED.

The report says DISPATCHED, not "confirmed" — RabbitMQ sends no acknowledgement for a consumer ack.

Source code in src/rabbitkit/async_/broker.py
async def ack_many(self, messages: Iterable[RabbitMessage], *, fail_fast: bool = True) -> SettlementReport:
    """Ack exactly the given deliveries — each with its own ``multiple=False``
    frame. Never a cumulative ack: an unselected, still-running sibling on
    the same channel is untouched.

    Validation runs before any I/O: duplicates, already-settled messages,
    no-ack deliveries and STALE handles (channel rebuilt since delivery)
    are reported per item. With ``fail_fast=True`` (default) any problem
    aborts the whole call with every valid item ``NOT_ATTEMPTED``.

    The report says ``DISPATCHED``, not "confirmed" — RabbitMQ sends no
    acknowledgement for a consumer ack.
    """
    return await settle_many_async(
        messages,
        SettlementAction.ACK,
        fail_fast=fail_fast,
        on_item=self._settlement_item_hook(SettlementAction.ACK),
    )

nack_many(messages: Iterable[RabbitMessage], *, requeue: bool = True, fail_fast: bool = True) -> SettlementReport async

Nack exactly the given deliveries (individually — see :meth:ack_many).

requeue=False dead-letters (or, without a DLX, DISCARDS) each message; for ordinary handler failures prefer the retry/terminal path (RetryConfig) over raw nacks.

Source code in src/rabbitkit/async_/broker.py
async def nack_many(
    self,
    messages: Iterable[RabbitMessage],
    *,
    requeue: bool = True,
    fail_fast: bool = True,
) -> SettlementReport:
    """Nack exactly the given deliveries (individually — see :meth:`ack_many`).

    ``requeue=False`` dead-letters (or, without a DLX, DISCARDS) each
    message; for ordinary handler failures prefer the retry/terminal
    path (``RetryConfig``) over raw nacks.
    """
    return await settle_many_async(
        messages,
        SettlementAction.NACK,
        requeue=requeue,
        fail_fast=fail_fast,
        on_item=self._settlement_item_hook(SettlementAction.NACK),
    )

request(routing_key: str, body: bytes, *, timeout: float = 5.0, exchange: str = '', headers: dict[str, Any] | None = None) -> RabbitMessage async

Send an RPC request and wait for a response.

Lazily initializes an AsyncRPCClient on first call. The client is shared across calls and closed in stop().

Parameters:

Name Type Description Default
routing_key str

Target queue/routing key.

required
body bytes

Request body as bytes.

required
timeout float

Max seconds to wait for response.

5.0
exchange str

Exchange to publish to (default "").

''
headers dict[str, Any] | None

Optional AMQP headers.

None

Returns:

Type Description
RabbitMessage

RabbitMessage containing the response.

Raises:

Type Description
RuntimeError

If broker is not started.

RPCTimeoutError

If no response within timeout.

Source code in src/rabbitkit/async_/broker.py
async def request(
    self,
    routing_key: str,
    body: bytes,
    *,
    timeout: float = 5.0,
    exchange: str = "",
    headers: dict[str, Any] | None = None,
) -> RabbitMessage:
    """Send an RPC request and wait for a response.

    Lazily initializes an AsyncRPCClient on first call.
    The client is shared across calls and closed in stop().

    Args:
        routing_key: Target queue/routing key.
        body: Request body as bytes.
        timeout: Max seconds to wait for response.
        exchange: Exchange to publish to (default "").
        headers: Optional AMQP headers.

    Returns:
        RabbitMessage containing the response.

    Raises:
        RuntimeError: If broker is not started.
        RPCTimeoutError: If no response within timeout.
    """
    if self._transport is None:
        raise BrokerNotStartedError("Broker not started. Call start() first.")
    if self._rpc_client is None:
        from rabbitkit.rpc import AsyncRPCClient

        self._rpc_client = AsyncRPCClient(self._transport)
    return await self._rpc_client.call(routing_key, body, timeout=timeout, exchange=exchange, headers=headers)

declare_exchange(exchange: RabbitExchange) -> None async

Declare exchange — for publish-only services that own their exchange.

Allowed only under TopologyMode.AUTO_DECLARE (or, under PASSIVE_ONLY, a passive=True existence check); otherwise raises :class:~rabbitkit.core.errors.ConfigurationError. A conflicting existing exchange raises with the conflicting argument named.

Source code in src/rabbitkit/async_/broker.py
async def declare_exchange(self, exchange: RabbitExchange) -> None:
    """Declare *exchange* — for publish-only services that own their exchange.

    Allowed only under ``TopologyMode.AUTO_DECLARE`` (or, under
    ``PASSIVE_ONLY``, a ``passive=True`` existence check); otherwise
    raises :class:`~rabbitkit.core.errors.ConfigurationError`. A conflicting
    existing exchange raises with the conflicting argument named.
    """
    from rabbitkit.core.topology_dispatch import check_public_topology_write

    check_public_topology_write(self._config.topology_mode, "declare_exchange", passive=exchange.passive)
    await self._started_transport().declare_exchange(exchange)

declare_queue(queue: RabbitQueue) -> None async

Declare queue exactly as given (no retry/safety arguments added).

Same topology-mode rules as :meth:declare_exchange.

Source code in src/rabbitkit/async_/broker.py
async def declare_queue(self, queue: RabbitQueue) -> None:
    """Declare *queue* exactly as given (no retry/safety arguments added).

    Same topology-mode rules as :meth:`declare_exchange`."""
    from rabbitkit.core.topology_dispatch import check_public_topology_write

    check_public_topology_write(self._config.topology_mode, "declare_queue", passive=queue.passive)
    await self._started_transport().declare_queue(queue)

bind_queue(queue: str, exchange: str, routing_key: str = '', arguments: dict[str, Any] | None = None) -> None async

Bind queue to exchange. AUTO_DECLARE only (a binding is always a write).

Source code in src/rabbitkit/async_/broker.py
async def bind_queue(
    self, queue: str, exchange: str, routing_key: str = "", arguments: dict[str, Any] | None = None
) -> None:
    """Bind *queue* to *exchange*. ``AUTO_DECLARE`` only (a binding is always a write)."""
    from rabbitkit.core.topology_dispatch import check_public_topology_write

    check_public_topology_write(self._config.topology_mode, "bind_queue")
    await self._started_transport().bind_queue(
        queue=queue, exchange=exchange, routing_key=routing_key, arguments=arguments
    )

bind_exchange(destination: str, source: str, routing_key: str = '', arguments: dict[str, Any] | None = None) -> None async

Bind exchange destination to source. AUTO_DECLARE only.

Source code in src/rabbitkit/async_/broker.py
async def bind_exchange(
    self, destination: str, source: str, routing_key: str = "", arguments: dict[str, Any] | None = None
) -> None:
    """Bind exchange *destination* to *source*. ``AUTO_DECLARE`` only."""
    from rabbitkit.core.topology_dispatch import check_public_topology_write

    check_public_topology_write(self._config.topology_mode, "bind_exchange")
    await self._started_transport().bind_exchange(
        destination=destination, source=source, routing_key=routing_key, arguments=arguments
    )

verify_topology(management_client: Any | None = None, *, vhost: str | None = None) -> Any async

Check the broker's topology against this application's routes (type, durability, arguments, dead-letter path, bindings). Read-only in every mode; runs the management client off the event loop. Without a client, every check AMQP cannot make is reported UNVERIFIED.

Returns a :class:~rabbitkit.core.topology_validation.TopologyReport; call report.raise_for_failures() to fail startup on drift.

Source code in src/rabbitkit/async_/broker.py
async def verify_topology(self, management_client: Any | None = None, *, vhost: str | None = None) -> Any:
    """Check the broker's topology against this application's routes
    (type, durability, arguments, dead-letter path, bindings). Read-only
    in every mode; runs the management client off the event loop. Without
    a client, every check AMQP cannot make is reported ``UNVERIFIED``.

    Returns a :class:`~rabbitkit.core.topology_validation.TopologyReport`;
    call ``report.raise_for_failures()`` to fail startup on drift.
    """
    from rabbitkit.core.topology_validation import verify_topology

    return await asyncio.to_thread(
        verify_topology,
        list(self._registry.routes),
        management_client=management_client,
        vhost=vhost if vhost is not None else self._config.connection.vhost,
        broker_retry=self._config.retry,
    )

SyncBroker

SyncBroker

Sync broker — wires registry + pipeline + SyncTransport.

Usage::

config = RabbitConfig(connection=ConnectionConfig(host="localhost"))
broker = SyncBroker(config)

@broker.subscriber(queue="orders", exchange="events")
def handle_order(body: bytes) -> None:
    ...

broker.start()
Source code in src/rabbitkit/sync/broker.py
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
class SyncBroker:
    """Sync broker — wires registry + pipeline + SyncTransport.

    Usage::

        config = RabbitConfig(connection=ConnectionConfig(host="localhost"))
        broker = SyncBroker(config)

        @broker.subscriber(queue="orders", exchange="events")
        def handle_order(body: bytes) -> None:
            ...

        broker.start()
    """

    def __init__(
        self,
        config: RabbitConfig | None = None,
        *,
        serializer: Serializer[Any] | None = None,
        di_resolver: Any | None = None,
        context_repo: Any | None = None,
        middlewares: list[BaseMiddleware] | None = None,
    ) -> None:
        self._config = config or RabbitConfig()
        # C3: middlewares applied to every broker.publish() call — the primary
        # producer API. Distinct from @subscriber(middlewares=[...]), which
        # only wraps a route's HANDLER-RESULT publishes (Contract 5); without
        # this, e.g. SigningMiddleware never signed anything published via
        # broker.publish() directly. The composed chain is cached by this
        # list's identity (see HandlerPipeline.compose_broker_publish_sync), so
        # set the full list via this constructor param — mutating it in place
        # after the first publish() call would silently reuse the stale
        # pre-mutation chain.
        self._publish_middlewares: list[BaseMiddleware] = middlewares or []
        # PublisherConfig.strip_reserved_headers (None = off).
        self._reserved_header_stripper: ReservedHeaderStripper | None = (
            ReservedHeaderStripper(extra=(self._config.retry.retry_header,) if self._config.retry is not None else ())
            if self._config.publisher.strip_reserved_headers
            else None
        )
        # Private mutable view of consumer config — brokers may apply a
        # prefetch override derived from WorkerConfig.prefetch_per_worker.
        # Stored separately so the caller's frozen RabbitConfig is never mutated.
        self._consumer_config = self._config.consumer

        self._registry = SubscriberRegistry(broker_retry=self._config.retry)
        # The client library's connection/channel errors classify as
        # INFRASTRUCTURE (retried) — core/ cannot import them itself.
        register_infrastructure_errors(*get_infrastructure_errors())
        self._pipeline = HandlerPipeline(
            serializer=serializer,
            di_resolver=di_resolver,
            context_repo=context_repo,
            reject_transient_on_redelivery=self._config.consumer.reject_transient_on_redelivery,
            manual_settle_on_error=self._config.consumer.manual_settle_on_error,
            max_body_bytes=self._config.consumer.max_body_bytes,
        )
        # ConsumerConfig.processing_timeout (see sync/deadlines.py): handlers
        # run off the I/O thread, which settles an expired delivery itself.
        timeout = self._config.consumer.processing_timeout
        self._deadlines: SyncDeadlines | None = (
            SyncDeadlines(timeout, self._pipeline.settle_expired_sync) if timeout is not None else None
        )
        if self._config.safety.dead_letter_with_metadata:
            logger.warning(
                "SafetyConfig.dead_letter_with_metadata is applied by AsyncBroker only: SyncBroker dead-letters "
                "failures RetryMiddleware did not handle by a reject, so their DLQ entry carries only x-death."
            )

        self._transport: SyncTransport | None = None
        # connection/channel/flow-control metrics (see AsyncBroker).
        self._broker_metrics: BrokerMetrics | None = None
        self._metrics_sampled_at = 0.0
        self._worker_pool: SyncWorkerPool | None = None
        self._started = False
        self._rpc_client: Any | None = None

        # optional hooks called with the queue name when the BROKER
        # cancels a route's consumer (queue deleted, quorum leader change, ...)
        # and when it is consuming again. The consume loop re-subscribes on
        # its own; the route reports as not consuming in health checks
        # meanwhile. Called on the owner thread (see AsyncBroker).
        self.on_consumer_cancelled: Callable[[str], None] | None = None
        self.on_consumer_resumed: Callable[[str], None] | None = None
        self._consumer_state_wired: Any = None  # the transport the state callbacks are on

        # L14: liveness heartbeat (see health.broker_liveness). Read by
        # health.py via duck-typed attribute access (no formal HealthProvider
        # method for it). None until start() -- see the start() docstring for
        # why it's set there rather than only on delivery/tick.
        self.last_heartbeat: float | None = None

        # Bounded graceful drain (C-2): track inline in-flight handlers so
        # stop() can wait for them to finish (up to graceful_timeout) instead
        # of disconnecting mid-handler. R-Condition: a threading.Condition
        # replaces the prior Event+int+manual set/clear; ``_in_flight`` stays
        # a plain int for backward-compat reads (health checks).
        self._in_flight = 0
        self._in_flight_cond = threading.Condition()
        # Stream routes: per-route offset tracker (route name -> tracker), kept
        # across reconnects and stop()/start() (see AsyncBroker).
        self._stream_trackers: dict[str, StreamOffsetTracker] = {}

        # Optional publish-side flow control (C-6). Opt-in via the
        # flow_controller setter; when set, publish() acquires/releases a
        # slot around transport.publish().
        self._flow_controller: Any | None = None

        # Signal-handler bookkeeping (C-1).
        self._original_handlers: dict[int, Any] = {}
        self._sigterm_thread: threading.Thread | None = None

    @property
    def flow_controller(self) -> Any | None:
        """Optional FlowController used to throttle the publish path."""
        return self._flow_controller

    @flow_controller.setter
    def flow_controller(self, value: Any | None) -> None:
        self._flow_controller = value
        # Wire the controller's blocked/unblocked callbacks to the transport if
        # it is already up (registration before start() is also fine: start()
        # wires them after constructing the transport).
        if self._transport is not None and value is not None:
            self._transport.on_blocked(value.on_blocked)
            self._transport.on_unblocked(value.on_unblocked)

    @property
    def started(self) -> bool:
        """True between a successful ``start()`` and ``stop()``.

        Public counterpart of ``_started`` — health checks
        (:func:`rabbitkit.health.broker_health_check`) read this instead of
        falling back to the private attribute (which emits a
        DeprecationWarning).
        """
        return self._started

    @property
    def config(self) -> RabbitConfig:
        return self._config

    @property
    def publish_middlewares(self) -> list[BaseMiddleware]:
        """Middlewares applied to every ``broker.publish()`` call (e.g. signing).

        Set via the constructor's ``middlewares=`` param. See the comment on
        ``self._publish_middlewares`` for why reassigning (not mutating) is
        required to change this after construction.
        """
        return self._publish_middlewares

    @property
    def routes(self) -> list[RouteDefinition]:
        return self._registry.routes

    @property
    def worker_pool(self) -> SyncWorkerPool | None:
        """Return the worker pool (if configured)."""
        return self._worker_pool

    @property
    def consumer_config(self) -> ConsumerConfig:
        """Effective consumer config (may reflect WorkerConfig.prefetch override)."""
        return self._consumer_config

    # ── Registration (decorator API) ──────────────────────────────────────

    def subscriber(
        self,
        queue: RabbitQueue | str,
        exchange: RabbitExchange | str | None = None,
        routing_key: str = "",
        ack_policy: AckPolicy = AckPolicy.AUTO,
        middlewares: list[BaseMiddleware] | None = None,
        serializer: Serializer[Any] | None = None,
        retry: RetryConfig | RetryDisabled | None = None,
        tags: frozenset[str] | set[str] | None = None,
        description: str = "",
        name: str | None = None,
        prefetch_count: int | None = None,
        filter_fn: Callable[[RabbitMessage], bool] | None = None,
        reject_without_dlx: str | None = None,
        reply_to_allow: tuple[str, ...] | None = None,
        stream: StreamConsumerConfig | None = None,
        stream_offset: StreamOffsetLike | None = None,
    ) -> Callable[[HandlerT], HandlerT]:
        """Register a subscriber handler."""
        return self._registry.subscriber(
            queue=queue,
            exchange=exchange,
            routing_key=routing_key,
            ack_policy=ack_policy,
            middlewares=middlewares,
            serializer=serializer,
            retry=retry,
            tags=tags,
            description=description,
            name=name,
            prefetch_count=prefetch_count,
            filter_fn=filter_fn,
            reject_without_dlx=reject_without_dlx,
            reply_to_allow=reply_to_allow,
            stream=stream,
            stream_offset=stream_offset,
        )

    def publisher(
        self,
        exchange: RabbitExchange | str | None = None,
        routing_key: str = "",
    ) -> Callable[[HandlerT], HandlerT]:
        """Register a result publisher."""
        return self._registry.publisher(exchange=exchange, routing_key=routing_key)

    def include_router(self, router: RabbitRouter, prefix: str = "") -> None:
        """Include routes from a RabbitRouter."""
        self._registry.include_router(router, prefix=prefix)

    # ── Lifecycle ─────────────────────────────────────────────────────────

    def start(self, worker_config: WorkerConfig | None = None) -> None:
        """Start the broker — connect, declare topology, start consuming.

        1. Connect to RabbitMQ
        2. Declare exchanges, queues, bindings per TopologyMode
        3. Declare retry topology (delay queues, DLQ)
        4. Optionally create a worker pool for concurrent processing
        5. Start consuming from all registered queues

        L14: ``last_heartbeat`` is initialized here (not left ``None`` until
        the first message/tick) so a broker that is wedged from the very
        start -- before it ever processes a message or a
        ``start_consuming()`` loop iteration -- is still caught by
        :func:`health.broker_liveness`'s staleness check, instead of
        bypassing it entirely (a ``None`` heartbeat is treated as "no
        signal available" there, which previously meant "always alive").
        """
        if self._started:
            return

        self.last_heartbeat = time.monotonic()

        # Configure structured logging if enabled
        if self._config.logging is not None:
            from rabbitkit.core.logging import configure_structlog

            configure_structlog(self._config.logging, override_existing=self._config.logging.override_existing)

        # Create transport
        self._transport = SyncTransport(
            connection_config=self._config.connection,
            socket_config=self._config.socket,
            security_config=self._config.security,
            topology_mode=self._config.topology_mode,
            confirm_delivery=self._config.publisher.confirm_delivery,
            confirm_timeout=self._config.publisher.confirm_timeout,
            on_topology_conflict=self._config.safety.on_topology_conflict,
            max_in_flight_bytes=self._config.publisher.max_in_flight_bytes,
            admission_timeout=self._config.pool.channel_acquire_timeout,
        )
        # Reconnect-attempts bound: previously hardcoded on the transport
        # and unreachable from config (see ConnectionConfig.reconnect_max_attempts).
        self._transport.max_reconnect_attempts = self._config.connection.reconnect_max_attempts
        # Before connect(), so the first connection and channel count.
        self._wire_reconnect_metric()

        self._transport.connect()
        self._transport.on_io_tick(self._mark_heartbeat)
        self._transport.on_io_tick(self._sample_metrics_throttled)
        if self._deadlines is not None:
            self._transport.on_io_tick(self._deadlines.check)
            self._transport.poll_interval = self._deadlines.poll_interval

        # Wire an opt-in FlowController's blocked/unblocked callbacks to the
        # transport now that it exists (C-6).
        if self._flow_controller is not None:
            self._transport.on_blocked(self._flow_controller.on_blocked)
            self._transport.on_unblocked(self._flow_controller.on_unblocked)

        # M2: the old M-P5 "channel_pool_size caps concurrent confirms"
        # warning was removed. The default SyncTransport publishes on a single
        # dedicated channel (not SyncChannelPool — see sync/pool.py), so
        # channel_pool_size does not gate publish concurrency or confirms;
        # tuning it changed nothing on this path. The real sync
        # confirmed-publish ceiling (RTT-bound, ~0.9k msg/s, H6) is documented
        # on SyncBroker.publish and in the README.

        # Declare topology
        self._declare_topology()
        self._notify_passive_only()

        # Install RetryMiddleware on retry-enabled routes (topology alone does
        # not retry — the middleware routes failures into the delay queues).
        self._wire_retry_middleware()

        # H2: single-worker sync consumers run the handler INLINE on the pika
        # I/O thread, so nothing services heartbeat frames while a handler
        # runs. A handler that runs longer than ~2x the heartbeat interval
        # gets its connection killed broker-side mid-handler → the ack fails,
        # the message is redelivered, and side effects can repeat (possibly in
        # a loop). worker_count>1 is immune (handlers run on pool threads while
        # the I/O thread keeps pumping). Warn so the failure mode is visible.
        single_worker = worker_config is None or worker_config.worker_count <= 1
        # processing_timeout: even a single worker runs off the I/O thread
        # (one dedicated handler thread), so that thread can settle a
        # delivery whose handler outran its deadline.
        handler_thread = single_worker and self._deadlines is not None and bool(self._registry.routes)
        if single_worker and not handler_thread and self._registry.routes and self._config.connection.heartbeat > 0:
            import warnings

            warnings.warn(
                f"Starting a single-worker sync consumer (worker_count=1) with "
                f"heartbeat={self._config.connection.heartbeat}s. Handlers run inline on "
                "the I/O thread, so any handler taking longer than ~"
                f"{self._config.connection.heartbeat * 2}s will starve heartbeats and the "
                "broker will drop the connection mid-handler (→ redelivery + duplicate "
                "side effects). For slow handlers, pass "
                "start(worker_config=WorkerConfig(worker_count=N)) so handlers run off the "
                "I/O thread, or raise ConnectionConfig.heartbeat well above your worst-case "
                "handler duration. Additionally (M5): a handler on THIS thread that "
                "publishes with confirms waits for the broker confirm UNBOUNDED — "
                "confirm_timeout cannot be enforced from the owner thread itself; "
                "worker_count>1 publishes marshal through the bounded cross-thread "
                "path instead.",
                RuntimeWarning,
                stacklevel=2,
            )

        # Create worker pool if requested
        if worker_config is not None and worker_config.worker_count > 1:
            # M2: the old channel_pool_size deadlock warning was removed — the
            # default SyncTransport publishes on a single dedicated publisher
            # channel, NOT through SyncChannelPool (see sync/pool.py), so
            # worker_count vs channel_pool_size cannot cause the described
            # publish deadlock. Tuning channel_pool_size changed nothing on
            # this path; the warning only misled operators.
            # Override prefetch_count if prefetch_per_worker is set
            if worker_config.prefetch_per_worker is not None:
                self._consumer_config = replace(
                    self._config.consumer,
                    prefetch_count=worker_config.worker_count * worker_config.prefetch_per_worker,
                )
            self._worker_pool = SyncWorkerPool(config=worker_config)
            self._worker_pool.start()
        elif handler_thread:
            self._worker_pool = SyncWorkerPool(config=worker_config, threaded=True)
            self._worker_pool.start()

        # Start consuming
        for route in self._registry.routes:
            self._start_consumer(route)

        self._started = True
        self._set_lifecycle_gauges(connected=True)
        logger.info(
            "SyncBroker started with %d routes",
            len(self._registry.routes),
        )

    def _in_flight_inc(self) -> None:
        with self._in_flight_cond:
            self._in_flight += 1

    def _in_flight_dec(self) -> None:
        with self._in_flight_cond:
            if self._in_flight > 0:
                self._in_flight -= 1
            if self._in_flight == 0:
                self._in_flight_cond.notify_all()

    def _wait_in_flight(self, deadline: float | None) -> None:
        """Wait for in-flight handlers to finish (bounded by deadline).

        H2: polls in short slices and pumps the transport's I/O loop between
        them (rather than one long condvar wait) so a worker thread's
        ack/nack/reject — marshaled onto the transport's owner thread via
        ``_run_on_io_thread`` once a consume loop has run — actually gets
        drained instead of stalling for the whole wait. Safe only because
        ``stop()`` (and therefore this method) runs on the transport's owner
        thread, matching ``SyncBroker.run()``'s call pattern.
        """
        transport = self._transport
        poll = 0.05
        with self._in_flight_cond:
            if self._in_flight == 0:
                return
            while self._in_flight > 0:
                if transport is not None:
                    self._pump(poll)
                if deadline is None:
                    self._in_flight_cond.wait(timeout=poll)
                    continue
                remaining = max(0.0, deadline - time.monotonic())
                if remaining <= 0:
                    break
                self._in_flight_cond.wait(timeout=min(poll, remaining))
            if self._in_flight > 0:
                logger.warning(
                    "SyncBroker.stop: %d in-flight handler(s) still running after "
                    "graceful drain deadline; disconnecting anyway",
                    self._in_flight,
                )

    def stop(self, timeout: float | None = None) -> None:
        """Stop the broker - cancel consumers, drain pool, drain in-flight, disconnect.

        ``timeout`` defaults to ``ConsumerConfig.graceful_timeout`` (C-2). The
        whole stop sequence is bounded by an overall deadline.

        C5: consumers are cancelled FIRST, before the worker pool is drained.
        Draining the pool before cancelling left the consumer active for the
        entire (potentially graceful_timeout-long) drain wait — a message
        delivered in that window was submitted to a pool already mid-shutdown:
        ``SyncWorkerPool.submit()`` either raises ``RuntimeError`` (uncaught,
        propagating into pika's callback machinery) or, once ``.stop()`` has
        fully returned, silently runs the handler *inline* on the pika I/O
        thread — either way the message is never cleanly settled before
        ``disconnect()``, so it is redelivered (duplicate-processing risk) on
        the next connection. Cancelling first stops new deliveries outright,
        so the pool only ever drains work that was already in flight.
        """
        if not self._started:
            return

        effective = timeout if timeout is not None else self._consumer_config.graceful_timeout
        deadline = None if effective is None else time.monotonic() + effective

        # Stream routes: from here a nack/reject hands a delivery back, so
        # its offset must not advance.
        for tracker in self._stream_trackers.values():
            tracker.begin_shutdown()

        # Cancel all consumers FIRST — stop new deliveries before draining
        # anything, so nothing new arrives while the pool/in-flight drain runs.
        if self._transport is None:  # pragma: no cover — defensive (assert was stripped under -O)
            return
        for route in self._registry.routes:
            if route.consumer_tag:
                self._transport.cancel_consumer(route.consumer_tag)

        # Drain the worker pool (let in-flight pooled tasks finish), bounded by
        # the outer deadline. H2: pass the transport's pump so a worker
        # thread's marshaled ack/nack/reject is actually drained during the
        # wait, instead of the transport falling back to an unsafe inline
        # cross-thread call once the consume loop has stopped.
        if self._worker_pool is not None:
            remaining = None if deadline is None else max(0.0, deadline - time.monotonic())
            self._worker_pool.stop(timeout=remaining, pump=self._pump)
            self._worker_pool = None

        # Drain inline in-flight handlers (C-2).
        self._wait_in_flight(deadline)

        # Commit the stream offsets, so the next start resumes right after
        # the last processed message.
        for tracker in self._stream_trackers.values():
            tracker.flush()

        # Close RPC client if used
        if self._rpc_client is not None:
            self._rpc_client.close()
            self._rpc_client = None

        # Disconnect
        if self._transport:
            self._transport.disconnect()

        self._started = False
        self._set_lifecycle_gauges(connected=False)
        logger.info("SyncBroker stopped")

    def _pump(self, time_limit: float = 0.05) -> None:
        """Drive the I/O loop during a drain (owner thread) and keep settling
        deliveries whose ``processing_timeout`` passed meanwhile."""
        transport = self._transport
        if transport is None:  # pragma: no cover — defensive; only called while started
            return
        transport.pump(time_limit)
        if self._deadlines is not None:
            self._deadlines.check()

    def _install_sigterm_handler(self) -> None:
        """Install a SIGTERM handler that breaks the pika consume loop (C-1).

        pika's BlockingConnection is not signal-safe, so the handler spawns a
        short-lived daemon thread that calls ``transport.stop_consuming()``.
        Only installed when running in the main thread; failures are ignored.
        """
        try:
            self._original_handlers[signal.SIGTERM] = signal.signal(signal.SIGTERM, self._on_sigterm)
        except (ValueError, OSError):  # pragma: no cover - not in main thread - best effort
            logger.debug("SIGTERM handler not installed (not in main thread)")

    def _restore_signal_handlers(self) -> None:
        for sig, prev in self._original_handlers.items():
            try:
                signal.signal(sig, prev)
            except (ValueError, OSError):  # pragma: no cover
                pass
        self._original_handlers.clear()

    def _on_sigterm(self, signum: int, frame: Any) -> None:
        logger.info("Received SIGTERM; initiating graceful drain")
        # pika BlockingConnection is not signal-safe: do the stop on a thread.
        transport = self._transport
        if transport is None:
            return

        def _drain() -> None:
            try:
                transport.stop_consuming()
            except Exception:  # pragma: no cover - best effort
                logger.warning("stop_consuming raised during SIGTERM drain", exc_info=True)

        self._sigterm_thread = threading.Thread(target=_drain, name="rabbitkit-sigterm", daemon=True)
        self._sigterm_thread.start()

    def run(self, worker_config: WorkerConfig | None = None) -> None:
        """Start and run the blocking consume loop.

        Blocks until SIGINT/SIGTERM or stop() is called. Installs a SIGTERM
        handler (C-1) so k8s pod termination drains instead of hard-killing.
        Recovers from connection drops by reconnecting, re-declaring topology,
        and re-subscribing all consumers - pika's BlockingConnection has no
        built-in recovery, so without this a single blip kills the consumer.

        ``worker_config`` is forwarded to :meth:`start`, so a multi-worker
        consumer (``worker_count > 1``) also gets the recovery loop.
        """
        self.start(worker_config=worker_config)
        self._install_sigterm_handler()
        connection_errors = get_connection_errors()
        try:
            while True:
                try:
                    if self._transport is None:
                        break
                    self._transport.start_consuming()
                    break  # clean stop_consuming() -> exit
                except KeyboardInterrupt:
                    break
                except connection_errors as exc:
                    logger.warning("consumer connection lost; recovering", error=str(exc))
                    self._recover_consumers(exc)
        finally:
            self._restore_signal_handlers()
            self.stop()

    def pump_idle(self, time_limit: float = 0.05) -> None:
        """Service the connection's I/O loop without consuming (idle keep-alive).

        ``run()``/``start_consuming()`` pumps ``process_data_events()``
        continuously while consumers are registered, which incidentally
        keeps the (single, shared) connection's heartbeats serviced too —
        see ``sync/transport.py``'s module docstring on the one-connection
        model. A **publish-only** broker (no registered routes, or one that
        never calls ``run()``) has nothing driving that pump: the connection
        is only touched when ``publish()`` actually runs, so a long idle gap
        can get it heartbeat-timed-out broker-side, and a dead connection is
        only discovered (and reconnected) on the *next* publish attempt.

        Call this periodically — from the SAME thread that called
        ``start()``, same invariant as every other transport call — from
        your own idle loop (e.g. between polling for work) to reconnect
        proactively if the connection died, service pending heartbeat
        frames, and refresh the liveness heartbeat (see
        ``health.broker_liveness``) even though no message was delivered.
        A no-op if the broker is not started.
        """
        if self._transport is None:
            return
        self._transport.ensure_connected()
        self._transport.pump(time_limit)
        self._mark_heartbeat()
        self._sample_metrics_throttled()

    # ── Publishing ────────────────────────────────────────────────────────

    def publish(
        self,
        envelope: MessageEnvelope | None = None,
        *,
        exchange: str = "",
        routing_key: str = "",
        body: bytes | str | dict[str, Any] | None = None,
        headers: dict[str, Any] | None = None,
        content_type: str = "application/json",
        correlation_id: str | None = None,
        reply_to: str | None = None,
        message_id: str | None = None,
    ) -> PublishOutcome:
        """Publish a message.

        Accepts either a pre-built ``MessageEnvelope`` or individual kwargs::

            # Envelope form (full control):
            broker.publish(MessageEnvelope(routing_key="orders.created", body=b"..."))

            # Kwargs form (convenient):
            broker.publish(
                exchange="orders",
                routing_key="orders.created",
                body={"order_id": 123},
                headers={"x-tenant": "acme"},
            )

        When ``body`` is a dict or str it is JSON-encoded automatically.

        When an opt-in ``FlowController`` is configured (``broker.flow_controller
        = fc``), a publish slot is acquired before and released after the
        transport publish so backpressure/rate-limiting applies to the hot path.
        Without a controller this is a plain pass-through.

        When ``middlewares=[...]`` was passed to the constructor, each
        middleware's ``publish_scope`` wraps this call (e.g. ``SigningMiddleware``
        signs the envelope) — see ``publish_middlewares``. Middleware wraps
        OUTSIDE the flow-control gate, so a middleware-transformed envelope is
        what gets rate-limited/blocked, and what the transport actually sends.

        Throughput note (H6): with publisher confirms on (the default), this
        waits for a broker confirm per message on a single channel, so it is
        RTT-bound at ~0.9k msg/s and does NOT scale with worker_count — pika's
        BlockingConnection serializes confirms, it cannot pipeline them. To
        drain a large backlog fast, use AsyncBroker + AsyncBatchPublisher
        (pipelined confirms, ~6.1k msg/s) or more processes.

        ``message_id`` (kwargs form only) sets the AMQP message id instead of
        a fresh uuid4, so the same logical message can be republished after
        an unknown outcome and deduplicated downstream.
        """
        if envelope is not None and message_id is not None:
            raise ValueError("message_id applies to the kwargs form; set MessageEnvelope.message_id instead")
        if envelope is None:
            import json as _json

            if body is None:
                raw_body = b""
            elif isinstance(body, bytes):
                raw_body = body
            elif isinstance(body, str):
                raw_body = body.encode()
            else:
                raw_body = _json.dumps(body).encode()
            # M2: honor PublisherConfig defaults for the kwargs form (they were
            # previously dead config). Envelope-form callers keep full control.
            envelope = MessageEnvelope(
                routing_key=routing_key,
                body=raw_body,
                exchange=exchange,
                headers=headers or {},
                content_type=content_type,
                correlation_id=correlation_id,
                reply_to=reply_to,
                mandatory=self._config.publisher.mandatory,
                delivery_mode=2 if self._config.publisher.persistent else 1,
            )
            if message_id is not None:
                envelope = replace(envelope, message_id=message_id)

        # an application publish cannot carry rabbitkit's retry/DLQ
        # bookkeeping headers (opt-in; the library's own republishes bypass this).
        if self._reserved_header_stripper is not None:
            envelope = self._reserved_header_stripper(envelope)

        # M10: reject oversized bodies at publish time (input validation at
        # the trust boundary — a too-large message is a programming/policy
        # error, caught before it hits the wire).
        max_bytes = self._config.publisher.max_message_bytes
        if max_bytes and len(envelope.body) > max_bytes:
            raise MessageTooLargeError(
                f"Message body ({len(envelope.body)} bytes) exceeds "
                f"PublisherConfig.max_message_bytes ({max_bytes}). Large messages are a "
                "RabbitMQ anti-pattern — store the payload externally and publish a "
                "reference, or raise the limit if this is intentional."
            )

        if self._transport is None:
            raise BrokerNotStartedError("Broker not started. Call start() first.")
        transport = self._transport  # narrowed local capture for the closure below

        def do_transport_publish(env: MessageEnvelope) -> PublishOutcome:
            fc = self._flow_controller
            if fc is not None:
                if not fc.acquire():
                    # Dropped by backpressure policy (drop/timeout). Do not publish.
                    return PublishOutcome(
                        status=PublishStatus.NOT_SENT,
                        exchange=env.exchange,
                        routing_key=env.routing_key,
                        error=BackpressureError("publish dropped by backpressure policy"),
                        reason=PublishReason.BACKPRESSURE_DROPPED,
                    )
                try:
                    return transport.publish(env)
                finally:
                    fc.release()
            return transport.publish(env)

        if self._publish_middlewares:
            chain = self._pipeline.compose_broker_publish_sync(self._publish_middlewares)
            outcome: PublishOutcome = chain(envelope, do_transport_publish)
            return outcome
        return do_transport_publish(envelope)

    # ── Bulk operations: metrics plumbing (plan §11) ─────────────────────

    def _bulk_metrics(self) -> tuple[Any, Any] | None:
        """``(collector, MetricsConfig)`` from the first MetricsMiddleware with a
        collector — publish-middlewares first, then any route. None = no metrics."""
        from rabbitkit.middleware.metrics import MetricsMiddleware

        candidates: list[Any] = list(self._publish_middlewares)
        for route in self._registry.routes:
            candidates.extend(route.route_middlewares)
        for mw in candidates:
            if isinstance(mw, MetricsMiddleware) and mw.collector is not None:
                return mw.collector, mw.config
        return None

    def _record_bulk_item(self, item: BulkPublishItem) -> None:
        found = self._bulk_metrics()
        if found is None:
            return
        collector, cfg = found
        collector.inc_counter(cfg.bulk_publish_items_total, {"status": item.status.value, "reason": item.reason})

    def _record_bulk_batch(self, size: int) -> None:
        found = self._bulk_metrics()
        if found is None:
            return
        collector, cfg = found
        collector.observe_histogram(cfg.bulk_publish_batch_size, {}, float(size))

    def _settlement_item_hook(self, action: SettlementAction) -> Callable[[SettlementItem], None] | None:
        found = self._bulk_metrics()
        if found is None:
            return None
        collector, cfg = found

        def _hook(item: SettlementItem) -> None:
            collector.inc_counter(cfg.settlement_items_total, {"action": action.value, "status": item.status.value})

        return _hook

    def _set_lifecycle_gauges(self, *, connected: bool) -> None:
        """Emit the declared-but-previously-missing lifecycle gauges:
        ``broker_connected``, ``consumer_active`` and ``worker_pool_pending``."""
        found = self._bulk_metrics()
        if found is None:
            return
        collector, cfg = found
        set_gauge = getattr(collector, "set_gauge", None)
        if set_gauge is None:
            return
        set_gauge(cfg.broker_connected, {}, 1.0 if connected else 0.0)
        set_gauge(cfg.consumer_active, {}, float(len(self._registry.routes)) if connected else 0.0)
        pool = self._worker_pool
        set_gauge(cfg.worker_pool_pending, {}, float(pool.pending_count) if pool is not None else 0.0)
        metrics = self._broker_metrics
        if metrics is None:
            return
        if connected:
            self._sample_metrics()
        else:
            metrics.stopped(route.queue.name for route in self._registry.routes)

    _METRICS_SAMPLE_INTERVAL: float = 5.0

    def _sample_metrics_throttled(self) -> None:
        """I/O-tick hook: sample at most every ``_METRICS_SAMPLE_INTERVAL``."""
        if self._broker_metrics is None:
            return
        now = time.monotonic()
        if now - self._metrics_sampled_at >= self._METRICS_SAMPLE_INTERVAL:
            self._metrics_sampled_at = now
            self._sample_metrics()

    def _sample_metrics(self) -> None:
        """Refresh the sampled broker gauges: connection state, open
        channels, publishes and bytes in flight, blocked state, per-route
        consuming, worker-pool backlog."""
        metrics, transport = self._broker_metrics, self._transport
        if metrics is None or transport is None:
            return
        try:
            metrics.set_states({"shared": transport.is_connected()})
            limiter = transport.byte_limiter
            metrics.sample(
                channels_active=transport.channels_active,
                publish_in_flight=transport.publishes_in_flight,
                publish_in_flight_bytes=limiter.used if limiter is not None else None,
                connection_blocked=transport.is_blocked,
                connection_blocked_reason=transport.blocked_reason,
                consuming={
                    route.queue.name: bool(route.consumer_tag) and not route.runtime_state.consumer_cancelled
                    for route in self._registry.routes
                },
            )
            pool = self._worker_pool
            if pool is not None:
                metrics.sample_worker_pool(pool.pending_count)
        except Exception:  # a metrics sample must never break the I/O loop
            logger.warning("Sampling broker metrics failed", exc_info=True)

    def preflight(
        self,
        profile: ReliabilityProfile | str = ReliabilityProfile.STANDARD,
        *,
        management_client: Any | None = None,
        vhost: str = "/",
    ) -> PreflightReport:
        """Verify reliability-profile prerequisites for this broker's config
        and registered routes (plan §9). Broker-side policy checks need a
        read-only management client; without one they are reported
        ``UNVERIFIED`` — never silently green. Pure inspection; no I/O on
        the AMQP connection and no policy mutation."""
        return run_preflight(
            self._config,
            profile,
            routes=self._registry.routes,
            management_client=management_client,
            vhost=vhost,
        )

    # ── Bulk publishing (plan §7) ────────────────────────────────────────

    def iter_publish(
        self,
        envelopes: Iterable[MessageEnvelope],
        options: BulkPublishOptions | None = None,
    ) -> Iterator[BulkPublishItem]:
        """Publish a (possibly unbounded) iterable, yielding one
        :class:`~rabbitkit.core.bulk.BulkPublishItem` per input as it settles.

        Every item goes through the SAME path as :meth:`publish` — publish
        middlewares, flow control, size limit, transport — so single and
        bulk publishing share every safeguard. The sync transport confirms
        one publish at a time (pika's BlockingConnection cannot pipeline
        confirms), so this is sequential; ``options.max_in_flight`` has no
        effect here. ``options.overall_timeout`` does: past the deadline
        remaining inputs are yielded ``NOT_SENT`` without touching the wire.

        Memory is bounded by the caller: results are yielded, not collected.
        """
        if self._transport is None:
            raise BrokerNotStartedError("Broker not started. Call start() first.")
        opts = options or BulkPublishOptions()
        preparer = PublishPreparer(
            max_message_bytes=self._config.publisher.max_message_bytes,
            max_buffer_bytes=opts.max_buffer_bytes,
        )
        return iter_publish_sync(
            envelopes,
            self.publish,
            options=opts,
            preparer=preparer,
            on_item=self._record_bulk_item,
        )

    def publish_many(
        self,
        envelopes: Sequence[MessageEnvelope],
        options: BulkPublishOptions | None = None,
    ) -> BulkPublishResult:
        """Publish a bounded collection and return input-ordered per-item outcomes.

        Never raises for a failed item — inspect ``result.items`` (or call
        ``result.raise_for_status()``). Raises ``ValueError`` before publishing
        anything if ``len(envelopes)`` exceeds ``options.max_items``; use
        :meth:`iter_publish` for streams. See
        :class:`~rabbitkit.core.types.BulkPublishStatus` for what each state
        means and what to do about it — in particular ``UNKNOWN`` items may
        have reached the broker and must be reconciled, not blindly replayed.
        """
        opts = options or BulkPublishOptions()
        if len(envelopes) > opts.max_items:
            raise ValueError(
                f"publish_many received {len(envelopes)} envelopes, more than BulkPublishOptions.max_items "
                f"({opts.max_items}); use iter_publish() for large or unbounded inputs."
            )
        started = datetime.now(UTC)
        items = list(self.iter_publish(envelopes, opts))
        self._record_bulk_batch(len(envelopes))
        return BulkPublishResult(
            items=tuple(sorted(items, key=lambda it: it.index)),
            started_at=started,
            finished_at=datetime.now(UTC),
        )

    # ── Selected settlement (plan §8) ────────────────────────────────────

    def ack_many(self, messages: Iterable[RabbitMessage], *, fail_fast: bool = True) -> SettlementReport:
        """Ack exactly the given deliveries — each with its own ``multiple=False``
        frame. Never a cumulative ack: an unselected, still-running sibling on
        the same channel is untouched.

        Validation runs before any I/O: duplicates, already-settled messages,
        no-ack deliveries and STALE handles (channel rebuilt since delivery)
        are reported per item. With ``fail_fast=True`` (default) any problem
        aborts the whole call with every valid item ``NOT_ATTEMPTED``.

        The report says ``DISPATCHED``, not "confirmed" — RabbitMQ sends no
        acknowledgement for a consumer ack. Messages must come from THIS
        broker (MANUAL ack policy, or a handler that deferred settlement).
        """
        return settle_many_sync(
            messages,
            SettlementAction.ACK,
            fail_fast=fail_fast,
            on_item=self._settlement_item_hook(SettlementAction.ACK),
        )

    def nack_many(
        self,
        messages: Iterable[RabbitMessage],
        *,
        requeue: bool = True,
        fail_fast: bool = True,
    ) -> SettlementReport:
        """Nack exactly the given deliveries (individually — see :meth:`ack_many`).

        ``requeue=False`` dead-letters (or, without a DLX, DISCARDS) each
        message; for ordinary handler failures prefer the retry/terminal
        path (``RetryConfig``) over raw nacks.
        """
        return settle_many_sync(
            messages,
            SettlementAction.NACK,
            requeue=requeue,
            fail_fast=fail_fast,
            on_item=self._settlement_item_hook(SettlementAction.NACK),
        )

    def _flow_controlled_internal_publish(self, env: MessageEnvelope) -> PublishOutcome:
        """M18: apply the broker's ``FlowController`` (if configured) to an
        INTERNAL republish — ``RetryMiddleware``'s delay-queue publish, or a
        handler's result/RPC-reply publish — used as their ``publish_fn``
        instead of the raw, unthrottled ``transport.publish``.

        Deliberately diverges from ``do_transport_publish`` above: a
        configured ``on_blocked="raise"`` must NEVER raise ``BackpressureError``
        out of here. ``RetryMiddleware`` and the pipeline's result-publish path
        only understand a returned ``PublishOutcome`` (checked via ``.ok``),
        not exceptions — letting one escape would propagate as an unclassified
        error, default to PERMANENT, and reject/destroy the message instead of
        the existing safe nack+requeue-on-publish-failure behavior both paths
        already implement. So regardless of the configured policy, a
        blocked/dropped slot here always resolves as a failed
        ``PublishOutcome`` (status=NOT_SENT, reason ``backpressure_dropped``),
        never an exception — the same outcome shape a real transport failure
        already produces.
        """
        if self._transport is None:  # pragma: no cover — defensive; callers only run while consuming
            raise BrokerNotStartedError("Broker not started. Call start() first.")
        if self._deadlines is not None and self._deadlines.current_expired():
            # A handler past its processing_timeout: its delivery was already
            # settled at the deadline, so its result / retry / DLQ copy would
            # duplicate it. Never sent (the async handler is cancelled instead).
            return PublishOutcome(
                status=PublishStatus.NOT_SENT,
                exchange=env.exchange,
                routing_key=env.routing_key,
                reason=PublishReason.CANCELLED,
            )
        transport = self._transport
        fc = self._flow_controller
        if fc is None:
            return transport.publish(env)
        try:
            acquired = fc.acquire()
        except BackpressureError as exc:
            return PublishOutcome(
                status=PublishStatus.NOT_SENT,
                exchange=env.exchange,
                routing_key=env.routing_key,
                error=exc,
                reason=PublishReason.BACKPRESSURE_DROPPED,
            )
        if not acquired:
            return PublishOutcome(
                status=PublishStatus.NOT_SENT,
                exchange=env.exchange,
                routing_key=env.routing_key,
                error=BackpressureError("publish dropped by backpressure policy"),
                reason=PublishReason.BACKPRESSURE_DROPPED,
            )
        try:
            return transport.publish(env)
        finally:
            fc.release()

    def request(
        self,
        routing_key: str,
        body: bytes,
        *,
        timeout: float = 5.0,
        exchange: str = "",
        headers: dict[str, Any] | None = None,
    ) -> RabbitMessage:
        """Send an RPC request and wait for a response (sync).

        Lazily initializes an RPCClient on first call.
        The client is shared across calls and closed in stop().
        """
        if self._transport is None:
            raise BrokerNotStartedError("Broker not started. Call start() first.")
        if self._rpc_client is None:
            from rabbitkit.rpc import RPCClient

            self._rpc_client = RPCClient(self._transport)
        return self._rpc_client.call(routing_key, body, timeout=timeout, exchange=exchange, headers=headers)

    # ── Internal ──────────────────────────────────────────────────────────

    def _recover_consumers(self, cause: BaseException | None = None) -> None:
        """Reconnect and re-establish topology + subscriptions after a drop."""
        if self._transport is None:
            return
        self._transport.reconnect(cause)
        self._declare_topology()
        for route in self._registry.routes:
            self._start_consumer(route)

    def _wire_retry_middleware(self) -> None:
        """Install ``RetryMiddleware`` on routes whose retry is enabled.

        ``_declare_topology`` declares the retry/DLQ *topology* (delay queues +
        source-queue DLX), but the ``RetryMiddleware`` that actually routes a
        failed message into the delay queues must also run in the route's
        middleware chain. Without it, ``retry=RetryConfig(...)`` would build the
        topology while transient failures ``nack(requeue=True)`` in a hot loop —
        the delay queues would never receive anything and ``max_retries`` would
        never be enforced. This wires both halves from the single retry switch
        (``RabbitConfig.retry`` / ``@subscriber(retry=...)``).

        Placed outer of ordinary user middlewares (e.g. ``TimeoutMiddleware``) so
        retry can classify and re-queue exceptions they raise, but inner of any
        ``ExceptionMiddleware`` (the documented true-outermost layer) — see
        :func:`rabbitkit.middleware.retry.retry_middleware_insertion_index`.

        Idempotent: routes that already carry a ``RetryMiddleware`` — supplied
        explicitly via ``middlewares=[...]`` or auto-wired on a previous start —
        are left untouched (no double-retry, no stacking on reconnect).
        """
        if self._transport is None:
            return

        from rabbitkit.middleware.metrics import MetricsMiddleware
        from rabbitkit.middleware.retry import (
            RetryMiddleware,
            retry_middleware_insertion_index,
            warn_retry_middleware_without_topology,
            warn_retry_without_confirms,
        )
        from rabbitkit.middleware.signing import check_signing_retry_conflict

        wired = False
        for route in self._registry.routes:
            retry_config = route.effective_retry_config(self._config.retry)
            has_retry_mw = any(isinstance(mw, RetryMiddleware) for mw in route.route_middlewares)
            if retry_config is None:
                if has_retry_mw:
                    # Half-configured: a RetryMiddleware runs but no retry topology
                    # was declared, so its delay-queue publishes target non-existent
                    # queues and are silently dropped. Surface it loudly.
                    warn_retry_middleware_without_topology(route.name)
                continue
            # H1: signing + retry destroys every retried message — fail fast.
            check_signing_retry_conflict(route.name, route.route_middlewares)
            if has_retry_mw:
                # A user-constructed RetryMiddleware: inject the broker's
                # confirmed publish fn if none was passed, so it routes to the
                # delay queues instead of nack-hot-looping (or, historically,
                # ack-dropping) every transient failure.
                for mw in route.route_middlewares:
                    if isinstance(mw, RetryMiddleware):
                        mw.ensure_publish_fns(publish_fn=self._flow_controlled_internal_publish)
                continue
            # (No confirms warning for the RETRY context: retry envelopes are
            # published mandatory=True, which forces per-publish confirm mode
            # on both transports even when confirm_delivery=False — the
            # ack-after-confirmed-outcome invariant holds regardless.)
            index = retry_middleware_insertion_index(route.route_middlewares)
            # M2: wire in an existing route MetricsMiddleware (if any) so
            # messages_retried_total/dead_lettered_total are observable.
            metrics_mw = next((mw for mw in route.route_middlewares if isinstance(mw, MetricsMiddleware)), None)
            route.route_middlewares.insert(
                index,
                RetryMiddleware(
                    retry_config,
                    publish_fn=self._flow_controlled_internal_publish,  # M18: honor FlowController
                    metrics_collector=metrics_mw.collector if metrics_mw else None,
                    metrics_config=metrics_mw.config if metrics_mw else None,
                ),
            )
            wired = True

        if not self._config.publisher.confirm_delivery:
            for route in self._registry.routes:
                if route.result_publisher is not None:
                    warn_retry_without_confirms(route.name, context="result")  # M4

        if wired:
            # Drop any middleware chains cached before the retry mw was installed.
            self._pipeline.clear_caches()

    def _wire_reconnect_metric(self) -> None:
        """Wire the broker metrics (:class:`BrokerMetrics`) to the transport's
        hooks via the first ``MetricsMiddleware`` with a collector: publish
        middlewares first, then any route (a publish-only broker gets
        connection and channel metrics too). No-op without metrics. The sync
        broker has one connection, reported as role ``"shared"``.
        """
        self._broker_metrics = None
        transport = self._transport
        if transport is None:
            return
        found = self._bulk_metrics()
        if found is None:
            return
        collector, cfg = found
        metrics = BrokerMetrics(collector, cfg, roles=("shared",))
        self._broker_metrics = metrics
        transport.on_reconnect(metrics.reconnected)
        transport.on_channel_opened(metrics.channel_opened)
        transport.on_channel_rebuilt(metrics.channel_rebuilt)
        transport.on_connection_state(metrics.connection_state)
        transport.on_reconnect_attempt(lambda _attempt, error: metrics.reconnect_failed("shared", error))
        transport.on_blocked(lambda: metrics.blocked(True, transport.blocked_reason))
        transport.on_unblocked(lambda: metrics.blocked(False))
        transport.on_publish_outcome(metrics.publish_outcome)
        metrics.take_over_confirm_latency(
            [*self._publish_middlewares, *(mw for route in self._registry.routes for mw in route.route_middlewares)]
        )

    def _declare_topology(self) -> None:
        """Declare exchanges, queues, and bindings for all routes."""
        if self._transport is None:
            return

        for route in self._registry.routes:
            # Declare exchange
            if route.exchange is not None:
                self._transport.declare_exchange(route.exchange)

                # Exchange-to-exchange binding
                bind_kwargs = route.exchange.to_bind_kwargs()
                if bind_kwargs is not None:
                    self._transport.bind_exchange(
                        destination=bind_kwargs["destination"],
                        source=bind_kwargs["source"],
                        routing_key=bind_kwargs["routing_key"],
                        arguments=bind_kwargs["arguments"],
                    )

            # Determine retry config early so source queue can include DLQ routing
            retry_config = route.effective_retry_config(self._config.retry)
            # C3: a route with no dead-letter path can reject(requeue=False)
            # (permanent errors, filter_fn, RejectMessage) and RabbitMQ would
            # DISCARD the message. Apply SafetyConfig.reject_without_dlx:
            # auto-provision "<queue>.dlq" (default), fail startup, or warn
            # and allow discard. Only under AUTO_DECLARE — in passive/manual
            # modes rabbitkit does not own the queue's arguments.
            safety_dlq_name: str | None = None
            if self._config.topology_mode is TopologyMode.AUTO_DECLARE:
                safety_dlq_name = route.resolve_safety_dlq(self._config.safety, self._config.retry)
            # A queue that IS another route's DLQ is terminal — consuming your
            # own DLQ is a legitimate pattern (inspect/replay consumers), and
            # auto-chaining more topology onto it (safety DLX injection, or
            # BROKER-DEFAULT retry inherited by the DLQ-consumer route) would
            # re-declare the DLQ with different arguments than the retry/
            # safety topology already declared it with — a 406 inequivalent-
            # arg startup failure, caught by the real-broker CI suite. An
            # EXPLICIT per-route retry= on a DLQ consumer still wins.
            is_anothers_dlq = any(
                other is not route and route.queue.name == f"{other.queue.name}.dlq" for other in self._registry.routes
            )
            if is_anothers_dlq:
                safety_dlq_name = None
                if route.retry_override is None:
                    retry_config = None  # don't inherit broker-default retry

            if retry_config is not None:
                retry_router = RetryRouter(retry_config)
                dlq_name = retry_router.get_dlq_name(route.queue.name)
                # Re-declare source queue with x-dead-letter fields so RabbitMQ
                # automatically routes nacked/rejected messages to the DLQ.
                import dataclasses

                source_queue = dataclasses.replace(
                    route.queue,
                    dead_letter_exchange="",
                    dead_letter_routing_key=dlq_name,
                )
            elif safety_dlq_name is not None:
                import dataclasses

                logger.info(
                    "Auto-provisioned DLQ %r for queue %r (reject_without_dlx=auto_provision)",
                    safety_dlq_name,
                    route.queue.name,
                )
                source_queue = dataclasses.replace(
                    route.queue,
                    dead_letter_exchange="",
                    dead_letter_routing_key=safety_dlq_name,
                )
            else:
                source_queue = route.queue

            # Declare queue (with DLQ routing arguments if retry/safety DLX applies)
            if source_queue is route.queue and is_anothers_dlq and route.queue.queue_type == QueueType.QUORUM:
                # Consuming another route's quorum DLQ: declare it exactly as
                # that route's retry/safety topology does, or the two
                # declarations disagree on x-delivery-limit (406).
                self._declare_dlq(
                    replace(
                        route.queue,
                        delivery_limit=(
                            route.queue.delivery_limit
                            if route.queue.delivery_limit is not None
                            else dlq_delivery_limit(self._broker_server_version())
                        ),
                    )
                )
            else:
                self._transport.declare_queue(source_queue)

            # Bind queue to exchange (C4: bind_arguments matter for headers exchanges)
            if route.exchange is not None:
                self._transport.bind_queue(
                    queue=route.queue.name,
                    exchange=route.exchange.name,
                    routing_key=to_binding_key(route.queue.routing_key),
                    arguments=route.queue.bind_arguments or None,
                )

            # Declare retry/DLQ topology if retry is enabled
            if retry_config is not None:
                exchange_name = route.exchange.name if route.exchange else ""
                delay_queues = retry_router.get_delay_queue_definitions(
                    route.queue.name,
                    exchange_name,
                    source_queue_type=route.queue.queue_type,
                    broker_version=self._broker_server_version(),
                )
                dlq_name = retry_router.get_dlq_name(route.queue.name)
                for delay_queue in delay_queues:
                    if delay_queue.name == dlq_name:
                        self._declare_dlq(delay_queue)
                    else:
                        self._transport.declare_queue(delay_queue)
            elif safety_dlq_name is not None:
                # Inherit quorum from a quorum source (see RetryRouter DLQ
                # note): the DLQ stores failures indefinitely.
                self._declare_dlq(
                    dlq_queue_definition(
                        safety_dlq_name,
                        quorum=route.queue.queue_type == QueueType.QUORUM,
                        broker_version=self._broker_server_version(),
                    )
                )

    def _notify_passive_only(self) -> None:
        """[retry/topology hook] PASSIVE_ONLY startup notice (see topology_validation)."""
        from rabbitkit.core.topology_validation import log_passive_only_limits

        log_passive_only_limits(self._config.topology_mode, self._registry.routes)

    def _broker_server_version(self) -> str | None:
        version = getattr(self._transport, "server_version", None)
        return version if isinstance(version, str) else None

    def _declare_dlq(self, dlq: RabbitQueue) -> None:
        """Declare a DLQ, leaving an existing one exactly as it is.

        A quorum DLQ on RabbitMQ 4.x carries ``x-delivery-limit: -1`` (see
        ``dlq_queue_definition``). RabbitMQ refuses to add that argument to
        a queue declared without it, and refuses to drop it from one declared
        with it (406 either way). So a DLQ that already exists is not
        redeclared at all; its delivery limit is the operator's to fix, with
        a policy, and ``DLQInspector`` refuses to browse it until they do.
        """
        if dlq.queue_type is QueueType.QUORUM and self._config.topology_mode is TopologyMode.AUTO_DECLARE:
            # Probe whatever the version: an existing DLQ may carry the
            # argument (created by 0.19 on 4.x) even when this connection
            # can't tell which broker version it is talking to.
            assert self._transport is not None
            if self._transport.queue_exists(dlq.name) is True:
                logger.debug("DLQ %r already exists; not redeclaring it", dlq.name)
                return
        assert self._transport is not None
        self._transport.declare_queue(dlq)

    def _mark_heartbeat(self) -> None:
        """Refresh the liveness heartbeat (I-4/L14).

        Called both per delivered message (``on_message`` below) and once
        per ``start_consuming()`` I/O loop tick (wired via
        ``transport.on_io_tick`` in :meth:`start`) -- the latter is what
        keeps a healthy but message-idle consumer from being mistaken for a
        wedged one by :func:`health.broker_liveness`.
        """
        self.last_heartbeat = time.monotonic()

    def _start_consumer(self, route: RouteDefinition) -> None:
        """Start consuming for a single route."""
        if self._transport is None:
            return

        pool = self._worker_pool

        def on_message(message: RabbitMessage) -> None:
            """Process incoming message through the pipeline."""
            # Track inline in-flight so stop() can drain gracefully (C-2).
            self._in_flight_inc()
            self._mark_heartbeat()
            try:
                # Set the original queue in headers for retry routing.
                # H2 (spoofing): ALWAYS overwrite — a legitimate retry round-trip
                # returns to this same queue, so the overwrite is always
                # correct, while honoring a producer-set value would let a
                # malicious/buggy publisher steer retries into another
                # route's delay ladder (cross-queue injection) or a
                # nonexistent queue (requeue hot loop).
                message.headers["x-rabbitkit-original-queue"] = route.queue.name

                # Populate named routing-key segments for Path() DI
                message.path = extract_path(message.routing_key, route.queue.routing_key)

                try:
                    self._pipeline.process_sync(
                        route,
                        message,
                        publish_fn=self._flow_controlled_internal_publish,  # M18
                    )
                except Exception:
                    # M12: AUTO/NACK_ON_ERROR settle inside the pipeline and
                    # never reach here — but a MANUAL-policy handler that
                    # raises without settling used to propagate out of the
                    # delivery callback and STOP the entire run loop (one bad
                    # handler took down the broker). Contain it: log and
                    # nack-requeue if still unsettled, so the failure degrades
                    # to a redelivery instead of a broker-wide halt. Matches
                    # the pooled/async paths, which already isolate handler
                    # exceptions.
                    logger.error(
                        "Handler raised through the pipeline; nacking for redelivery",
                        queue=route.queue.name,
                        message_id=message.message_id,
                        exc_info=True,
                    )
                    if not message.is_settled:
                        message.nack(requeue=True)
            finally:
                self._in_flight_dec()

        deadlines = self._deadlines
        handler: Callable[[RabbitMessage], None] = on_message
        if deadlines is not None and pool is not None:

            def on_message_with_deadline(message: RabbitMessage) -> None:
                """processing_timeout (handler thread): see sync/deadlines.py."""
                claim = deadlines.begin(route, message)
                try:
                    on_message(message)
                except LateSettlementError:
                    pass  # the deadline settled the delivery; finish() logs the late return
                finally:
                    deadlines.finish(claim)

            handler = on_message_with_deadline

        if pool is not None:

            def on_message_pooled(message: RabbitMessage) -> None:
                pool.submit(handler, message)

            callback = on_message_pooled
        else:
            callback = on_message

        consume_kwargs: dict[str, Any] = {}
        tracker = self._stream_tracker(route)
        if tracker is not None:
            # Record each delivery's offset in arrival order (on the I/O
            # thread, before a worker pool can reorder handling); a
            # re-subscription after a reconnect starts at the processed position.
            untracked = callback

            def on_stream_message(message: RabbitMessage) -> None:
                tracker.track(message)
                untracked(message)

            callback = on_stream_message
            consume_kwargs["arguments"] = tracker.consume_arguments

        effective_prefetch = route.prefetch_count or self._consumer_config.prefetch_count
        self._wire_consumer_state()
        was_cancelled = route.runtime_state.consumer_cancelled
        route.runtime_state.consumer_cancelled = False
        consumer_tag = self._transport.consume(
            queue=route.queue.name,
            callback=callback,
            prefetch=effective_prefetch,
            **consume_kwargs,
        )
        route.runtime_state.consumer_tag = consumer_tag
        if was_cancelled:
            # Re-subscribed by a reconnect while the broker had it cancelled.
            self._consumer_state_changed(route.queue.name, cancelled=False)
        if tracker is not None:
            tracker.subscribed()

    def _wire_consumer_state(self) -> None:
        """Mirror broker-initiated consumer cancels into route state and the hooks."""
        transport: Any = self._transport  # set: _start_consumer returns early without one
        if self._consumer_state_wired is transport:
            return
        self._consumer_state_wired = transport
        transport.on_consumer_cancelled(lambda queue: self._consumer_state_changed(queue, cancelled=True))
        transport.on_consumer_resumed(lambda queue: self._consumer_state_changed(queue, cancelled=False))

    def _consumer_state_changed(self, queue: str, *, cancelled: bool) -> None:
        for route in self._registry.routes:
            if route.queue.name == queue:
                route.runtime_state.consumer_cancelled = cancelled
        metrics = self._broker_metrics
        if metrics is not None:
            if cancelled:
                metrics.consumer_cancelled(queue)
            else:
                metrics.consumer_resumed(queue)
        hook = self.on_consumer_cancelled if cancelled else self.on_consumer_resumed
        if hook is None:
            return
        try:
            hook(queue)
        except Exception:
            event = "cancelled" if cancelled else "resumed"
            logger.warning("on_consumer_%s hook raised (queue=%s)", event, queue, exc_info=True)

    def _stream_tracker(self, route: RouteDefinition) -> StreamOffsetTracker | None:
        """The offset tracker of a stream route (created on first use, which
        loads the stored offset), else None."""
        config = route.stream_config
        if config is None:
            return None
        tracker = self._stream_trackers.get(route.name)
        if tracker is None:
            tracker = StreamOffsetTracker(route_name=route.name, queue=route.queue.name, config=config)
            self._stream_trackers[route.name] = tracker
        return tracker

    # ── Public topology API (16.6) — additive, retry/topology owner ─────

    def declare_exchange(self, exchange: RabbitExchange) -> None:
        """Declare *exchange* (``AUTO_DECLARE`` only, or a ``passive=True``
        existence check under ``PASSIVE_ONLY``). See ``AsyncBroker.declare_exchange``."""
        from rabbitkit.core.topology_dispatch import check_public_topology_write

        check_public_topology_write(self._config.topology_mode, "declare_exchange", passive=exchange.passive)
        self._started_transport().declare_exchange(exchange)

    def declare_queue(self, queue: RabbitQueue) -> None:
        """Declare *queue* exactly as given. Same rules as :meth:`declare_exchange`."""
        from rabbitkit.core.topology_dispatch import check_public_topology_write

        check_public_topology_write(self._config.topology_mode, "declare_queue", passive=queue.passive)
        self._started_transport().declare_queue(queue)

    def bind_queue(
        self, queue: str, exchange: str, routing_key: str = "", arguments: dict[str, Any] | None = None
    ) -> None:
        """Bind *queue* to *exchange*. ``AUTO_DECLARE`` only."""
        from rabbitkit.core.topology_dispatch import check_public_topology_write

        check_public_topology_write(self._config.topology_mode, "bind_queue")
        self._started_transport().bind_queue(
            queue=queue, exchange=exchange, routing_key=routing_key, arguments=arguments
        )

    def bind_exchange(
        self, destination: str, source: str, routing_key: str = "", arguments: dict[str, Any] | None = None
    ) -> None:
        """Bind exchange *destination* to *source*. ``AUTO_DECLARE`` only."""
        from rabbitkit.core.topology_dispatch import check_public_topology_write

        check_public_topology_write(self._config.topology_mode, "bind_exchange")
        self._started_transport().bind_exchange(
            destination=destination, source=source, routing_key=routing_key, arguments=arguments
        )

    def verify_topology(self, management_client: Any | None = None, *, vhost: str | None = None) -> Any:
        """Read-only topology compatibility check — see ``AsyncBroker.verify_topology``."""
        from rabbitkit.core.topology_validation import verify_topology

        return verify_topology(
            list(self._registry.routes),
            management_client=management_client,
            vhost=vhost if vhost is not None else self._config.connection.vhost,
            broker_retry=self._config.retry,
        )

    def _started_transport(self) -> Any:
        if self._transport is None:
            raise BrokerNotStartedError("Broker not started. Call start() first.")
        return self._transport

Attributes

flow_controller: Any | None property writable

Optional FlowController used to throttle the publish path.

started: bool property

True between a successful start() and stop().

Public counterpart of _started — health checks (:func:rabbitkit.health.broker_health_check) read this instead of falling back to the private attribute (which emits a DeprecationWarning).

publish_middlewares: list[BaseMiddleware] property

Middlewares applied to every broker.publish() call (e.g. signing).

Set via the constructor's middlewares= param. See the comment on self._publish_middlewares for why reassigning (not mutating) is required to change this after construction.

worker_pool: SyncWorkerPool | None property

Return the worker pool (if configured).

consumer_config: ConsumerConfig property

Effective consumer config (may reflect WorkerConfig.prefetch override).

Methods:

subscriber(queue: RabbitQueue | str, exchange: RabbitExchange | str | None = None, routing_key: str = '', ack_policy: AckPolicy = AckPolicy.AUTO, middlewares: list[BaseMiddleware] | None = None, serializer: Serializer[Any] | None = None, retry: RetryConfig | RetryDisabled | None = None, tags: frozenset[str] | set[str] | None = None, description: str = '', name: str | None = None, prefetch_count: int | None = None, filter_fn: Callable[[RabbitMessage], bool] | None = None, reject_without_dlx: str | None = None, reply_to_allow: tuple[str, ...] | None = None, stream: StreamConsumerConfig | None = None, stream_offset: StreamOffsetLike | None = None) -> Callable[[HandlerT], HandlerT]

Register a subscriber handler.

Source code in src/rabbitkit/sync/broker.py
def subscriber(
    self,
    queue: RabbitQueue | str,
    exchange: RabbitExchange | str | None = None,
    routing_key: str = "",
    ack_policy: AckPolicy = AckPolicy.AUTO,
    middlewares: list[BaseMiddleware] | None = None,
    serializer: Serializer[Any] | None = None,
    retry: RetryConfig | RetryDisabled | None = None,
    tags: frozenset[str] | set[str] | None = None,
    description: str = "",
    name: str | None = None,
    prefetch_count: int | None = None,
    filter_fn: Callable[[RabbitMessage], bool] | None = None,
    reject_without_dlx: str | None = None,
    reply_to_allow: tuple[str, ...] | None = None,
    stream: StreamConsumerConfig | None = None,
    stream_offset: StreamOffsetLike | None = None,
) -> Callable[[HandlerT], HandlerT]:
    """Register a subscriber handler."""
    return self._registry.subscriber(
        queue=queue,
        exchange=exchange,
        routing_key=routing_key,
        ack_policy=ack_policy,
        middlewares=middlewares,
        serializer=serializer,
        retry=retry,
        tags=tags,
        description=description,
        name=name,
        prefetch_count=prefetch_count,
        filter_fn=filter_fn,
        reject_without_dlx=reject_without_dlx,
        reply_to_allow=reply_to_allow,
        stream=stream,
        stream_offset=stream_offset,
    )

publisher(exchange: RabbitExchange | str | None = None, routing_key: str = '') -> Callable[[HandlerT], HandlerT]

Register a result publisher.

Source code in src/rabbitkit/sync/broker.py
def publisher(
    self,
    exchange: RabbitExchange | str | None = None,
    routing_key: str = "",
) -> Callable[[HandlerT], HandlerT]:
    """Register a result publisher."""
    return self._registry.publisher(exchange=exchange, routing_key=routing_key)

include_router(router: RabbitRouter, prefix: str = '') -> None

Include routes from a RabbitRouter.

Source code in src/rabbitkit/sync/broker.py
def include_router(self, router: RabbitRouter, prefix: str = "") -> None:
    """Include routes from a RabbitRouter."""
    self._registry.include_router(router, prefix=prefix)

start(worker_config: WorkerConfig | None = None) -> None

Start the broker — connect, declare topology, start consuming.

  1. Connect to RabbitMQ
  2. Declare exchanges, queues, bindings per TopologyMode
  3. Declare retry topology (delay queues, DLQ)
  4. Optionally create a worker pool for concurrent processing
  5. Start consuming from all registered queues

L14: last_heartbeat is initialized here (not left None until the first message/tick) so a broker that is wedged from the very start -- before it ever processes a message or a start_consuming() loop iteration -- is still caught by :func:health.broker_liveness's staleness check, instead of bypassing it entirely (a None heartbeat is treated as "no signal available" there, which previously meant "always alive").

Source code in src/rabbitkit/sync/broker.py
def start(self, worker_config: WorkerConfig | None = None) -> None:
    """Start the broker — connect, declare topology, start consuming.

    1. Connect to RabbitMQ
    2. Declare exchanges, queues, bindings per TopologyMode
    3. Declare retry topology (delay queues, DLQ)
    4. Optionally create a worker pool for concurrent processing
    5. Start consuming from all registered queues

    L14: ``last_heartbeat`` is initialized here (not left ``None`` until
    the first message/tick) so a broker that is wedged from the very
    start -- before it ever processes a message or a
    ``start_consuming()`` loop iteration -- is still caught by
    :func:`health.broker_liveness`'s staleness check, instead of
    bypassing it entirely (a ``None`` heartbeat is treated as "no
    signal available" there, which previously meant "always alive").
    """
    if self._started:
        return

    self.last_heartbeat = time.monotonic()

    # Configure structured logging if enabled
    if self._config.logging is not None:
        from rabbitkit.core.logging import configure_structlog

        configure_structlog(self._config.logging, override_existing=self._config.logging.override_existing)

    # Create transport
    self._transport = SyncTransport(
        connection_config=self._config.connection,
        socket_config=self._config.socket,
        security_config=self._config.security,
        topology_mode=self._config.topology_mode,
        confirm_delivery=self._config.publisher.confirm_delivery,
        confirm_timeout=self._config.publisher.confirm_timeout,
        on_topology_conflict=self._config.safety.on_topology_conflict,
        max_in_flight_bytes=self._config.publisher.max_in_flight_bytes,
        admission_timeout=self._config.pool.channel_acquire_timeout,
    )
    # Reconnect-attempts bound: previously hardcoded on the transport
    # and unreachable from config (see ConnectionConfig.reconnect_max_attempts).
    self._transport.max_reconnect_attempts = self._config.connection.reconnect_max_attempts
    # Before connect(), so the first connection and channel count.
    self._wire_reconnect_metric()

    self._transport.connect()
    self._transport.on_io_tick(self._mark_heartbeat)
    self._transport.on_io_tick(self._sample_metrics_throttled)
    if self._deadlines is not None:
        self._transport.on_io_tick(self._deadlines.check)
        self._transport.poll_interval = self._deadlines.poll_interval

    # Wire an opt-in FlowController's blocked/unblocked callbacks to the
    # transport now that it exists (C-6).
    if self._flow_controller is not None:
        self._transport.on_blocked(self._flow_controller.on_blocked)
        self._transport.on_unblocked(self._flow_controller.on_unblocked)

    # M2: the old M-P5 "channel_pool_size caps concurrent confirms"
    # warning was removed. The default SyncTransport publishes on a single
    # dedicated channel (not SyncChannelPool — see sync/pool.py), so
    # channel_pool_size does not gate publish concurrency or confirms;
    # tuning it changed nothing on this path. The real sync
    # confirmed-publish ceiling (RTT-bound, ~0.9k msg/s, H6) is documented
    # on SyncBroker.publish and in the README.

    # Declare topology
    self._declare_topology()
    self._notify_passive_only()

    # Install RetryMiddleware on retry-enabled routes (topology alone does
    # not retry — the middleware routes failures into the delay queues).
    self._wire_retry_middleware()

    # H2: single-worker sync consumers run the handler INLINE on the pika
    # I/O thread, so nothing services heartbeat frames while a handler
    # runs. A handler that runs longer than ~2x the heartbeat interval
    # gets its connection killed broker-side mid-handler → the ack fails,
    # the message is redelivered, and side effects can repeat (possibly in
    # a loop). worker_count>1 is immune (handlers run on pool threads while
    # the I/O thread keeps pumping). Warn so the failure mode is visible.
    single_worker = worker_config is None or worker_config.worker_count <= 1
    # processing_timeout: even a single worker runs off the I/O thread
    # (one dedicated handler thread), so that thread can settle a
    # delivery whose handler outran its deadline.
    handler_thread = single_worker and self._deadlines is not None and bool(self._registry.routes)
    if single_worker and not handler_thread and self._registry.routes and self._config.connection.heartbeat > 0:
        import warnings

        warnings.warn(
            f"Starting a single-worker sync consumer (worker_count=1) with "
            f"heartbeat={self._config.connection.heartbeat}s. Handlers run inline on "
            "the I/O thread, so any handler taking longer than ~"
            f"{self._config.connection.heartbeat * 2}s will starve heartbeats and the "
            "broker will drop the connection mid-handler (→ redelivery + duplicate "
            "side effects). For slow handlers, pass "
            "start(worker_config=WorkerConfig(worker_count=N)) so handlers run off the "
            "I/O thread, or raise ConnectionConfig.heartbeat well above your worst-case "
            "handler duration. Additionally (M5): a handler on THIS thread that "
            "publishes with confirms waits for the broker confirm UNBOUNDED — "
            "confirm_timeout cannot be enforced from the owner thread itself; "
            "worker_count>1 publishes marshal through the bounded cross-thread "
            "path instead.",
            RuntimeWarning,
            stacklevel=2,
        )

    # Create worker pool if requested
    if worker_config is not None and worker_config.worker_count > 1:
        # M2: the old channel_pool_size deadlock warning was removed — the
        # default SyncTransport publishes on a single dedicated publisher
        # channel, NOT through SyncChannelPool (see sync/pool.py), so
        # worker_count vs channel_pool_size cannot cause the described
        # publish deadlock. Tuning channel_pool_size changed nothing on
        # this path; the warning only misled operators.
        # Override prefetch_count if prefetch_per_worker is set
        if worker_config.prefetch_per_worker is not None:
            self._consumer_config = replace(
                self._config.consumer,
                prefetch_count=worker_config.worker_count * worker_config.prefetch_per_worker,
            )
        self._worker_pool = SyncWorkerPool(config=worker_config)
        self._worker_pool.start()
    elif handler_thread:
        self._worker_pool = SyncWorkerPool(config=worker_config, threaded=True)
        self._worker_pool.start()

    # Start consuming
    for route in self._registry.routes:
        self._start_consumer(route)

    self._started = True
    self._set_lifecycle_gauges(connected=True)
    logger.info(
        "SyncBroker started with %d routes",
        len(self._registry.routes),
    )

stop(timeout: float | None = None) -> None

Stop the broker - cancel consumers, drain pool, drain in-flight, disconnect.

timeout defaults to ConsumerConfig.graceful_timeout (C-2). The whole stop sequence is bounded by an overall deadline.

C5: consumers are cancelled FIRST, before the worker pool is drained. Draining the pool before cancelling left the consumer active for the entire (potentially graceful_timeout-long) drain wait — a message delivered in that window was submitted to a pool already mid-shutdown: SyncWorkerPool.submit() either raises RuntimeError (uncaught, propagating into pika's callback machinery) or, once .stop() has fully returned, silently runs the handler inline on the pika I/O thread — either way the message is never cleanly settled before disconnect(), so it is redelivered (duplicate-processing risk) on the next connection. Cancelling first stops new deliveries outright, so the pool only ever drains work that was already in flight.

Source code in src/rabbitkit/sync/broker.py
def stop(self, timeout: float | None = None) -> None:
    """Stop the broker - cancel consumers, drain pool, drain in-flight, disconnect.

    ``timeout`` defaults to ``ConsumerConfig.graceful_timeout`` (C-2). The
    whole stop sequence is bounded by an overall deadline.

    C5: consumers are cancelled FIRST, before the worker pool is drained.
    Draining the pool before cancelling left the consumer active for the
    entire (potentially graceful_timeout-long) drain wait — a message
    delivered in that window was submitted to a pool already mid-shutdown:
    ``SyncWorkerPool.submit()`` either raises ``RuntimeError`` (uncaught,
    propagating into pika's callback machinery) or, once ``.stop()`` has
    fully returned, silently runs the handler *inline* on the pika I/O
    thread — either way the message is never cleanly settled before
    ``disconnect()``, so it is redelivered (duplicate-processing risk) on
    the next connection. Cancelling first stops new deliveries outright,
    so the pool only ever drains work that was already in flight.
    """
    if not self._started:
        return

    effective = timeout if timeout is not None else self._consumer_config.graceful_timeout
    deadline = None if effective is None else time.monotonic() + effective

    # Stream routes: from here a nack/reject hands a delivery back, so
    # its offset must not advance.
    for tracker in self._stream_trackers.values():
        tracker.begin_shutdown()

    # Cancel all consumers FIRST — stop new deliveries before draining
    # anything, so nothing new arrives while the pool/in-flight drain runs.
    if self._transport is None:  # pragma: no cover — defensive (assert was stripped under -O)
        return
    for route in self._registry.routes:
        if route.consumer_tag:
            self._transport.cancel_consumer(route.consumer_tag)

    # Drain the worker pool (let in-flight pooled tasks finish), bounded by
    # the outer deadline. H2: pass the transport's pump so a worker
    # thread's marshaled ack/nack/reject is actually drained during the
    # wait, instead of the transport falling back to an unsafe inline
    # cross-thread call once the consume loop has stopped.
    if self._worker_pool is not None:
        remaining = None if deadline is None else max(0.0, deadline - time.monotonic())
        self._worker_pool.stop(timeout=remaining, pump=self._pump)
        self._worker_pool = None

    # Drain inline in-flight handlers (C-2).
    self._wait_in_flight(deadline)

    # Commit the stream offsets, so the next start resumes right after
    # the last processed message.
    for tracker in self._stream_trackers.values():
        tracker.flush()

    # Close RPC client if used
    if self._rpc_client is not None:
        self._rpc_client.close()
        self._rpc_client = None

    # Disconnect
    if self._transport:
        self._transport.disconnect()

    self._started = False
    self._set_lifecycle_gauges(connected=False)
    logger.info("SyncBroker stopped")

run(worker_config: WorkerConfig | None = None) -> None

Start and run the blocking consume loop.

Blocks until SIGINT/SIGTERM or stop() is called. Installs a SIGTERM handler (C-1) so k8s pod termination drains instead of hard-killing. Recovers from connection drops by reconnecting, re-declaring topology, and re-subscribing all consumers - pika's BlockingConnection has no built-in recovery, so without this a single blip kills the consumer.

worker_config is forwarded to :meth:start, so a multi-worker consumer (worker_count > 1) also gets the recovery loop.

Source code in src/rabbitkit/sync/broker.py
def run(self, worker_config: WorkerConfig | None = None) -> None:
    """Start and run the blocking consume loop.

    Blocks until SIGINT/SIGTERM or stop() is called. Installs a SIGTERM
    handler (C-1) so k8s pod termination drains instead of hard-killing.
    Recovers from connection drops by reconnecting, re-declaring topology,
    and re-subscribing all consumers - pika's BlockingConnection has no
    built-in recovery, so without this a single blip kills the consumer.

    ``worker_config`` is forwarded to :meth:`start`, so a multi-worker
    consumer (``worker_count > 1``) also gets the recovery loop.
    """
    self.start(worker_config=worker_config)
    self._install_sigterm_handler()
    connection_errors = get_connection_errors()
    try:
        while True:
            try:
                if self._transport is None:
                    break
                self._transport.start_consuming()
                break  # clean stop_consuming() -> exit
            except KeyboardInterrupt:
                break
            except connection_errors as exc:
                logger.warning("consumer connection lost; recovering", error=str(exc))
                self._recover_consumers(exc)
    finally:
        self._restore_signal_handlers()
        self.stop()

pump_idle(time_limit: float = 0.05) -> None

Service the connection's I/O loop without consuming (idle keep-alive).

run()/start_consuming() pumps process_data_events() continuously while consumers are registered, which incidentally keeps the (single, shared) connection's heartbeats serviced too — see sync/transport.py's module docstring on the one-connection model. A publish-only broker (no registered routes, or one that never calls run()) has nothing driving that pump: the connection is only touched when publish() actually runs, so a long idle gap can get it heartbeat-timed-out broker-side, and a dead connection is only discovered (and reconnected) on the next publish attempt.

Call this periodically — from the SAME thread that called start(), same invariant as every other transport call — from your own idle loop (e.g. between polling for work) to reconnect proactively if the connection died, service pending heartbeat frames, and refresh the liveness heartbeat (see health.broker_liveness) even though no message was delivered. A no-op if the broker is not started.

Source code in src/rabbitkit/sync/broker.py
def pump_idle(self, time_limit: float = 0.05) -> None:
    """Service the connection's I/O loop without consuming (idle keep-alive).

    ``run()``/``start_consuming()`` pumps ``process_data_events()``
    continuously while consumers are registered, which incidentally
    keeps the (single, shared) connection's heartbeats serviced too —
    see ``sync/transport.py``'s module docstring on the one-connection
    model. A **publish-only** broker (no registered routes, or one that
    never calls ``run()``) has nothing driving that pump: the connection
    is only touched when ``publish()`` actually runs, so a long idle gap
    can get it heartbeat-timed-out broker-side, and a dead connection is
    only discovered (and reconnected) on the *next* publish attempt.

    Call this periodically — from the SAME thread that called
    ``start()``, same invariant as every other transport call — from
    your own idle loop (e.g. between polling for work) to reconnect
    proactively if the connection died, service pending heartbeat
    frames, and refresh the liveness heartbeat (see
    ``health.broker_liveness``) even though no message was delivered.
    A no-op if the broker is not started.
    """
    if self._transport is None:
        return
    self._transport.ensure_connected()
    self._transport.pump(time_limit)
    self._mark_heartbeat()
    self._sample_metrics_throttled()

publish(envelope: MessageEnvelope | None = None, *, exchange: str = '', routing_key: str = '', body: bytes | str | dict[str, Any] | None = None, headers: dict[str, Any] | None = None, content_type: str = 'application/json', correlation_id: str | None = None, reply_to: str | None = None, message_id: str | None = None) -> PublishOutcome

Publish a message.

Accepts either a pre-built MessageEnvelope or individual kwargs::

# Envelope form (full control):
broker.publish(MessageEnvelope(routing_key="orders.created", body=b"..."))

# Kwargs form (convenient):
broker.publish(
    exchange="orders",
    routing_key="orders.created",
    body={"order_id": 123},
    headers={"x-tenant": "acme"},
)

When body is a dict or str it is JSON-encoded automatically.

When an opt-in FlowController is configured (broker.flow_controller = fc), a publish slot is acquired before and released after the transport publish so backpressure/rate-limiting applies to the hot path. Without a controller this is a plain pass-through.

When middlewares=[...] was passed to the constructor, each middleware's publish_scope wraps this call (e.g. SigningMiddleware signs the envelope) — see publish_middlewares. Middleware wraps OUTSIDE the flow-control gate, so a middleware-transformed envelope is what gets rate-limited/blocked, and what the transport actually sends.

Throughput note (H6): with publisher confirms on (the default), this waits for a broker confirm per message on a single channel, so it is RTT-bound at ~0.9k msg/s and does NOT scale with worker_count — pika's BlockingConnection serializes confirms, it cannot pipeline them. To drain a large backlog fast, use AsyncBroker + AsyncBatchPublisher (pipelined confirms, ~6.1k msg/s) or more processes.

message_id (kwargs form only) sets the AMQP message id instead of a fresh uuid4, so the same logical message can be republished after an unknown outcome and deduplicated downstream.

Source code in src/rabbitkit/sync/broker.py
def publish(
    self,
    envelope: MessageEnvelope | None = None,
    *,
    exchange: str = "",
    routing_key: str = "",
    body: bytes | str | dict[str, Any] | None = None,
    headers: dict[str, Any] | None = None,
    content_type: str = "application/json",
    correlation_id: str | None = None,
    reply_to: str | None = None,
    message_id: str | None = None,
) -> PublishOutcome:
    """Publish a message.

    Accepts either a pre-built ``MessageEnvelope`` or individual kwargs::

        # Envelope form (full control):
        broker.publish(MessageEnvelope(routing_key="orders.created", body=b"..."))

        # Kwargs form (convenient):
        broker.publish(
            exchange="orders",
            routing_key="orders.created",
            body={"order_id": 123},
            headers={"x-tenant": "acme"},
        )

    When ``body`` is a dict or str it is JSON-encoded automatically.

    When an opt-in ``FlowController`` is configured (``broker.flow_controller
    = fc``), a publish slot is acquired before and released after the
    transport publish so backpressure/rate-limiting applies to the hot path.
    Without a controller this is a plain pass-through.

    When ``middlewares=[...]`` was passed to the constructor, each
    middleware's ``publish_scope`` wraps this call (e.g. ``SigningMiddleware``
    signs the envelope) — see ``publish_middlewares``. Middleware wraps
    OUTSIDE the flow-control gate, so a middleware-transformed envelope is
    what gets rate-limited/blocked, and what the transport actually sends.

    Throughput note (H6): with publisher confirms on (the default), this
    waits for a broker confirm per message on a single channel, so it is
    RTT-bound at ~0.9k msg/s and does NOT scale with worker_count — pika's
    BlockingConnection serializes confirms, it cannot pipeline them. To
    drain a large backlog fast, use AsyncBroker + AsyncBatchPublisher
    (pipelined confirms, ~6.1k msg/s) or more processes.

    ``message_id`` (kwargs form only) sets the AMQP message id instead of
    a fresh uuid4, so the same logical message can be republished after
    an unknown outcome and deduplicated downstream.
    """
    if envelope is not None and message_id is not None:
        raise ValueError("message_id applies to the kwargs form; set MessageEnvelope.message_id instead")
    if envelope is None:
        import json as _json

        if body is None:
            raw_body = b""
        elif isinstance(body, bytes):
            raw_body = body
        elif isinstance(body, str):
            raw_body = body.encode()
        else:
            raw_body = _json.dumps(body).encode()
        # M2: honor PublisherConfig defaults for the kwargs form (they were
        # previously dead config). Envelope-form callers keep full control.
        envelope = MessageEnvelope(
            routing_key=routing_key,
            body=raw_body,
            exchange=exchange,
            headers=headers or {},
            content_type=content_type,
            correlation_id=correlation_id,
            reply_to=reply_to,
            mandatory=self._config.publisher.mandatory,
            delivery_mode=2 if self._config.publisher.persistent else 1,
        )
        if message_id is not None:
            envelope = replace(envelope, message_id=message_id)

    # an application publish cannot carry rabbitkit's retry/DLQ
    # bookkeeping headers (opt-in; the library's own republishes bypass this).
    if self._reserved_header_stripper is not None:
        envelope = self._reserved_header_stripper(envelope)

    # M10: reject oversized bodies at publish time (input validation at
    # the trust boundary — a too-large message is a programming/policy
    # error, caught before it hits the wire).
    max_bytes = self._config.publisher.max_message_bytes
    if max_bytes and len(envelope.body) > max_bytes:
        raise MessageTooLargeError(
            f"Message body ({len(envelope.body)} bytes) exceeds "
            f"PublisherConfig.max_message_bytes ({max_bytes}). Large messages are a "
            "RabbitMQ anti-pattern — store the payload externally and publish a "
            "reference, or raise the limit if this is intentional."
        )

    if self._transport is None:
        raise BrokerNotStartedError("Broker not started. Call start() first.")
    transport = self._transport  # narrowed local capture for the closure below

    def do_transport_publish(env: MessageEnvelope) -> PublishOutcome:
        fc = self._flow_controller
        if fc is not None:
            if not fc.acquire():
                # Dropped by backpressure policy (drop/timeout). Do not publish.
                return PublishOutcome(
                    status=PublishStatus.NOT_SENT,
                    exchange=env.exchange,
                    routing_key=env.routing_key,
                    error=BackpressureError("publish dropped by backpressure policy"),
                    reason=PublishReason.BACKPRESSURE_DROPPED,
                )
            try:
                return transport.publish(env)
            finally:
                fc.release()
        return transport.publish(env)

    if self._publish_middlewares:
        chain = self._pipeline.compose_broker_publish_sync(self._publish_middlewares)
        outcome: PublishOutcome = chain(envelope, do_transport_publish)
        return outcome
    return do_transport_publish(envelope)

preflight(profile: ReliabilityProfile | str = ReliabilityProfile.STANDARD, *, management_client: Any | None = None, vhost: str = '/') -> PreflightReport

Verify reliability-profile prerequisites for this broker's config and registered routes (plan §9). Broker-side policy checks need a read-only management client; without one they are reported UNVERIFIED — never silently green. Pure inspection; no I/O on the AMQP connection and no policy mutation.

Source code in src/rabbitkit/sync/broker.py
def preflight(
    self,
    profile: ReliabilityProfile | str = ReliabilityProfile.STANDARD,
    *,
    management_client: Any | None = None,
    vhost: str = "/",
) -> PreflightReport:
    """Verify reliability-profile prerequisites for this broker's config
    and registered routes (plan §9). Broker-side policy checks need a
    read-only management client; without one they are reported
    ``UNVERIFIED`` — never silently green. Pure inspection; no I/O on
    the AMQP connection and no policy mutation."""
    return run_preflight(
        self._config,
        profile,
        routes=self._registry.routes,
        management_client=management_client,
        vhost=vhost,
    )

iter_publish(envelopes: Iterable[MessageEnvelope], options: BulkPublishOptions | None = None) -> Iterator[BulkPublishItem]

Publish a (possibly unbounded) iterable, yielding one :class:~rabbitkit.core.bulk.BulkPublishItem per input as it settles.

Every item goes through the SAME path as :meth:publish — publish middlewares, flow control, size limit, transport — so single and bulk publishing share every safeguard. The sync transport confirms one publish at a time (pika's BlockingConnection cannot pipeline confirms), so this is sequential; options.max_in_flight has no effect here. options.overall_timeout does: past the deadline remaining inputs are yielded NOT_SENT without touching the wire.

Memory is bounded by the caller: results are yielded, not collected.

Source code in src/rabbitkit/sync/broker.py
def iter_publish(
    self,
    envelopes: Iterable[MessageEnvelope],
    options: BulkPublishOptions | None = None,
) -> Iterator[BulkPublishItem]:
    """Publish a (possibly unbounded) iterable, yielding one
    :class:`~rabbitkit.core.bulk.BulkPublishItem` per input as it settles.

    Every item goes through the SAME path as :meth:`publish` — publish
    middlewares, flow control, size limit, transport — so single and
    bulk publishing share every safeguard. The sync transport confirms
    one publish at a time (pika's BlockingConnection cannot pipeline
    confirms), so this is sequential; ``options.max_in_flight`` has no
    effect here. ``options.overall_timeout`` does: past the deadline
    remaining inputs are yielded ``NOT_SENT`` without touching the wire.

    Memory is bounded by the caller: results are yielded, not collected.
    """
    if self._transport is None:
        raise BrokerNotStartedError("Broker not started. Call start() first.")
    opts = options or BulkPublishOptions()
    preparer = PublishPreparer(
        max_message_bytes=self._config.publisher.max_message_bytes,
        max_buffer_bytes=opts.max_buffer_bytes,
    )
    return iter_publish_sync(
        envelopes,
        self.publish,
        options=opts,
        preparer=preparer,
        on_item=self._record_bulk_item,
    )

publish_many(envelopes: Sequence[MessageEnvelope], options: BulkPublishOptions | None = None) -> BulkPublishResult

Publish a bounded collection and return input-ordered per-item outcomes.

Never raises for a failed item — inspect result.items (or call result.raise_for_status()). Raises ValueError before publishing anything if len(envelopes) exceeds options.max_items; use :meth:iter_publish for streams. See :class:~rabbitkit.core.types.BulkPublishStatus for what each state means and what to do about it — in particular UNKNOWN items may have reached the broker and must be reconciled, not blindly replayed.

Source code in src/rabbitkit/sync/broker.py
def publish_many(
    self,
    envelopes: Sequence[MessageEnvelope],
    options: BulkPublishOptions | None = None,
) -> BulkPublishResult:
    """Publish a bounded collection and return input-ordered per-item outcomes.

    Never raises for a failed item — inspect ``result.items`` (or call
    ``result.raise_for_status()``). Raises ``ValueError`` before publishing
    anything if ``len(envelopes)`` exceeds ``options.max_items``; use
    :meth:`iter_publish` for streams. See
    :class:`~rabbitkit.core.types.BulkPublishStatus` for what each state
    means and what to do about it — in particular ``UNKNOWN`` items may
    have reached the broker and must be reconciled, not blindly replayed.
    """
    opts = options or BulkPublishOptions()
    if len(envelopes) > opts.max_items:
        raise ValueError(
            f"publish_many received {len(envelopes)} envelopes, more than BulkPublishOptions.max_items "
            f"({opts.max_items}); use iter_publish() for large or unbounded inputs."
        )
    started = datetime.now(UTC)
    items = list(self.iter_publish(envelopes, opts))
    self._record_bulk_batch(len(envelopes))
    return BulkPublishResult(
        items=tuple(sorted(items, key=lambda it: it.index)),
        started_at=started,
        finished_at=datetime.now(UTC),
    )

ack_many(messages: Iterable[RabbitMessage], *, fail_fast: bool = True) -> SettlementReport

Ack exactly the given deliveries — each with its own multiple=False frame. Never a cumulative ack: an unselected, still-running sibling on the same channel is untouched.

Validation runs before any I/O: duplicates, already-settled messages, no-ack deliveries and STALE handles (channel rebuilt since delivery) are reported per item. With fail_fast=True (default) any problem aborts the whole call with every valid item NOT_ATTEMPTED.

The report says DISPATCHED, not "confirmed" — RabbitMQ sends no acknowledgement for a consumer ack. Messages must come from THIS broker (MANUAL ack policy, or a handler that deferred settlement).

Source code in src/rabbitkit/sync/broker.py
def ack_many(self, messages: Iterable[RabbitMessage], *, fail_fast: bool = True) -> SettlementReport:
    """Ack exactly the given deliveries — each with its own ``multiple=False``
    frame. Never a cumulative ack: an unselected, still-running sibling on
    the same channel is untouched.

    Validation runs before any I/O: duplicates, already-settled messages,
    no-ack deliveries and STALE handles (channel rebuilt since delivery)
    are reported per item. With ``fail_fast=True`` (default) any problem
    aborts the whole call with every valid item ``NOT_ATTEMPTED``.

    The report says ``DISPATCHED``, not "confirmed" — RabbitMQ sends no
    acknowledgement for a consumer ack. Messages must come from THIS
    broker (MANUAL ack policy, or a handler that deferred settlement).
    """
    return settle_many_sync(
        messages,
        SettlementAction.ACK,
        fail_fast=fail_fast,
        on_item=self._settlement_item_hook(SettlementAction.ACK),
    )

nack_many(messages: Iterable[RabbitMessage], *, requeue: bool = True, fail_fast: bool = True) -> SettlementReport

Nack exactly the given deliveries (individually — see :meth:ack_many).

requeue=False dead-letters (or, without a DLX, DISCARDS) each message; for ordinary handler failures prefer the retry/terminal path (RetryConfig) over raw nacks.

Source code in src/rabbitkit/sync/broker.py
def nack_many(
    self,
    messages: Iterable[RabbitMessage],
    *,
    requeue: bool = True,
    fail_fast: bool = True,
) -> SettlementReport:
    """Nack exactly the given deliveries (individually — see :meth:`ack_many`).

    ``requeue=False`` dead-letters (or, without a DLX, DISCARDS) each
    message; for ordinary handler failures prefer the retry/terminal
    path (``RetryConfig``) over raw nacks.
    """
    return settle_many_sync(
        messages,
        SettlementAction.NACK,
        requeue=requeue,
        fail_fast=fail_fast,
        on_item=self._settlement_item_hook(SettlementAction.NACK),
    )

request(routing_key: str, body: bytes, *, timeout: float = 5.0, exchange: str = '', headers: dict[str, Any] | None = None) -> RabbitMessage

Send an RPC request and wait for a response (sync).

Lazily initializes an RPCClient on first call. The client is shared across calls and closed in stop().

Source code in src/rabbitkit/sync/broker.py
def request(
    self,
    routing_key: str,
    body: bytes,
    *,
    timeout: float = 5.0,
    exchange: str = "",
    headers: dict[str, Any] | None = None,
) -> RabbitMessage:
    """Send an RPC request and wait for a response (sync).

    Lazily initializes an RPCClient on first call.
    The client is shared across calls and closed in stop().
    """
    if self._transport is None:
        raise BrokerNotStartedError("Broker not started. Call start() first.")
    if self._rpc_client is None:
        from rabbitkit.rpc import RPCClient

        self._rpc_client = RPCClient(self._transport)
    return self._rpc_client.call(routing_key, body, timeout=timeout, exchange=exchange, headers=headers)

declare_exchange(exchange: RabbitExchange) -> None

Declare exchange (AUTO_DECLARE only, or a passive=True existence check under PASSIVE_ONLY). See AsyncBroker.declare_exchange.

Source code in src/rabbitkit/sync/broker.py
def declare_exchange(self, exchange: RabbitExchange) -> None:
    """Declare *exchange* (``AUTO_DECLARE`` only, or a ``passive=True``
    existence check under ``PASSIVE_ONLY``). See ``AsyncBroker.declare_exchange``."""
    from rabbitkit.core.topology_dispatch import check_public_topology_write

    check_public_topology_write(self._config.topology_mode, "declare_exchange", passive=exchange.passive)
    self._started_transport().declare_exchange(exchange)

declare_queue(queue: RabbitQueue) -> None

Declare queue exactly as given. Same rules as :meth:declare_exchange.

Source code in src/rabbitkit/sync/broker.py
def declare_queue(self, queue: RabbitQueue) -> None:
    """Declare *queue* exactly as given. Same rules as :meth:`declare_exchange`."""
    from rabbitkit.core.topology_dispatch import check_public_topology_write

    check_public_topology_write(self._config.topology_mode, "declare_queue", passive=queue.passive)
    self._started_transport().declare_queue(queue)

bind_queue(queue: str, exchange: str, routing_key: str = '', arguments: dict[str, Any] | None = None) -> None

Bind queue to exchange. AUTO_DECLARE only.

Source code in src/rabbitkit/sync/broker.py
def bind_queue(
    self, queue: str, exchange: str, routing_key: str = "", arguments: dict[str, Any] | None = None
) -> None:
    """Bind *queue* to *exchange*. ``AUTO_DECLARE`` only."""
    from rabbitkit.core.topology_dispatch import check_public_topology_write

    check_public_topology_write(self._config.topology_mode, "bind_queue")
    self._started_transport().bind_queue(
        queue=queue, exchange=exchange, routing_key=routing_key, arguments=arguments
    )

bind_exchange(destination: str, source: str, routing_key: str = '', arguments: dict[str, Any] | None = None) -> None

Bind exchange destination to source. AUTO_DECLARE only.

Source code in src/rabbitkit/sync/broker.py
def bind_exchange(
    self, destination: str, source: str, routing_key: str = "", arguments: dict[str, Any] | None = None
) -> None:
    """Bind exchange *destination* to *source*. ``AUTO_DECLARE`` only."""
    from rabbitkit.core.topology_dispatch import check_public_topology_write

    check_public_topology_write(self._config.topology_mode, "bind_exchange")
    self._started_transport().bind_exchange(
        destination=destination, source=source, routing_key=routing_key, arguments=arguments
    )

verify_topology(management_client: Any | None = None, *, vhost: str | None = None) -> Any

Read-only topology compatibility check — see AsyncBroker.verify_topology.

Source code in src/rabbitkit/sync/broker.py
def verify_topology(self, management_client: Any | None = None, *, vhost: str | None = None) -> Any:
    """Read-only topology compatibility check — see ``AsyncBroker.verify_topology``."""
    from rabbitkit.core.topology_validation import verify_topology

    return verify_topology(
        list(self._registry.routes),
        management_client=management_client,
        vhost=vhost if vhost is not None else self._config.connection.vhost,
        broker_retry=self._config.retry,
    )

RabbitApp (lifecycle)

RabbitApp

Application lifecycle manager.

Manages startup/shutdown hooks and signal handling. Idempotent: start() twice is safe (no-op if already running). Startup failure rollback: if any startup hook fails → on_shutdown still called.

startup_timeout bounds each startup/after-startup hook so a hung hook fails fast instead of hanging until SIGKILL. The default (120.0) is finite; pass None explicitly to disable the bound.

Source code in src/rabbitkit/core/app.py
class RabbitApp:
    """Application lifecycle manager.

    Manages startup/shutdown hooks and signal handling.
    Idempotent: start() twice is safe (no-op if already running).
    Startup failure rollback: if any startup hook fails → on_shutdown still called.

    ``startup_timeout`` bounds each startup/after-startup hook so a hung hook
    fails fast instead of hanging until SIGKILL. The default (``120.0``) is
    finite; pass ``None`` explicitly to disable the bound.
    """

    def __init__(self, title: str = "rabbitkit", *, startup_timeout: float | None = 120.0) -> None:
        self._title = title
        self._state = AppState.IDLE
        self._startup_timeout = startup_timeout

        # Lifecycle hooks
        self._on_startup: list[Callable[[], Any]] = []
        self._after_startup: list[Callable[[], Any]] = []
        self._on_shutdown: list[Callable[[], Any]] = []
        self._after_shutdown: list[Callable[[], Any]] = []

        # Concurrency guards: prevent double-start / concurrent stop races.
        # The async lock is created eagerly — modern asyncio binds it to the
        # running loop on first use, so creating it without a loop is safe and
        # avoids a lazy-create race in concurrent start_async/stop_async calls.
        self._sync_lock = threading.Lock()
        self._async_lock = asyncio.Lock()

        # Signal handling
        self._shutdown_event: asyncio.Event | None = None
        self._original_handlers: dict[signal.Signals, Any] = {}
        self._loop: asyncio.AbstractEventLoop | None = None

    @property
    def state(self) -> AppState:
        return self._state

    @property
    def title(self) -> str:
        return self._title

    # ── Hook registration ────────────────────────────────────────────────

    def on_startup(self, func: Callable[[], Any]) -> Callable[[], Any]:
        """Register a startup hook (decorator or direct call)."""
        self._on_startup.append(func)
        return func

    def after_startup(self, func: Callable[[], Any]) -> Callable[[], Any]:
        """Register a post-startup hook."""
        self._after_startup.append(func)
        return func

    def on_shutdown(self, func: Callable[[], Any]) -> Callable[[], Any]:
        """Register a shutdown hook."""
        self._on_shutdown.append(func)
        return func

    def after_shutdown(self, func: Callable[[], Any]) -> Callable[[], Any]:
        """Register a post-shutdown hook."""
        self._after_shutdown.append(func)
        return func

    # ── Sync lifecycle ───────────────────────────────────────────────────

    def start(self) -> None:
        """Start the application (sync).

        Idempotent and concurrency-safe — no-op if already running.
        On startup hook failure → on_shutdown is still called.
        """
        with self._sync_lock:
            if self._state in (AppState.RUNNING, AppState.STARTING, AppState.STOPPING):
                logger.debug("App already %s, ignoring start()", self._state.value)
                return

            self._state = AppState.STARTING
            logger.info("Starting %s", self._title)

            try:
                self._run_hooks_sync(self._on_startup, timeout=self._startup_timeout)
                self._state = AppState.RUNNING
                self._run_hooks_sync(self._after_startup, timeout=self._startup_timeout)
                logger.info("%s started", self._title)
            except Exception:
                logger.exception("Startup failed, running shutdown hooks")
                self._state = AppState.STOPPING
                self._run_hooks_sync(self._on_shutdown)
                self._state = AppState.STOPPED
                raise

    def stop(self) -> None:
        """Stop the application (sync).

        Idempotent and concurrency-safe — no-op if already stopped.
        """
        with self._sync_lock:
            if self._state in (AppState.STOPPED, AppState.STOPPING, AppState.IDLE):
                return

            self._state = AppState.STOPPING
            logger.info("Stopping %s", self._title)

            try:
                self._run_hooks_sync(self._on_shutdown)
            finally:
                self._run_hooks_sync(self._after_shutdown)
                self._state = AppState.STOPPED
                logger.info("%s stopped", self._title)

    # ── Async lifecycle ──────────────────────────────────────────────────

    async def start_async(self) -> None:
        """Start the application (async).

        Idempotent and concurrency-safe — no-op if already running.
        On startup hook failure → on_shutdown is still called.
        """
        async with self._async_lock:
            if self._state in (AppState.RUNNING, AppState.STARTING, AppState.STOPPING):
                logger.debug("App already %s, ignoring start_async()", self._state.value)
                return

            self._state = AppState.STARTING
            logger.info("Starting %s", self._title)

            try:
                await self._run_hooks_async(self._on_startup, timeout=self._startup_timeout)
                self._state = AppState.RUNNING
                await self._run_hooks_async(self._after_startup, timeout=self._startup_timeout)
                logger.info("%s started", self._title)
            except Exception:
                logger.exception("Startup failed, running shutdown hooks")
                self._state = AppState.STOPPING
                await self._run_hooks_async(self._on_shutdown)
                self._state = AppState.STOPPED
                raise

    async def stop_async(self) -> None:
        """Stop the application (async).

        Idempotent and concurrency-safe — no-op if already stopped.
        """
        async with self._async_lock:
            if self._state in (AppState.STOPPED, AppState.STOPPING, AppState.IDLE):
                return

            self._state = AppState.STOPPING
            logger.info("Stopping %s", self._title)

            try:
                await self._run_hooks_async(self._on_shutdown)
            finally:
                await self._run_hooks_async(self._after_shutdown)
                self._state = AppState.STOPPED
                logger.info("%s stopped", self._title)

    async def run_async(self) -> None:
        """Start, wait for shutdown signal, then stop (async).

        Installs SIGINT/SIGTERM handlers for graceful shutdown. Falls back to
        ``signal.signal`` on platforms/threads where ``loop.add_signal_handler``
        is unavailable (e.g. Windows, non-main-thread).

        the handlers in place before are kept. The Python-level handler
        (``signal.getsignal``) is captured and put back on exit:
        ``loop.remove_signal_handler`` alone resets the signal to its
        default, which dropped e.g. an application's SIGTERM handler or
        ``asyncio.run()``'s SIGINT handler. A signal that already has an
        ``loop.add_signal_handler`` handler (asyncio cannot hand it back) is
        left alone with a WARNING; that handler should call
        :meth:`request_shutdown`. A handler installed by someone else while
        the app runs is not removed.
        """
        self._shutdown_event = asyncio.Event()

        loop = asyncio.get_running_loop()
        self._loop = loop
        installed: dict[signal.Signals, Any] = {}
        try:
            for sig in (signal.SIGINT, signal.SIGTERM):
                prev = signal.getsignal(sig)
                if is_loop_signal_handler(prev):
                    logger.warning(
                        "RabbitApp: an asyncio handler for %s is already installed; not replacing it, "
                        "because asyncio cannot hand it back afterwards. That handler should call "
                        "app.request_shutdown().",
                        sig.name,
                    )
                    continue
                loop.add_signal_handler(sig, self._signal_handler)
                installed[sig] = prev
        except (NotImplementedError, RuntimeError, ValueError):  # pragma: no cover
            # Not supported on this platform/thread — fall back to signal.signal.
            # The handler runs in a signal context; schedule the set via the loop.
            for sig in (signal.SIGINT, signal.SIGTERM):
                try:
                    self._original_handlers[sig] = signal.signal(sig, self._signal_handler_sync)
                except (ValueError, OSError):  # pragma: no cover
                    pass  # not in main thread — best effort

        try:
            await self.start_async()
            await self._shutdown_event.wait()
        finally:
            await self.stop_async()
            self._restore_signal_handlers(loop, installed)

    def _restore_signal_handlers(self, loop: asyncio.AbstractEventLoop, installed: dict[signal.Signals, Any]) -> None:
        """Remove the handlers ``run_async`` installed and put back what was there before."""
        for sig, prev in installed.items():
            if not loop_signal_handler_is(loop, sig, self._signal_handler):
                logger.info("RabbitApp: %s handler was replaced while running; leaving it in place", sig.name)
                continue
            try:
                loop.remove_signal_handler(sig)
            except (NotImplementedError, RuntimeError, ValueError):  # pragma: no cover
                continue
            if prev is None:
                continue  # installed outside Python: nothing to put back
            try:
                signal.signal(sig, prev)
            except (ValueError, OSError, TypeError):
                logger.warning("RabbitApp: could not restore the previous %s handler", sig.name, exc_info=True)
        for sig, prev in self._original_handlers.items():  # pragma: no cover
            try:
                signal.signal(sig, prev)
            except (ValueError, OSError):  # pragma: no cover
                pass
        self._original_handlers.clear()

    def _signal_handler_sync(self, signum: int, frame: Any) -> None:  # pragma: no cover
        """signal.signal fallback handler — schedule shutdown on the loop."""
        logger.info("Received shutdown signal %d", signum)
        if self._shutdown_event is not None and self._loop is not None:
            self._loop.call_soon_threadsafe(self._shutdown_event.set)

    def request_shutdown(self) -> None:
        """Request graceful shutdown (can be called from any context)."""
        if self._shutdown_event is not None:
            self._shutdown_event.set()

    # ── Internal ─────────────────────────────────────────────────────────

    def _signal_handler(self) -> None:
        """Handle SIGINT/SIGTERM."""
        logger.info("Received shutdown signal")
        self.request_shutdown()

    def _run_hooks_sync(self, hooks: list[Callable[[], Any]], *, timeout: float | None = None) -> None:
        """Run hooks synchronously. If ``timeout`` is set, bound each hook.

        When a timeout is set, each hook runs in a dedicated worker thread so
        the caller is not blocked by a hung hook. NOTE: the worker thread is
        non-daemon, so a truly-uninterruptible hook still lingers until process
        exit; the timeout bounds the *caller* (it receives ``TimeoutError``)
        rather than hanging forever. ``cancel_futures=True`` drops any
        not-yet-started work.

        The executor is NOT used as a context manager — its ``__exit__`` calls
        ``shutdown(wait=True)`` which would block forever on a hung hook.
        """
        import concurrent.futures

        for hook in hooks:
            if timeout is None:
                result = hook()
                if asyncio.iscoroutine(result):
                    result.close()
                    raise TypeError(
                        f"Async hook {hook.__qualname__} called in sync context. "
                        "Use start_async() or make the hook synchronous."
                    )
            else:
                # A FRESH executor per hook is deliberate, not waste: Python
                # cannot kill a thread, so a hook that hangs past its timeout
                # occupies its worker forever. With a shared pool that stuck
                # worker would make every SUBSEQUENT hook (including shutdown
                # hooks during a SIGTERM drain) time out spuriously without
                # ever running. Isolation costs one thread spawn (~50µs), paid
                # only at startup/shutdown.
                ex = concurrent.futures.ThreadPoolExecutor(max_workers=1)
                try:
                    fut = ex.submit(hook)
                    try:
                        result = fut.result(timeout=timeout)
                    except concurrent.futures.TimeoutError as e:
                        raise TimeoutError(f"Startup hook {hook.__qualname__} exceeded timeout {timeout}s") from e
                    if asyncio.iscoroutine(result):
                        raise TypeError(
                            f"Async hook {hook.__qualname__} called in sync context. "
                            "Use start_async() or make the hook synchronous."
                        )
                finally:
                    # wait=False so a hung worker thread does not block the caller;
                    # cancel_futures=True drops any queued (not-yet-started) work.
                    ex.shutdown(wait=False, cancel_futures=True)

    async def _run_hooks_async(self, hooks: list[Callable[[], Any]], *, timeout: float | None = None) -> None:
        """Run hooks — supports both sync and async callables. Bounds each hook.

        With a timeout: coroutine-function hooks are awaited bounded; sync
        hooks run in a worker thread via ``asyncio.to_thread`` bounded (a sync
        hook running inline would be unbounded). If a sync hook returns a
        future, that future is awaited bounded as well.
        """
        for hook in hooks:
            if timeout is None:
                result = hook()
                if asyncio.iscoroutine(result):
                    await result
            elif inspect.iscoroutinefunction(hook):
                result = hook()  # builds the coroutine; body not yet executed
                try:
                    async with asyncio.timeout(timeout):
                        await result
                except TimeoutError as e:
                    raise TimeoutError(f"Startup hook {hook.__qualname__} exceeded timeout {timeout}s") from e
            else:
                # Sync hook — run in a thread so it is bounded by the timeout.
                try:
                    result = await asyncio.wait_for(asyncio.to_thread(hook), timeout=timeout)
                except TimeoutError as e:
                    raise TimeoutError(f"Startup hook {hook.__qualname__} exceeded timeout {timeout}s") from e
                if asyncio.isfuture(result):
                    try:
                        async with asyncio.timeout(timeout):
                            await result
                    except TimeoutError as e:
                        raise TimeoutError(f"Startup hook {hook.__qualname__} exceeded timeout {timeout}s") from e

Methods:

on_startup(func: Callable[[], Any]) -> Callable[[], Any]

Register a startup hook (decorator or direct call).

Source code in src/rabbitkit/core/app.py
def on_startup(self, func: Callable[[], Any]) -> Callable[[], Any]:
    """Register a startup hook (decorator or direct call)."""
    self._on_startup.append(func)
    return func

after_startup(func: Callable[[], Any]) -> Callable[[], Any]

Register a post-startup hook.

Source code in src/rabbitkit/core/app.py
def after_startup(self, func: Callable[[], Any]) -> Callable[[], Any]:
    """Register a post-startup hook."""
    self._after_startup.append(func)
    return func

on_shutdown(func: Callable[[], Any]) -> Callable[[], Any]

Register a shutdown hook.

Source code in src/rabbitkit/core/app.py
def on_shutdown(self, func: Callable[[], Any]) -> Callable[[], Any]:
    """Register a shutdown hook."""
    self._on_shutdown.append(func)
    return func

after_shutdown(func: Callable[[], Any]) -> Callable[[], Any]

Register a post-shutdown hook.

Source code in src/rabbitkit/core/app.py
def after_shutdown(self, func: Callable[[], Any]) -> Callable[[], Any]:
    """Register a post-shutdown hook."""
    self._after_shutdown.append(func)
    return func

start() -> None

Start the application (sync).

Idempotent and concurrency-safe — no-op if already running. On startup hook failure → on_shutdown is still called.

Source code in src/rabbitkit/core/app.py
def start(self) -> None:
    """Start the application (sync).

    Idempotent and concurrency-safe — no-op if already running.
    On startup hook failure → on_shutdown is still called.
    """
    with self._sync_lock:
        if self._state in (AppState.RUNNING, AppState.STARTING, AppState.STOPPING):
            logger.debug("App already %s, ignoring start()", self._state.value)
            return

        self._state = AppState.STARTING
        logger.info("Starting %s", self._title)

        try:
            self._run_hooks_sync(self._on_startup, timeout=self._startup_timeout)
            self._state = AppState.RUNNING
            self._run_hooks_sync(self._after_startup, timeout=self._startup_timeout)
            logger.info("%s started", self._title)
        except Exception:
            logger.exception("Startup failed, running shutdown hooks")
            self._state = AppState.STOPPING
            self._run_hooks_sync(self._on_shutdown)
            self._state = AppState.STOPPED
            raise

stop() -> None

Stop the application (sync).

Idempotent and concurrency-safe — no-op if already stopped.

Source code in src/rabbitkit/core/app.py
def stop(self) -> None:
    """Stop the application (sync).

    Idempotent and concurrency-safe — no-op if already stopped.
    """
    with self._sync_lock:
        if self._state in (AppState.STOPPED, AppState.STOPPING, AppState.IDLE):
            return

        self._state = AppState.STOPPING
        logger.info("Stopping %s", self._title)

        try:
            self._run_hooks_sync(self._on_shutdown)
        finally:
            self._run_hooks_sync(self._after_shutdown)
            self._state = AppState.STOPPED
            logger.info("%s stopped", self._title)

start_async() -> None async

Start the application (async).

Idempotent and concurrency-safe — no-op if already running. On startup hook failure → on_shutdown is still called.

Source code in src/rabbitkit/core/app.py
async def start_async(self) -> None:
    """Start the application (async).

    Idempotent and concurrency-safe — no-op if already running.
    On startup hook failure → on_shutdown is still called.
    """
    async with self._async_lock:
        if self._state in (AppState.RUNNING, AppState.STARTING, AppState.STOPPING):
            logger.debug("App already %s, ignoring start_async()", self._state.value)
            return

        self._state = AppState.STARTING
        logger.info("Starting %s", self._title)

        try:
            await self._run_hooks_async(self._on_startup, timeout=self._startup_timeout)
            self._state = AppState.RUNNING
            await self._run_hooks_async(self._after_startup, timeout=self._startup_timeout)
            logger.info("%s started", self._title)
        except Exception:
            logger.exception("Startup failed, running shutdown hooks")
            self._state = AppState.STOPPING
            await self._run_hooks_async(self._on_shutdown)
            self._state = AppState.STOPPED
            raise

stop_async() -> None async

Stop the application (async).

Idempotent and concurrency-safe — no-op if already stopped.

Source code in src/rabbitkit/core/app.py
async def stop_async(self) -> None:
    """Stop the application (async).

    Idempotent and concurrency-safe — no-op if already stopped.
    """
    async with self._async_lock:
        if self._state in (AppState.STOPPED, AppState.STOPPING, AppState.IDLE):
            return

        self._state = AppState.STOPPING
        logger.info("Stopping %s", self._title)

        try:
            await self._run_hooks_async(self._on_shutdown)
        finally:
            await self._run_hooks_async(self._after_shutdown)
            self._state = AppState.STOPPED
            logger.info("%s stopped", self._title)

run_async() -> None async

Start, wait for shutdown signal, then stop (async).

Installs SIGINT/SIGTERM handlers for graceful shutdown. Falls back to signal.signal on platforms/threads where loop.add_signal_handler is unavailable (e.g. Windows, non-main-thread).

the handlers in place before are kept. The Python-level handler (signal.getsignal) is captured and put back on exit: loop.remove_signal_handler alone resets the signal to its default, which dropped e.g. an application's SIGTERM handler or asyncio.run()'s SIGINT handler. A signal that already has an loop.add_signal_handler handler (asyncio cannot hand it back) is left alone with a WARNING; that handler should call :meth:request_shutdown. A handler installed by someone else while the app runs is not removed.

Source code in src/rabbitkit/core/app.py
async def run_async(self) -> None:
    """Start, wait for shutdown signal, then stop (async).

    Installs SIGINT/SIGTERM handlers for graceful shutdown. Falls back to
    ``signal.signal`` on platforms/threads where ``loop.add_signal_handler``
    is unavailable (e.g. Windows, non-main-thread).

    the handlers in place before are kept. The Python-level handler
    (``signal.getsignal``) is captured and put back on exit:
    ``loop.remove_signal_handler`` alone resets the signal to its
    default, which dropped e.g. an application's SIGTERM handler or
    ``asyncio.run()``'s SIGINT handler. A signal that already has an
    ``loop.add_signal_handler`` handler (asyncio cannot hand it back) is
    left alone with a WARNING; that handler should call
    :meth:`request_shutdown`. A handler installed by someone else while
    the app runs is not removed.
    """
    self._shutdown_event = asyncio.Event()

    loop = asyncio.get_running_loop()
    self._loop = loop
    installed: dict[signal.Signals, Any] = {}
    try:
        for sig in (signal.SIGINT, signal.SIGTERM):
            prev = signal.getsignal(sig)
            if is_loop_signal_handler(prev):
                logger.warning(
                    "RabbitApp: an asyncio handler for %s is already installed; not replacing it, "
                    "because asyncio cannot hand it back afterwards. That handler should call "
                    "app.request_shutdown().",
                    sig.name,
                )
                continue
            loop.add_signal_handler(sig, self._signal_handler)
            installed[sig] = prev
    except (NotImplementedError, RuntimeError, ValueError):  # pragma: no cover
        # Not supported on this platform/thread — fall back to signal.signal.
        # The handler runs in a signal context; schedule the set via the loop.
        for sig in (signal.SIGINT, signal.SIGTERM):
            try:
                self._original_handlers[sig] = signal.signal(sig, self._signal_handler_sync)
            except (ValueError, OSError):  # pragma: no cover
                pass  # not in main thread — best effort

    try:
        await self.start_async()
        await self._shutdown_event.wait()
    finally:
        await self.stop_async()
        self._restore_signal_handlers(loop, installed)

request_shutdown() -> None

Request graceful shutdown (can be called from any context).

Source code in src/rabbitkit/core/app.py
def request_shutdown(self) -> None:
    """Request graceful shutdown (can be called from any context)."""
    if self._shutdown_event is not None:
        self._shutdown_event.set()

AppState

Bases: str, Enum

Application lifecycle states.

Canonical home for this enum is core/types.py per the project rule that types.py is the SINGLE canonical location for all enums and data types.

Source code in src/rabbitkit/core/types.py
class AppState(str, Enum):
    """Application lifecycle states.

    Canonical home for this enum is ``core/types.py`` per the project rule that
    ``types.py`` is the SINGLE canonical location for all enums and data types.
    """

    IDLE = "idle"
    STARTING = "starting"
    RUNNING = "running"
    STOPPING = "stopping"
    STOPPED = "stopped"