Core Internals¶
HandlerPipeline¶
HandlerPipeline
¶
Executes the full message processing pipeline.
on_receive() receives a RabbitMessage (transport builds it first).
The pipeline is responsible for: 1. Ack timing (per AckPolicy) 2. Deserialization (via serializer) 3. Parameter resolution (via DI resolver) 4. Handler invocation 5. Result serialization and publishing 6. Settlement (ack/nack/reject)
Both sync and async variants are provided.
Source code in src/rabbitkit/core/pipeline.py
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 | |
Methods:¶
clear_caches() -> None
¶
Drop all per-route caches.
Clears the four route-keyed middleware-chain caches
(_consume_chain_cache, _consume_chain_async_cache,
_publish_chain_cache, _publish_chain_async_cache).
The caches are keyed by id(route) and are bounded by the number of
registered routes, which is typically small and stable. They are only
an eviction concern across reconnect/restart cycles where old
RouteDefinition objects are dropped and replaced by new ones; in
that case the stale entries (keyed by the old id) would otherwise
linger. Call this on reconnect/restart to reclaim them — the next
message rebuilds the chain lazily.
Does NOT clear the broker-level publish chain caches
(_broker_publish_chain_cache / _broker_publish_chain_async_cache)
— those are keyed by the broker's publish_middlewares list, which is
set once at construction and never mutated in place, so they cannot go
stale the way route-keyed caches can.
Source code in src/rabbitkit/core/pipeline.py
compose_broker_publish_sync(middlewares: list[Any]) -> Callable[[MessageEnvelope, Callable[[MessageEnvelope], PublishOutcome]], Any]
¶
Compose broker-level publish_scope middlewares into a reusable chain.
Unlike :meth:_compose_publish_sync (which wraps a route's
HANDLER-RESULT publishes per Contract 5), this wraps broker.publish()
itself — the primary producer API — so middleware such as signing or
tracing actually applies to direct publishes, not just replies/results.
Cached by id(middlewares): callers must pass the SAME list object on
every call (e.g. a broker stores it once at construction) for the cache
to hit — see :meth:clear_caches.
Source code in src/rabbitkit/core/pipeline.py
compose_broker_publish_async(middlewares: list[Any]) -> Callable[[MessageEnvelope, Callable[[MessageEnvelope], Awaitable[PublishOutcome]]], Awaitable[Any]]
¶
Async variant of :meth:compose_broker_publish_sync.
Source code in src/rabbitkit/core/pipeline.py
process_sync(route: RouteDefinition, message: RabbitMessage, publish_fn: Callable[[MessageEnvelope], PublishOutcome] | None = None) -> None
¶
Sync pipeline — calls msg.ack(), handler(), publish().
Pipeline stages: 1. ACK_FIRST: ack before handler 2. Deserialize body → resolve params → call handler 3. Process result (serialize + publish if applicable) 4. Settle message (ack/nack/reject per AckPolicy)
Source code in src/rabbitkit/core/pipeline.py
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 | |
process_async(route: RouteDefinition, message: RabbitMessage, publish_fn: Callable[[MessageEnvelope], Awaitable[PublishOutcome]] | None = None) -> None
async
¶
Async pipeline — calls await msg.ack_async(), await handler(), await publish().
Same stages as sync, but async.
Source code in src/rabbitkit/core/pipeline.py
SubscriberRegistry¶
SubscriberRegistry
¶
Stores all @subscriber/@publisher registrations.
Used by RabbitApp and RabbitRouter to collect route definitions which are later wired by the broker.
Source code in src/rabbitkit/core/registry.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 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 | |
Attributes¶
routes: list[RouteDefinition]
property
¶
Return all registered routes.
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) -> Callable[[Callable[..., Any]], Callable[..., Any]]
¶
Decorator to register a message handler for a queue.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
queue
|
RabbitQueue | str
|
Queue to consume from (str auto-creates RabbitQueue). |
required |
exchange
|
RabbitExchange | str | None
|
Exchange to bind to (str auto-creates RabbitExchange). |
None
|
routing_key
|
str
|
Routing key for binding. |
''
|
ack_policy
|
AckPolicy
|
Acknowledgment policy for this route. |
AUTO
|
middlewares
|
list[BaseMiddleware] | None
|
Route-specific middleware list. |
None
|
serializer
|
Serializer[Any] | None
|
Route-specific serializer override. |
None
|
retry
|
RetryConfig | RetryDisabled | None
|
Per-route retry config (None=inherit, RETRY_DISABLED=opt-out). |
None
|
tags
|
frozenset[str] | set[str] | None
|
Route tags for filtering/grouping. |
None
|
description
|
str
|
Human-readable route description. |
''
|
name
|
str | None
|
Explicit route name (auto-generated if None). |
None
|
prefetch_count
|
int | None
|
Per-route prefetch override (None=use global). |
None
|
reject_without_dlx
|
str | None
|
Per-route override of
|
None
|
Source code in src/rabbitkit/core/registry.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 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 | |
publisher(exchange: RabbitExchange | str | None = None, routing_key: str = '') -> Callable[[Callable[..., Any]], Callable[..., Any]]
¶
Decorator to configure result publishing for a handler.
Must be applied BEFORE @subscriber on the same handler. If applied without @subscriber, the publisher info is stored and applied when @subscriber is later applied.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exchange
|
RabbitExchange | str | None
|
Target exchange for result publishing. |
None
|
routing_key
|
str
|
Routing key for result publishing. |
''
|
Source code in src/rabbitkit/core/registry.py
include_router(router: RabbitRouter, prefix: str = '') -> None
¶
Include routes from a RabbitRouter.
Applies the router's prefix to routing keys and merges router-level defaults (exchange, middlewares, serializer, tags).
Source code in src/rabbitkit/core/registry.py
set_broker_retry(retry: RetryConfig | None) -> None
¶
Update broker retry default. Re-validates all existing routes.
validate_dlx_graph() -> None
¶
Detect dead-letter-exchange cycles across registered routes.
A queue's dead_letter_exchange points at an exchange; if that exchange
is the bind target of another route whose queue dead-letters back to an
exchange reachable from the first, messages loop forever (until TTL/GC).
This builds a queue→queue graph via DLX→exchange→bound-queue and rejects
any cycle with :class:ConfigurationError. Best-effort: only exchanges
named as a route's exchange are resolvable to a queue; unknown DLX
targets (external exchanges) are treated as sinks.
Source code in src/rabbitkit/core/registry.py
DuplicateRouteError
¶
RouteDefinition¶
RouteDefinition
dataclass
¶
Internal route model — produced by registry, consumed by broker.
Registration metadata is immutable (frozen) after creation. Runtime
state (consumer_tag) lives in the separate mutable
:class:RouteRuntimeState instance held by :attr:runtime_state, and
is populated by the broker during start/reconnect.
A backward-compatible consumer_tag property is provided (read-only)
that delegates to runtime_state.consumer_tag so that callers that
still read route.consumer_tag (e.g. health.py) keep working
without modification. Brokers write via
route.runtime_state.consumer_tag = ....
Contains all metadata needed to: - declare topology - start consuming - process messages through pipeline - publish results
See Contracts 1, 4, 5 for semantic rules.
Source code in src/rabbitkit/core/route.py
75 76 77 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 | |
Attributes¶
consumer_tag: str | None
property
¶
Active consumer tag for this route (delegates to runtime_state).
Read-only (L10) — kept for callers (e.g. health.py) that read
route.consumer_tag. To set it, write
route.runtime_state.consumer_tag = ... directly;
route.consumer_tag = ... raises (a TypeError, not a clean
FrozenInstanceError — a side effect of frozen=True combined
with slots=True and a same-named property) just like assigning
any other field on this frozen dataclass. There is no special-cased
__setattr__ here — the mutable runtime state lives entirely in
the separate :class:RouteRuntimeState object, and this class is
genuinely frozen.
Methods:¶
has_retry_enabled(broker_retry: RetryConfig | None = None) -> bool
¶
Check if this route has retry enabled.
Resolution order: 1. retry_override=RetryDisabled → NO retry (explicit opt-out) 2. retry_override=RetryConfig(...) → YES retry (per-route override) 3. retry_override=None → inherit broker default (broker_retry)
Source code in src/rabbitkit/core/route.py
effective_retry_config(broker_retry: RetryConfig | None = None) -> RetryConfig | None
¶
Get the effective retry config for this route.
Returns None if retry is disabled.
Source code in src/rabbitkit/core/route.py
validate_retry_ack_compatibility(broker_retry: RetryConfig | None = None) -> None
¶
Validate that retry + ack policy are compatible.
Raises ConfigurationError if retry is enabled on MANUAL or ACK_FIRST routes. Called at registration time — fail fast.
Source code in src/rabbitkit/core/route.py
validate_retry_dlx_conflict(broker_retry: RetryConfig | None = None) -> None
¶
Validate that retry and manual DLX config don't conflict.
If retry is enabled, RetryRouter owns DLQ topology. User must not also set dead_letter_exchange on the queue.
Source code in src/rabbitkit/core/route.py
validate_headers_binding() -> None
¶
Validate headers-exchange bindings at registration time (C4).
A headers exchange routes on binding arguments, not routing keys —
an argument-less binding matches everything (silent firehose /
misrouting). Require bind_arguments with a valid x-match.
Source code in src/rabbitkit/core/route.py
validate_reject_without_dlx_value() -> None
¶
Validate the per-route reject_without_dlx override value.
Source code in src/rabbitkit/core/route.py
validate(broker_retry: RetryConfig | None = None) -> None
¶
Run all route validations.
Called at registration time — fail fast on conflicts.
Source code in src/rabbitkit/core/route.py
can_reject_without_dlx(broker_retry: RetryConfig | None = None) -> bool
¶
True when this route can reject(requeue=False) into a queue
with no dead-letter path — i.e. RabbitMQ would discard the message.
Retry-enabled routes get a DLX from RetryRouter; a manually
configured dead_letter_exchange is a dead-letter path already.
ACK_FIRST routes without a filter ack before the handler runs, so
they never reject. Everything else (AUTO/NACK_ON_ERROR/MANUAL,
filter_fn, permanent-error classification) can reject.
Source code in src/rabbitkit/core/route.py
resolve_safety_dlq(safety: SafetyConfig, broker_retry: RetryConfig | None = None) -> str | None
¶
Apply the reject-without-DLX safety policy to this route (C3).
Returns the DLQ name to auto-provision, or None when nothing is
needed (route already has a dead-letter path, cannot reject, or the
policy is discard). Raises :class:UnsafeTopologyError under the
error policy.
Called by brokers during topology declaration, only under
TopologyMode.AUTO_DECLARE.
Source code in src/rabbitkit/core/route.py
ResultPublisher
dataclass
¶
Where to publish handler return values.
Set by @publisher decorator on a handler.
Source code in src/rabbitkit/core/route.py
ConfigurationError
¶
Bases: Exception
Raised for invalid configuration detected at registration time.
Single canonical class for all registration-time misconfigurations (route
conflicts, invalid handler signatures, bad retry/ack combinations). Both
core/route.py and di/resolver.py raise this; tests/users can catch
one type regardless of import source.
Source code in src/rabbitkit/core/errors.py
Error Classification¶
classify_error(exc: BaseException, *, predicates: Sequence[ErrorPredicate] = (), transient: tuple[type[BaseException], ...] = TRANSIENT_ERRORS, permanent: tuple[type[BaseException], ...] = PERMANENT_ERRORS, unknown_policy: ErrorSeverity = ErrorSeverity.PERMANENT) -> ClassifiedError
¶
Classify exception severity.
Evaluation order: 1. User predicates (first non-None wins) 2. transient tuple (isinstance check) 3. permanent tuple (isinstance check) 4. unknown_policy (configurable, default=PERMANENT)
DEFAULT IS PERMANENT, NOT TRANSIENT. Reason: unknown errors include malformed payloads, business validation failures, handler bugs, and schema mismatches. Treating these as transient creates retry storms. Network/connection errors are already in the transient tuple.
Override per-route: RetryMiddleware accepts unknown_policy to change per route.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exc
|
BaseException
|
The exception to classify. |
required |
predicates
|
Sequence[ErrorPredicate]
|
User-provided classification functions. Return True=transient, False=permanent, None=no opinion. |
()
|
transient
|
tuple[type[BaseException], ...]
|
Exception types considered transient. |
TRANSIENT_ERRORS
|
permanent
|
tuple[type[BaseException], ...]
|
Exception types considered permanent. |
PERMANENT_ERRORS
|
unknown_policy
|
ErrorSeverity
|
Severity for unclassified exceptions. |
PERMANENT
|
Returns:
| Type | Description |
|---|---|
ClassifiedError
|
ClassifiedError with severity, original exception, and reason. |
Source code in src/rabbitkit/core/errors.py
ErrorSeverity
¶
ClassifiedError
dataclass
¶
Exceptions¶
All raised for caller-side mistakes; the validation errors dual-inherit
ValueError and the runtime-misuse errors dual-inherit RuntimeError, so
pre-existing builtin catches keep working. See the
exception taxonomy for the
full table and catch patterns.
ConfigurationError
¶
Bases: Exception
Raised for invalid configuration detected at registration time.
Single canonical class for all registration-time misconfigurations (route
conflicts, invalid handler signatures, bad retry/ack combinations). Both
core/route.py and di/resolver.py raise this; tests/users can catch
one type regardless of import source.
Source code in src/rabbitkit/core/errors.py
ConfigValidationError
¶
Bases: ConfigurationError, ValueError
An invalid value was passed to a rabbitkit config object or
constructor — RabbitConfig sub-configs (RetryConfig(max_retries=-1),
WorkerConfig(max_queue_size=-1), …) and AMQP short-string fields
(queue/exchange/routing-key names that are too long or contain control
characters, including on MessageEnvelope).
Raised at construction time (__post_init__), so a bad value fails
where it's written, not at first use.
Source code in src/rabbitkit/core/errors.py
TopologyValidationError
¶
Bases: ConfigurationError, ValueError
An invalid RabbitQueue / RabbitExchange declaration — a
combination RabbitMQ itself would reject or silently misbehave on
(non-durable quorum queue, priorities on a stream, delivery_limit on
a classic queue, non-positive consumer_timeout, …).
Raised at model construction time, before anything touches the broker.
Source code in src/rabbitkit/core/errors.py
UnsafeTopologyError
¶
Bases: ConfigurationError
Raised at startup when RejectWithoutDLXPolicy.ERROR is active and a
route can reject(requeue=False) but its queue has no dead-letter
exchange — RabbitMQ would silently discard rejected messages.
Subclasses :class:ConfigurationError so existing catch-alls for
registration/startup misconfiguration keep working.
Source code in src/rabbitkit/core/errors.py
MessageTooLargeError
¶
Bases: ValueError
A publish was rejected client-side because the body exceeds
PublisherConfig.max_message_bytes (default 16 MiB, mirroring the
server's max_message_size default).
Raised before the bytes hit the wire: the server would reject the
message anyway, but with a channel exception that kills the (pooled)
publisher channel and corrupts sibling in-flight publishes. Subclasses
ValueError for backward compatibility with earlier releases that
raised it directly.
Source code in src/rabbitkit/core/errors.py
BrokerNotStartedError
¶
Bases: RuntimeError
A broker method that needs a live transport (publish(), RPC,
topology helpers) was called before start() (or after stop()).
SettlementError
¶
Bases: RuntimeError
Invalid message-settlement call: calling the sync settlement methods
(ack() ...) on a message from an async-only transport, or the async
variants (ack_async() ...) on a message with no settlement function
wired at all.
Defined here rather than in core/errors.py because errors.py
(indirectly, via types.py) imports this module -- it is re-exported
from rabbitkit.core.errors and the package root, which are the
import paths to use. Subclasses RuntimeError so pre-existing
except RuntimeError handlers keep working.
Source code in src/rabbitkit/core/message.py
MissingDependencyError
¶
Bases: Exception
Raised at message-processing time when a required Header() /
Path() / Context() marker's value is absent from the incoming
message and no default is available — neither on the marker itself
(Header("x-tenant", default=...)) nor the handler's own parameter
default (tenant: Annotated[str | None, Header("x-tenant")] = None).
Names the specific parameter and marker so the failure is immediately
actionable — unlike the bare KeyError this replaces, which looked
identical to a handler bug (e.g. indexing a dict) and gave no indication
which DI marker was the culprit. Classified PERMANENT by
:func:classify_error (see PERMANENT_ERRORS below), matching the
KeyError classification it replaces: a missing required value means
the message itself is malformed for this handler — retrying will not fix
it, so it settles straight to the DLQ rather than looping.
Source code in src/rabbitkit/core/errors.py
BackpressureError
¶
Bases: Exception
Raised when publish-side flow control blocks a publish attempt.
Only raised when BackpressureConfig.on_blocked == "raise".
PublishError
¶
Bases: Exception
Raised by PublishOutcome.raise_for_status() on a failed publish.
broker.publish() never raises on its own — it returns a
PublishOutcome so callers can decide how to handle NACKED / TIMEOUT /
RETURNED / ERROR. Code that prefers exceptions can opt in with
broker.publish(...).raise_for_status(). Carries the outcome for
inspection (status, routing_key, underlying error).
Source code in src/rabbitkit/core/errors.py
Protocols¶
Transport
¶
Bases: Protocol
Sync transport — implemented by sync/transport.py.
Minimal interface for sync message broker I/O.
Source code in src/rabbitkit/core/protocols.py
Methods:¶
connect() -> None
¶
disconnect() -> None
¶
is_connected() -> bool
¶
publish(envelope: MessageEnvelope) -> PublishOutcome
¶
consume(queue: str, callback: Callable[[RabbitMessage], None], prefetch: int = 10, *, no_ack: bool = False, declare: bool = True) -> str
¶
Start consuming from a queue. Returns consumer_tag.
no_ack=True starts a no-ack consumer (the broker auto-acks on
delivery; the built RabbitMessage gets no settlement functions).
declare=False skips declaring/checking the queue first — required
for AMQP pseudo-queues such as amq.rabbitmq.reply-to, which the
broker rejects any Queue.Declare for (active or passive).
Source code in src/rabbitkit/core/protocols.py
declare_exchange(exchange: RabbitExchange) -> None
¶
declare_queue(queue: RabbitQueue) -> None
¶
bind_queue(queue: str, exchange: str, routing_key: str, arguments: dict[str, Any] | None = None) -> None
¶
Bind a queue to an exchange with a routing key.
arguments carries header-match criteria for HEADERS exchanges.
Source code in src/rabbitkit/core/protocols.py
bind_exchange(destination: str, source: str, routing_key: str = '', arguments: dict[str, Any] | None = None) -> None
¶
Bind an exchange to another exchange (exchange-to-exchange binding).
AsyncTransport
¶
Bases: Protocol
Async transport — implemented by async_/transport.py.
Minimal interface for async message broker I/O.
Source code in src/rabbitkit/core/protocols.py
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 | |
Methods:¶
connect() -> None
async
¶
disconnect() -> None
async
¶
is_connected() -> bool
¶
publish(envelope: MessageEnvelope) -> PublishOutcome
async
¶
consume(queue: str, callback: Callable[[RabbitMessage], Awaitable[None]], prefetch: int = 10, *, no_ack: bool = False, declare: bool = True) -> str
async
¶
Start consuming from a queue. Returns consumer_tag.
no_ack=True starts a no-ack consumer (the broker auto-acks on
delivery; the built RabbitMessage gets no settlement functions).
declare=False skips declaring/checking the queue first — required
for AMQP pseudo-queues such as amq.rabbitmq.reply-to, which the
broker rejects any Queue.Declare for (active or passive).
Source code in src/rabbitkit/core/protocols.py
declare_exchange(exchange: RabbitExchange) -> None
async
¶
declare_queue(queue: RabbitQueue) -> None
async
¶
bind_queue(queue: str, exchange: str, routing_key: str, arguments: dict[str, Any] | None = None) -> None
async
¶
Bind a queue to an exchange with a routing key.
arguments carries header-match criteria for HEADERS exchanges.
Source code in src/rabbitkit/core/protocols.py
bind_exchange(destination: str, source: str, routing_key: str = '', arguments: dict[str, Any] | None = None) -> None
async
¶
Bind an exchange to another exchange (exchange-to-exchange binding).
SupportsBackpressure
¶
Bases: Protocol
Transport supports connection.blocked/unblocked callbacks.
Source code in src/rabbitkit/core/protocols.py
Types¶
ExchangeType
¶
QueueType
¶
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
Logging¶
LoggingConfig
dataclass
¶
Structured logging configuration.
Attributes:
| Name | Type | Description |
|---|---|---|
render_json |
bool
|
True for JSON output (prod), False for console (dev). |
add_log_level |
bool
|
Include log level in output. |
timestamper_fmt |
str
|
Timestamp format ("iso", "unix", or None to disable). |
include_caller_info |
bool
|
Add filename/line number to log events. |
redact_keys |
frozenset[str] | None
|
Key names to redact from log events -- checked at the
top level and one level deep inside nested dict values (e.g. a
|
capture_warnings |
bool
|
Route Python's |
Source code in src/rabbitkit/core/logging.py
configure_structlog(config: LoggingConfig | None = None) -> None
¶
One-time structlog configuration.
Safe to call multiple times — last call wins. If config is None, uses defaults (console renderer, ISO timestamps).
Source code in src/rabbitkit/core/logging.py
Path extraction¶
extract_path(actual_routing_key: str, pattern: str) -> dict[str, str]
¶
Extract named segments from a delivered routing key given the route pattern.
Positional: each {name} in the pattern maps to the same-index segment of
the actual key. Stops at a # (which spans a variable number of words, so
nothing after it has a fixed position). Returns {} when the pattern has no
named segments — the broker already matched the binding, so no validation is
needed here.
Source code in src/rabbitkit/core/path.py
to_binding_key(routing_key: str) -> str
¶
Translate {name} segments to the AMQP single-word wildcard *.
Routing keys without named segments are returned unchanged (fast path), so existing topic/direct routes are completely unaffected.