Skip to main content

nautilus_common/msgbus/
api.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Public API functions for interacting with the message bus.
17//!
18//! This module provides free-standing functions that wrap the thread-local
19//! message bus, providing a convenient API for:
20//!
21//! - Registering endpoint handlers (point-to-point messaging).
22//! - Subscribing to topics (pub/sub messaging).
23//! - Publishing messages to subscribers.
24//! - Sending messages to endpoints.
25
26use std::{any::Any, cell::RefCell, thread::LocalKey};
27
28use nautilus_core::UUID4;
29#[cfg(feature = "defi")]
30use nautilus_model::defi::{
31    Block, DefiData, Pool, PoolFeeCollect, PoolFlash, PoolLiquidityUpdate, PoolSwap,
32};
33use nautilus_model::{
34    data::{
35        Bar, Data, FundingRateUpdate, GreeksData, IndexPriceUpdate, MarkPriceUpdate,
36        OrderBookDeltas, OrderBookDepth, QuoteTick, TradeTick,
37        option_chain::{OptionChainSlice, OptionGreeks},
38    },
39    events::{AccountState, OrderEventAny, PortfolioSnapshot, PositionEvent},
40    instruments::InstrumentAny,
41    orderbook::OrderBook,
42    orders::OrderAny,
43    position::Position,
44};
45use smallvec::SmallVec;
46use ustr::Ustr;
47
48pub use super::external::{process_external_typed_message, republish_external_message};
49use super::{
50    ACCOUNT_STATE_HANDLERS, ANY_HANDLERS, BAR_HANDLERS, BOOK_HANDLERS, BusPayloadType,
51    DELTAS_HANDLERS, DEPTH_HANDLERS, FUNDING_RATE_HANDLERS, GREEKS_HANDLERS, HANDLER_BUFFER_CAP,
52    INDEX_PRICE_HANDLERS, INSTRUMENT_HANDLERS, MARK_PRICE_HANDLERS, OPTION_CHAIN_HANDLERS,
53    OPTION_GREEKS_HANDLERS, ORDER_EVENT_HANDLERS, PORTFOLIO_SNAPSHOT_HANDLERS,
54    POSITION_EVENT_HANDLERS, QUOTE_HANDLERS, TRADE_HANDLERS,
55    core::{MessageBus, Subscription},
56    dispatch_tap_publish, dispatch_tap_response, dispatch_tap_send,
57    external::{forward_any_to_external_egress, forward_to_external_egress},
58    get_message_bus,
59    matching::is_matching_backtracking,
60    mstr::{Endpoint, MStr, Pattern, Topic},
61    try_get_message_bus,
62    typed_handler::{ShareableMessageHandler, TypedHandler, TypedIntoHandler},
63};
64#[cfg(feature = "defi")]
65use super::{
66    DEFI_BLOCK_HANDLERS, DEFI_COLLECT_HANDLERS, DEFI_FLASH_HANDLERS, DEFI_LIQUIDITY_HANDLERS,
67    DEFI_POOL_HANDLERS, DEFI_SWAP_HANDLERS,
68};
69use crate::{
70    actor::PublicationScope,
71    messages::{
72        data::{DataCommand, DataResponse, DataResponseEnvelope},
73        execution::{ExecutionReport, TradingCommand},
74    },
75};
76
77/// Registers a handler for an endpoint using runtime type dispatch (Any).
78pub fn register_any(endpoint: MStr<Endpoint>, handler: ShareableMessageHandler) {
79    log::debug!(
80        "Registering endpoint '{endpoint}' with handler ID {}",
81        handler.0.id(),
82    );
83    get_message_bus()
84        .borrow_mut()
85        .endpoints
86        .insert(endpoint, handler);
87}
88
89/// Registers a response handler for a correlation ID.
90pub fn register_response_handler(
91    correlation_id: &UUID4,
92    handler: TypedHandler<DataResponseEnvelope>,
93) {
94    if let Err(e) = get_message_bus()
95        .borrow_mut()
96        .register_response_handler(correlation_id, handler)
97    {
98        log::error!("Failed to register request handler: {e}");
99    }
100}
101
102/// Registers a quote tick handler at an endpoint.
103pub fn register_quote_endpoint(endpoint: MStr<Endpoint>, handler: TypedHandler<QuoteTick>) {
104    get_message_bus()
105        .borrow_mut()
106        .endpoints_quotes
107        .register(endpoint, handler);
108}
109
110/// Returns whether a quote tick handler is registered for the given endpoint.
111#[must_use]
112pub fn has_quote_endpoint(endpoint: MStr<Endpoint>) -> bool {
113    get_message_bus()
114        .borrow()
115        .endpoints_quotes
116        .is_registered(endpoint)
117}
118
119/// Registers a trade tick handler at an endpoint.
120pub fn register_trade_endpoint(endpoint: MStr<Endpoint>, handler: TypedHandler<TradeTick>) {
121    get_message_bus()
122        .borrow_mut()
123        .endpoints_trades
124        .register(endpoint, handler);
125}
126
127/// Registers a bar handler at an endpoint.
128pub fn register_bar_endpoint(endpoint: MStr<Endpoint>, handler: TypedHandler<Bar>) {
129    get_message_bus()
130        .borrow_mut()
131        .endpoints_bars
132        .register(endpoint, handler);
133}
134
135/// Registers an order event handler at an endpoint (ownership-based).
136pub fn register_order_event_endpoint(
137    endpoint: MStr<Endpoint>,
138    handler: TypedIntoHandler<OrderEventAny>,
139) {
140    get_message_bus()
141        .borrow_mut()
142        .endpoints_order_events
143        .register(endpoint, handler);
144}
145
146/// Registers an account state handler at an endpoint.
147pub fn register_account_state_endpoint(
148    endpoint: MStr<Endpoint>,
149    handler: TypedHandler<AccountState>,
150) {
151    get_message_bus()
152        .borrow_mut()
153        .endpoints_account_state
154        .register(endpoint, handler);
155}
156
157/// Registers a trading command handler at an endpoint (ownership-based).
158pub fn register_trading_command_endpoint(
159    endpoint: MStr<Endpoint>,
160    handler: TypedIntoHandler<TradingCommand>,
161) {
162    get_message_bus()
163        .borrow_mut()
164        .endpoints_trading_commands
165        .register(endpoint, handler);
166}
167
168/// Registers a data command handler at an endpoint (ownership-based).
169pub fn register_data_command_endpoint(
170    endpoint: MStr<Endpoint>,
171    handler: TypedIntoHandler<DataCommand>,
172) {
173    get_message_bus()
174        .borrow_mut()
175        .endpoints_data_commands
176        .register(endpoint, handler);
177}
178
179/// Registers a data response handler at an endpoint (ownership-based).
180pub fn register_data_response_endpoint(
181    endpoint: MStr<Endpoint>,
182    handler: TypedIntoHandler<DataResponse>,
183) {
184    get_message_bus()
185        .borrow_mut()
186        .endpoints_data_responses
187        .register(endpoint, handler);
188}
189
190/// Registers an execution report handler at an endpoint (ownership-based).
191pub fn register_execution_report_endpoint(
192    endpoint: MStr<Endpoint>,
193    handler: TypedIntoHandler<ExecutionReport>,
194) {
195    get_message_bus()
196        .borrow_mut()
197        .endpoints_exec_reports
198        .register(endpoint, handler);
199}
200
201/// Registers a data handler at an endpoint (ownership-based).
202pub fn register_data_endpoint(endpoint: MStr<Endpoint>, handler: TypedIntoHandler<Data>) {
203    get_message_bus()
204        .borrow_mut()
205        .endpoints_data
206        .register(endpoint, handler);
207}
208
209/// Registers a DeFi data handler at an endpoint (ownership-based).
210#[cfg(feature = "defi")]
211pub fn register_defi_data_endpoint(endpoint: MStr<Endpoint>, handler: TypedIntoHandler<DefiData>) {
212    get_message_bus()
213        .borrow_mut()
214        .endpoints_defi_data
215        .register(endpoint, handler);
216}
217
218/// Deregisters the handler for an endpoint (Any-based).
219pub fn deregister_any(endpoint: MStr<Endpoint>) {
220    log::debug!("Deregistering endpoint '{endpoint}'");
221    get_message_bus()
222        .borrow_mut()
223        .endpoints
224        .shift_remove(&endpoint);
225}
226
227/// Returns whether an endpoint handler is registered for the given endpoint name.
228///
229/// An invalid endpoint name returns `false`, because registration rejects such names.
230#[must_use]
231pub fn has_endpoint(endpoint: &str) -> bool {
232    let Ok(key) = MStr::<Endpoint>::endpoint(endpoint) else {
233        return false;
234    };
235
236    get_message_bus().borrow().get_endpoint(key).is_some()
237}
238
239/// Subscribes a handler to a pattern using runtime type dispatch (Any).
240///
241/// # Warnings
242///
243/// Assigning priority handling is an advanced feature which *shouldn't
244/// normally be needed by most users*. **Only assign a higher priority to the
245/// subscription if you are certain of what you're doing**. If an inappropriate
246/// priority is assigned then the handler may receive messages before core
247/// system components have been able to process necessary calculations and
248/// produce potential side effects for logically sound behavior.
249pub fn subscribe_any(
250    pattern: MStr<Pattern>,
251    handler: ShareableMessageHandler,
252    priority: Option<u32>,
253) {
254    let msgbus = get_message_bus();
255    let mut msgbus_ref_mut = msgbus.borrow_mut();
256    let sub = Subscription::new(pattern, handler, priority);
257
258    log::debug!(
259        "Subscribing {:?} for pattern '{}'",
260        sub.handler,
261        sub.pattern
262    );
263
264    if msgbus_ref_mut.subscriptions.contains(&sub) {
265        log::warn!("{sub:?} already exists");
266        return;
267    }
268
269    for (topic, subs) in &mut msgbus_ref_mut.topics {
270        if is_matching_backtracking(*topic, sub.pattern) {
271            subs.push(sub.clone());
272            subs.sort_by(Subscription::delivery_order);
273            log::debug!("Added subscription for '{topic}'");
274        }
275    }
276
277    msgbus_ref_mut.subscriptions.insert(sub);
278}
279
280/// Subscribes a handler to instrument messages matching a pattern.
281pub fn subscribe_instruments(
282    pattern: MStr<Pattern>,
283    handler: TypedHandler<InstrumentAny>,
284    priority: Option<u32>,
285) {
286    get_message_bus().borrow_mut().router_instruments.subscribe(
287        pattern,
288        handler,
289        priority.unwrap_or(0),
290    );
291}
292
293/// Subscribes a handler to instrument close messages matching a pattern.
294pub fn subscribe_instrument_close(
295    pattern: MStr<Pattern>,
296    handler: ShareableMessageHandler,
297    priority: Option<u32>,
298) {
299    subscribe_any(pattern, handler, priority);
300}
301
302/// Subscribes a handler to order book deltas matching a pattern.
303pub fn subscribe_book_deltas(
304    pattern: MStr<Pattern>,
305    handler: TypedHandler<OrderBookDeltas>,
306    priority: Option<u32>,
307) {
308    get_message_bus()
309        .borrow_mut()
310        .router_deltas
311        .subscribe(pattern, handler, priority.unwrap_or(0));
312}
313
314/// Subscribes a handler to order book depth snapshots matching a pattern.
315pub fn subscribe_book_depth(
316    pattern: MStr<Pattern>,
317    handler: TypedHandler<OrderBookDepth>,
318    priority: Option<u32>,
319) {
320    get_message_bus()
321        .borrow_mut()
322        .router_depth
323        .subscribe(pattern, handler, priority.unwrap_or(0));
324}
325
326/// Subscribes a handler to order book snapshots matching a pattern.
327pub fn subscribe_book_snapshots(
328    pattern: MStr<Pattern>,
329    handler: TypedHandler<OrderBook>,
330    priority: Option<u32>,
331) {
332    get_message_bus()
333        .borrow_mut()
334        .router_book_snapshots
335        .subscribe(pattern, handler, priority.unwrap_or(0));
336}
337
338/// Subscribes a handler to quote ticks matching a pattern.
339pub fn subscribe_quotes(
340    pattern: MStr<Pattern>,
341    handler: TypedHandler<QuoteTick>,
342    priority: Option<u32>,
343) {
344    get_message_bus()
345        .borrow_mut()
346        .router_quotes
347        .subscribe(pattern, handler, priority.unwrap_or(0));
348}
349
350/// Subscribes a handler to trade ticks matching a pattern.
351pub fn subscribe_trades(
352    pattern: MStr<Pattern>,
353    handler: TypedHandler<TradeTick>,
354    priority: Option<u32>,
355) {
356    get_message_bus()
357        .borrow_mut()
358        .router_trades
359        .subscribe(pattern, handler, priority.unwrap_or(0));
360}
361
362/// Subscribes a handler to bars matching a pattern.
363pub fn subscribe_bars(pattern: MStr<Pattern>, handler: TypedHandler<Bar>, priority: Option<u32>) {
364    get_message_bus()
365        .borrow_mut()
366        .router_bars
367        .subscribe(pattern, handler, priority.unwrap_or(0));
368}
369
370/// Subscribes a handler to mark price updates matching a pattern.
371pub fn subscribe_mark_prices(
372    pattern: MStr<Pattern>,
373    handler: TypedHandler<MarkPriceUpdate>,
374    priority: Option<u32>,
375) {
376    get_message_bus().borrow_mut().router_mark_prices.subscribe(
377        pattern,
378        handler,
379        priority.unwrap_or(0),
380    );
381}
382
383/// Subscribes a handler to index price updates matching a pattern.
384pub fn subscribe_index_prices(
385    pattern: MStr<Pattern>,
386    handler: TypedHandler<IndexPriceUpdate>,
387    priority: Option<u32>,
388) {
389    get_message_bus()
390        .borrow_mut()
391        .router_index_prices
392        .subscribe(pattern, handler, priority.unwrap_or(0));
393}
394
395/// Subscribes a handler to funding rate updates matching a pattern.
396pub fn subscribe_funding_rates(
397    pattern: MStr<Pattern>,
398    handler: TypedHandler<FundingRateUpdate>,
399    priority: Option<u32>,
400) {
401    get_message_bus()
402        .borrow_mut()
403        .router_funding_rates
404        .subscribe(pattern, handler, priority.unwrap_or(0));
405}
406
407/// Subscribes a handler to greeks data matching a pattern.
408pub fn subscribe_greeks(
409    pattern: MStr<Pattern>,
410    handler: TypedHandler<GreeksData>,
411    priority: Option<u32>,
412) {
413    get_message_bus()
414        .borrow_mut()
415        .router_greeks
416        .subscribe(pattern, handler, priority.unwrap_or(0));
417}
418
419/// Subscribes a handler to option greeks updates matching a pattern.
420pub fn subscribe_option_greeks(
421    pattern: MStr<Pattern>,
422    handler: TypedHandler<OptionGreeks>,
423    priority: Option<u32>,
424) {
425    get_message_bus()
426        .borrow_mut()
427        .router_option_greeks
428        .subscribe(pattern, handler, priority.unwrap_or(0));
429}
430
431/// Subscribes a handler to option chain slice updates matching a pattern.
432pub fn subscribe_option_chain(
433    pattern: MStr<Pattern>,
434    handler: TypedHandler<OptionChainSlice>,
435    priority: Option<u32>,
436) {
437    get_message_bus()
438        .borrow_mut()
439        .router_option_chain
440        .subscribe(pattern, handler, priority.unwrap_or(0));
441}
442
443/// Subscribes a handler to order events matching a pattern.
444pub fn subscribe_order_events(
445    pattern: MStr<Pattern>,
446    handler: TypedHandler<OrderEventAny>,
447    priority: Option<u32>,
448) {
449    get_message_bus()
450        .borrow_mut()
451        .router_order_events
452        .subscribe(pattern, handler, priority.unwrap_or(0));
453}
454
455/// Subscribes a handler to position events matching a pattern.
456pub fn subscribe_position_events(
457    pattern: MStr<Pattern>,
458    handler: TypedHandler<PositionEvent>,
459    priority: Option<u32>,
460) {
461    get_message_bus()
462        .borrow_mut()
463        .router_position_events
464        .subscribe(pattern, handler, priority.unwrap_or(0));
465}
466
467/// Subscribes a handler to positions matching a pattern.
468pub fn subscribe_positions(
469    pattern: MStr<Pattern>,
470    handler: TypedHandler<Position>,
471    priority: Option<u32>,
472) {
473    get_message_bus().borrow_mut().router_positions.subscribe(
474        pattern,
475        handler,
476        priority.unwrap_or(0),
477    );
478}
479
480/// Subscribes a handler to account state updates matching a pattern.
481pub fn subscribe_account_state(
482    pattern: MStr<Pattern>,
483    handler: TypedHandler<AccountState>,
484    priority: Option<u32>,
485) {
486    get_message_bus()
487        .borrow_mut()
488        .router_account_state
489        .subscribe(pattern, handler, priority.unwrap_or(0));
490}
491
492/// Subscribes a handler to portfolio snapshots matching a pattern.
493pub fn subscribe_portfolio_snapshot(
494    pattern: MStr<Pattern>,
495    handler: TypedHandler<PortfolioSnapshot>,
496    priority: Option<u32>,
497) {
498    get_message_bus().borrow_mut().router_portfolio.subscribe(
499        pattern,
500        handler,
501        priority.unwrap_or(0),
502    );
503}
504
505/// Subscribes a handler to DeFi blocks matching a pattern.
506#[cfg(feature = "defi")]
507pub fn subscribe_defi_blocks(
508    pattern: MStr<Pattern>,
509    handler: TypedHandler<Block>,
510    priority: Option<u32>,
511) {
512    get_message_bus().borrow_mut().router_defi_blocks.subscribe(
513        pattern,
514        handler,
515        priority.unwrap_or(0),
516    );
517}
518
519/// Subscribes a handler to DeFi pools matching a pattern.
520#[cfg(feature = "defi")]
521pub fn subscribe_defi_pools(
522    pattern: MStr<Pattern>,
523    handler: TypedHandler<Pool>,
524    priority: Option<u32>,
525) {
526    get_message_bus().borrow_mut().router_defi_pools.subscribe(
527        pattern,
528        handler,
529        priority.unwrap_or(0),
530    );
531}
532
533/// Subscribes a handler to DeFi pool swaps matching a pattern.
534#[cfg(feature = "defi")]
535pub fn subscribe_defi_swaps(
536    pattern: MStr<Pattern>,
537    handler: TypedHandler<PoolSwap>,
538    priority: Option<u32>,
539) {
540    get_message_bus().borrow_mut().router_defi_swaps.subscribe(
541        pattern,
542        handler,
543        priority.unwrap_or(0),
544    );
545}
546
547/// Subscribes a handler to DeFi liquidity updates matching a pattern.
548#[cfg(feature = "defi")]
549pub fn subscribe_defi_liquidity(
550    pattern: MStr<Pattern>,
551    handler: TypedHandler<PoolLiquidityUpdate>,
552    priority: Option<u32>,
553) {
554    get_message_bus()
555        .borrow_mut()
556        .router_defi_liquidity
557        .subscribe(pattern, handler, priority.unwrap_or(0));
558}
559
560/// Subscribes a handler to DeFi fee collects matching a pattern.
561#[cfg(feature = "defi")]
562pub fn subscribe_defi_collects(
563    pattern: MStr<Pattern>,
564    handler: TypedHandler<PoolFeeCollect>,
565    priority: Option<u32>,
566) {
567    get_message_bus()
568        .borrow_mut()
569        .router_defi_collects
570        .subscribe(pattern, handler, priority.unwrap_or(0));
571}
572
573/// Subscribes a handler to DeFi flash loans matching a pattern.
574#[cfg(feature = "defi")]
575pub fn subscribe_defi_flash(
576    pattern: MStr<Pattern>,
577    handler: TypedHandler<PoolFlash>,
578    priority: Option<u32>,
579) {
580    get_message_bus().borrow_mut().router_defi_flash.subscribe(
581        pattern,
582        handler,
583        priority.unwrap_or(0),
584    );
585}
586
587/// Unsubscribes a handler from instrument messages.
588pub fn unsubscribe_instruments(pattern: MStr<Pattern>, handler: &TypedHandler<InstrumentAny>) {
589    get_message_bus()
590        .borrow_mut()
591        .router_instruments
592        .unsubscribe(pattern, handler);
593}
594
595/// Unsubscribes a handler from instrument close messages.
596pub fn unsubscribe_instrument_close(pattern: MStr<Pattern>, handler: &ShareableMessageHandler) {
597    unsubscribe_any(pattern, handler);
598}
599
600/// Unsubscribes a handler from order book deltas.
601pub fn unsubscribe_book_deltas(pattern: MStr<Pattern>, handler: &TypedHandler<OrderBookDeltas>) {
602    get_message_bus()
603        .borrow_mut()
604        .router_deltas
605        .unsubscribe(pattern, handler);
606}
607
608/// Unsubscribes a handler from order book depth snapshots.
609pub fn unsubscribe_book_depth(pattern: MStr<Pattern>, handler: &TypedHandler<OrderBookDepth>) {
610    get_message_bus()
611        .borrow_mut()
612        .router_depth
613        .unsubscribe(pattern, handler);
614}
615
616/// Unsubscribes a handler from order book snapshots.
617pub fn unsubscribe_book_snapshots(pattern: MStr<Pattern>, handler: &TypedHandler<OrderBook>) {
618    get_message_bus()
619        .borrow_mut()
620        .router_book_snapshots
621        .unsubscribe(pattern, handler);
622}
623
624/// Unsubscribes a handler from quote ticks.
625pub fn unsubscribe_quotes(pattern: MStr<Pattern>, handler: &TypedHandler<QuoteTick>) {
626    get_message_bus()
627        .borrow_mut()
628        .router_quotes
629        .unsubscribe(pattern, handler);
630}
631
632/// Unsubscribes a handler from trade ticks.
633pub fn unsubscribe_trades(pattern: MStr<Pattern>, handler: &TypedHandler<TradeTick>) {
634    get_message_bus()
635        .borrow_mut()
636        .router_trades
637        .unsubscribe(pattern, handler);
638}
639
640/// Unsubscribes a handler from bars.
641pub fn unsubscribe_bars(pattern: MStr<Pattern>, handler: &TypedHandler<Bar>) {
642    get_message_bus()
643        .borrow_mut()
644        .router_bars
645        .unsubscribe(pattern, handler);
646}
647
648/// Unsubscribes a handler from mark price updates.
649pub fn unsubscribe_mark_prices(pattern: MStr<Pattern>, handler: &TypedHandler<MarkPriceUpdate>) {
650    get_message_bus()
651        .borrow_mut()
652        .router_mark_prices
653        .unsubscribe(pattern, handler);
654}
655
656/// Unsubscribes a handler from index price updates.
657pub fn unsubscribe_index_prices(pattern: MStr<Pattern>, handler: &TypedHandler<IndexPriceUpdate>) {
658    get_message_bus()
659        .borrow_mut()
660        .router_index_prices
661        .unsubscribe(pattern, handler);
662}
663
664/// Unsubscribes a handler from funding rate updates.
665pub fn unsubscribe_funding_rates(
666    pattern: MStr<Pattern>,
667    handler: &TypedHandler<FundingRateUpdate>,
668) {
669    get_message_bus()
670        .borrow_mut()
671        .router_funding_rates
672        .unsubscribe(pattern, handler);
673}
674
675/// Unsubscribes a handler from account state updates.
676pub fn unsubscribe_account_state(pattern: MStr<Pattern>, handler: &TypedHandler<AccountState>) {
677    get_message_bus()
678        .borrow_mut()
679        .router_account_state
680        .unsubscribe(pattern, handler);
681}
682
683/// Unsubscribes a handler from portfolio snapshots.
684pub fn unsubscribe_portfolio_snapshot(
685    pattern: MStr<Pattern>,
686    handler: &TypedHandler<PortfolioSnapshot>,
687) {
688    get_message_bus()
689        .borrow_mut()
690        .router_portfolio
691        .unsubscribe(pattern, handler);
692}
693
694/// Unsubscribes a handler from order events.
695pub fn unsubscribe_order_events(pattern: MStr<Pattern>, handler: &TypedHandler<OrderEventAny>) {
696    get_message_bus()
697        .borrow_mut()
698        .router_order_events
699        .unsubscribe(pattern, handler);
700}
701
702/// Unsubscribes a handler from position events.
703pub fn unsubscribe_position_events(pattern: MStr<Pattern>, handler: &TypedHandler<PositionEvent>) {
704    get_message_bus()
705        .borrow_mut()
706        .router_position_events
707        .unsubscribe(pattern, handler);
708}
709
710/// Removes a specific order event handler by pattern and handler ID.
711pub fn remove_order_event_handler(pattern: MStr<Pattern>, handler_id: Ustr) {
712    get_message_bus()
713        .borrow_mut()
714        .router_order_events
715        .remove_handler(pattern, handler_id);
716}
717
718/// Removes a specific position event handler by pattern and handler ID.
719pub fn remove_position_event_handler(pattern: MStr<Pattern>, handler_id: Ustr) {
720    get_message_bus()
721        .borrow_mut()
722        .router_position_events
723        .remove_handler(pattern, handler_id);
724}
725
726/// Unsubscribes a handler from orders.
727pub fn unsubscribe_orders(pattern: MStr<Pattern>, handler: &TypedHandler<OrderAny>) {
728    get_message_bus()
729        .borrow_mut()
730        .router_orders
731        .unsubscribe(pattern, handler);
732}
733
734/// Unsubscribes a handler from positions.
735pub fn unsubscribe_positions(pattern: MStr<Pattern>, handler: &TypedHandler<Position>) {
736    get_message_bus()
737        .borrow_mut()
738        .router_positions
739        .unsubscribe(pattern, handler);
740}
741
742/// Unsubscribes a handler from greeks data.
743pub fn unsubscribe_greeks(pattern: MStr<Pattern>, handler: &TypedHandler<GreeksData>) {
744    get_message_bus()
745        .borrow_mut()
746        .router_greeks
747        .unsubscribe(pattern, handler);
748}
749
750/// Unsubscribes a handler from option greeks updates.
751pub fn unsubscribe_option_greeks(pattern: MStr<Pattern>, handler: &TypedHandler<OptionGreeks>) {
752    get_message_bus()
753        .borrow_mut()
754        .router_option_greeks
755        .unsubscribe(pattern, handler);
756}
757
758/// Unsubscribes a handler from option chain slice updates.
759pub fn unsubscribe_option_chain(pattern: MStr<Pattern>, handler: &TypedHandler<OptionChainSlice>) {
760    get_message_bus()
761        .borrow_mut()
762        .router_option_chain
763        .unsubscribe(pattern, handler);
764}
765
766/// Unsubscribes a handler from DeFi blocks.
767#[cfg(feature = "defi")]
768pub fn unsubscribe_defi_blocks(pattern: MStr<Pattern>, handler: &TypedHandler<Block>) {
769    get_message_bus()
770        .borrow_mut()
771        .router_defi_blocks
772        .unsubscribe(pattern, handler);
773}
774
775/// Unsubscribes a handler from DeFi pools.
776#[cfg(feature = "defi")]
777pub fn unsubscribe_defi_pools(pattern: MStr<Pattern>, handler: &TypedHandler<Pool>) {
778    get_message_bus()
779        .borrow_mut()
780        .router_defi_pools
781        .unsubscribe(pattern, handler);
782}
783
784/// Unsubscribes a handler from DeFi pool swaps.
785#[cfg(feature = "defi")]
786pub fn unsubscribe_defi_swaps(pattern: MStr<Pattern>, handler: &TypedHandler<PoolSwap>) {
787    get_message_bus()
788        .borrow_mut()
789        .router_defi_swaps
790        .unsubscribe(pattern, handler);
791}
792
793/// Unsubscribes a handler from DeFi liquidity updates.
794#[cfg(feature = "defi")]
795pub fn unsubscribe_defi_liquidity(
796    pattern: MStr<Pattern>,
797    handler: &TypedHandler<PoolLiquidityUpdate>,
798) {
799    get_message_bus()
800        .borrow_mut()
801        .router_defi_liquidity
802        .unsubscribe(pattern, handler);
803}
804
805/// Unsubscribes a handler from DeFi fee collects.
806#[cfg(feature = "defi")]
807pub fn unsubscribe_defi_collects(pattern: MStr<Pattern>, handler: &TypedHandler<PoolFeeCollect>) {
808    get_message_bus()
809        .borrow_mut()
810        .router_defi_collects
811        .unsubscribe(pattern, handler);
812}
813
814/// Unsubscribes a handler from DeFi flash loans.
815#[cfg(feature = "defi")]
816pub fn unsubscribe_defi_flash(pattern: MStr<Pattern>, handler: &TypedHandler<PoolFlash>) {
817    get_message_bus()
818        .borrow_mut()
819        .router_defi_flash
820        .unsubscribe(pattern, handler);
821}
822
823/// Unsubscribes a handler from a pattern (Any-based).
824pub fn unsubscribe_any(pattern: MStr<Pattern>, handler: &ShareableMessageHandler) {
825    get_message_bus()
826        .borrow_mut()
827        .unsubscribe_any(pattern, handler);
828}
829
830/// Checks if a handler is subscribed to a pattern (Any-based).
831pub fn is_subscribed_any<T: AsRef<str>>(pattern: T, handler: ShareableMessageHandler) -> bool {
832    let pattern = MStr::from(pattern.as_ref());
833    let sub = Subscription::new(pattern, handler, None);
834    get_message_bus().borrow().subscriptions.contains(&sub)
835}
836
837/// Returns the count of Any-based subscriptions for a topic.
838///
839/// # Errors
840///
841/// Returns an error if the `topic` is not a valid topic string.
842pub fn subscriptions_count_any<S: AsRef<str>>(topic: S) -> anyhow::Result<usize> {
843    get_message_bus().borrow().subscriptions_count(topic)
844}
845
846/// Returns the subscriber count for order book deltas on a topic.
847pub fn subscriber_count_deltas(topic: MStr<Topic>) -> usize {
848    get_message_bus()
849        .borrow()
850        .router_deltas
851        .subscriber_count(topic)
852}
853
854/// Returns the subscriber count for order book depth on a topic.
855pub fn subscriber_count_depth(topic: MStr<Topic>) -> usize {
856    get_message_bus()
857        .borrow()
858        .router_depth
859        .subscriber_count(topic)
860}
861
862/// Returns the subscriber count for order book snapshots on a topic.
863pub fn subscriber_count_book_snapshots(topic: MStr<Topic>) -> usize {
864    get_message_bus()
865        .borrow()
866        .router_book_snapshots
867        .subscriber_count(topic)
868}
869
870/// Returns the exact subscriber count for quotes on a topic,
871/// excluding wildcard pattern subscriptions.
872pub fn exact_subscriber_count_quotes(topic: MStr<Topic>) -> usize {
873    get_message_bus()
874        .borrow()
875        .router_quotes
876        .exact_subscriber_count(topic)
877}
878
879/// Returns the exact subscriber count for trades on a topic,
880/// excluding wildcard pattern subscriptions.
881pub fn exact_subscriber_count_trades(topic: MStr<Topic>) -> usize {
882    get_message_bus()
883        .borrow()
884        .router_trades
885        .exact_subscriber_count(topic)
886}
887
888/// Returns the exact subscriber count for mark prices on a topic,
889/// excluding wildcard pattern subscriptions.
890pub fn exact_subscriber_count_mark_prices(topic: MStr<Topic>) -> usize {
891    get_message_bus()
892        .borrow()
893        .router_mark_prices
894        .exact_subscriber_count(topic)
895}
896
897/// Returns the exact subscriber count for index prices on a topic,
898/// excluding wildcard pattern subscriptions.
899pub fn exact_subscriber_count_index_prices(topic: MStr<Topic>) -> usize {
900    get_message_bus()
901        .borrow()
902        .router_index_prices
903        .exact_subscriber_count(topic)
904}
905
906/// Returns the exact subscriber count for funding rates on a topic,
907/// excluding wildcard pattern subscriptions.
908pub fn exact_subscriber_count_funding_rates(topic: MStr<Topic>) -> usize {
909    get_message_bus()
910        .borrow()
911        .router_funding_rates
912        .exact_subscriber_count(topic)
913}
914
915/// Returns the exact subscriber count for option greeks on a topic,
916/// excluding wildcard pattern subscriptions.
917pub fn exact_subscriber_count_option_greeks(topic: MStr<Topic>) -> usize {
918    get_message_bus()
919        .borrow()
920        .router_option_greeks
921        .exact_subscriber_count(topic)
922}
923
924/// Returns the exact subscriber count for option chains on a topic,
925/// excluding wildcard pattern subscriptions.
926pub fn exact_subscriber_count_option_chain(topic: MStr<Topic>) -> usize {
927    get_message_bus()
928        .borrow()
929        .router_option_chain
930        .exact_subscriber_count(topic)
931}
932
933/// Returns the exact subscriber count for bars on a topic,
934/// excluding wildcard pattern subscriptions.
935pub fn exact_subscriber_count_bars(topic: MStr<Topic>) -> usize {
936    get_message_bus()
937        .borrow()
938        .router_bars
939        .exact_subscriber_count(topic)
940}
941
942/// Publishes a message to the topic using runtime type dispatch (Any).
943pub fn publish_any(topic: MStr<Topic>, message: &dyn Any) {
944    let _publication = PublicationScope::enter();
945    dispatch_tap_publish(topic, message);
946
947    // Take buffer (re-entrancy safe)
948    let mut handlers = ANY_HANDLERS.with_borrow_mut(std::mem::take);
949
950    {
951        let bus_rc = get_message_bus();
952        let mut bus = bus_rc.borrow_mut();
953        bus.fill_matching_any_handlers(topic, &mut handlers);
954        bus.increment_pub_count();
955    }
956
957    for handler in &handlers {
958        handler.0.handle(message);
959    }
960
961    handlers.clear(); // Release refs before restore
962    ANY_HANDLERS.with_borrow_mut(|buf| *buf = handlers);
963
964    forward_any_to_external_egress(topic, message);
965}
966
967/// Tries to publish a message to the current thread's registered message bus.
968///
969/// Returns `false` when the thread has no bus or the bus is already borrowed.
970pub fn try_publish_any(topic: MStr<Topic>, message: &dyn Any) -> bool {
971    let Some(bus_rc) = try_get_message_bus() else {
972        return false;
973    };
974
975    if bus_rc.try_borrow_mut().is_err() {
976        return false;
977    }
978
979    let _publication = PublicationScope::enter();
980    dispatch_tap_publish(topic, message);
981
982    let Ok(mut bus) = bus_rc.try_borrow_mut() else {
983        return false;
984    };
985
986    // Take buffer (re-entrancy safe)
987    let mut handlers = ANY_HANDLERS.with_borrow_mut(std::mem::take);
988
989    bus.fill_matching_any_handlers(topic, &mut handlers);
990    bus.increment_pub_count();
991    drop(bus);
992
993    for handler in &handlers {
994        handler.0.handle(message);
995    }
996
997    handlers.clear(); // Release refs before restore
998    ANY_HANDLERS.with_borrow_mut(|buf| *buf = handlers);
999    true
1000}
1001
1002/// Publishes an instrument to subscribers on a topic.
1003pub fn publish_instrument(topic: MStr<Topic>, instrument: &InstrumentAny) {
1004    publish_typed(
1005        topic,
1006        &INSTRUMENT_HANDLERS,
1007        |bus, h| bus.router_instruments.fill_matching_handlers(topic, h),
1008        instrument,
1009    );
1010
1011    forward_to_external_egress(topic, BusPayloadType::Instrument, instrument);
1012}
1013
1014/// Publishes order book deltas to subscribers on a topic.
1015pub fn publish_deltas(topic: MStr<Topic>, deltas: &OrderBookDeltas) {
1016    publish_typed(
1017        topic,
1018        &DELTAS_HANDLERS,
1019        |bus, h| bus.router_deltas.fill_matching_handlers(topic, h),
1020        deltas,
1021    );
1022
1023    forward_to_external_egress(topic, BusPayloadType::OrderBookDeltas, deltas);
1024}
1025
1026/// Publishes order book depth to subscribers on a topic.
1027pub fn publish_depth(topic: MStr<Topic>, depth: &OrderBookDepth) {
1028    publish_typed(
1029        topic,
1030        &DEPTH_HANDLERS,
1031        |bus, h| bus.router_depth.fill_matching_handlers(topic, h),
1032        depth,
1033    );
1034
1035    forward_to_external_egress(topic, BusPayloadType::OrderBookDepth, depth);
1036}
1037
1038/// Publishes an order book snapshot to subscribers on a topic.
1039pub fn publish_book(topic: MStr<Topic>, book: &OrderBook) {
1040    publish_typed(
1041        topic,
1042        &BOOK_HANDLERS,
1043        |bus, h| bus.router_book_snapshots.fill_matching_handlers(topic, h),
1044        book,
1045    );
1046}
1047
1048/// Publishes a quote tick to subscribers on a topic.
1049pub fn publish_quote(topic: MStr<Topic>, quote: &QuoteTick) {
1050    publish_typed(
1051        topic,
1052        &QUOTE_HANDLERS,
1053        |bus, h| bus.router_quotes.fill_matching_handlers(topic, h),
1054        quote,
1055    );
1056
1057    forward_to_external_egress(topic, BusPayloadType::QuoteTick, quote);
1058}
1059
1060/// Publishes a trade tick to subscribers on a topic.
1061pub fn publish_trade(topic: MStr<Topic>, trade: &TradeTick) {
1062    publish_typed(
1063        topic,
1064        &TRADE_HANDLERS,
1065        |bus, h| bus.router_trades.fill_matching_handlers(topic, h),
1066        trade,
1067    );
1068
1069    forward_to_external_egress(topic, BusPayloadType::TradeTick, trade);
1070}
1071
1072/// Publishes a bar to subscribers on a topic.
1073pub fn publish_bar(topic: MStr<Topic>, bar: &Bar) {
1074    publish_typed(
1075        topic,
1076        &BAR_HANDLERS,
1077        |bus, h| bus.router_bars.fill_matching_handlers(topic, h),
1078        bar,
1079    );
1080
1081    forward_to_external_egress(topic, BusPayloadType::Bar, bar);
1082}
1083
1084/// Publishes a mark price update to subscribers on a topic.
1085pub fn publish_mark_price(topic: MStr<Topic>, mark_price: &MarkPriceUpdate) {
1086    publish_typed(
1087        topic,
1088        &MARK_PRICE_HANDLERS,
1089        |bus, h| bus.router_mark_prices.fill_matching_handlers(topic, h),
1090        mark_price,
1091    );
1092
1093    forward_to_external_egress(topic, BusPayloadType::MarkPriceUpdate, mark_price);
1094}
1095
1096/// Publishes an index price update to subscribers on a topic.
1097pub fn publish_index_price(topic: MStr<Topic>, index_price: &IndexPriceUpdate) {
1098    publish_typed(
1099        topic,
1100        &INDEX_PRICE_HANDLERS,
1101        |bus, h| bus.router_index_prices.fill_matching_handlers(topic, h),
1102        index_price,
1103    );
1104
1105    forward_to_external_egress(topic, BusPayloadType::IndexPriceUpdate, index_price);
1106}
1107
1108/// Publishes a funding rate update to subscribers on a topic.
1109pub fn publish_funding_rate(topic: MStr<Topic>, funding_rate: &FundingRateUpdate) {
1110    publish_typed(
1111        topic,
1112        &FUNDING_RATE_HANDLERS,
1113        |bus, h| bus.router_funding_rates.fill_matching_handlers(topic, h),
1114        funding_rate,
1115    );
1116
1117    forward_to_external_egress(topic, BusPayloadType::FundingRateUpdate, funding_rate);
1118}
1119
1120/// Publishes greeks data to subscribers on a topic.
1121pub fn publish_greeks(topic: MStr<Topic>, greeks: &GreeksData) {
1122    publish_typed(
1123        topic,
1124        &GREEKS_HANDLERS,
1125        |bus, h| bus.router_greeks.fill_matching_handlers(topic, h),
1126        greeks,
1127    );
1128}
1129
1130/// Publishes option greeks to subscribers on a topic.
1131pub fn publish_option_greeks(topic: MStr<Topic>, option_greeks: &OptionGreeks) {
1132    publish_typed(
1133        topic,
1134        &OPTION_GREEKS_HANDLERS,
1135        |bus, h| bus.router_option_greeks.fill_matching_handlers(topic, h),
1136        option_greeks,
1137    );
1138
1139    forward_to_external_egress(topic, BusPayloadType::OptionGreeks, option_greeks);
1140}
1141
1142/// Publishes an option chain slice to subscribers on a topic.
1143pub fn publish_option_chain(topic: MStr<Topic>, slice: &OptionChainSlice) {
1144    publish_typed(
1145        topic,
1146        &OPTION_CHAIN_HANDLERS,
1147        |bus, h| bus.router_option_chain.fill_matching_handlers(topic, h),
1148        slice,
1149    );
1150}
1151
1152/// Publishes an account state to subscribers on a topic.
1153pub fn publish_account_state(topic: MStr<Topic>, state: &AccountState) {
1154    publish_typed(
1155        topic,
1156        &ACCOUNT_STATE_HANDLERS,
1157        |bus, h| bus.router_account_state.fill_matching_handlers(topic, h),
1158        state,
1159    );
1160
1161    forward_to_external_egress(topic, BusPayloadType::AccountState, state);
1162}
1163
1164/// Publishes a portfolio snapshot to subscribers on a topic.
1165pub fn publish_portfolio_snapshot(topic: MStr<Topic>, snapshot: &PortfolioSnapshot) {
1166    publish_typed(
1167        topic,
1168        &PORTFOLIO_SNAPSHOT_HANDLERS,
1169        |bus, h| {
1170            bus.router_portfolio.fill_matching_handlers(topic, h);
1171        },
1172        snapshot,
1173    );
1174
1175    forward_to_external_egress(topic, BusPayloadType::PortfolioSnapshot, snapshot);
1176}
1177
1178/// Publishes an order event to subscribers on a topic.
1179pub fn publish_order_event(topic: MStr<Topic>, event: &OrderEventAny) {
1180    publish_typed(
1181        topic,
1182        &ORDER_EVENT_HANDLERS,
1183        |bus, h| bus.router_order_events.fill_matching_handlers(topic, h),
1184        event,
1185    );
1186
1187    forward_to_external_egress(topic, BusPayloadType::OrderEvent, event);
1188}
1189
1190/// Publishes a position event to subscribers on a topic.
1191pub fn publish_position_event(topic: MStr<Topic>, event: &PositionEvent) {
1192    publish_typed(
1193        topic,
1194        &POSITION_EVENT_HANDLERS,
1195        |bus, h| bus.router_position_events.fill_matching_handlers(topic, h),
1196        event,
1197    );
1198
1199    forward_to_external_egress(topic, BusPayloadType::PositionEvent, event);
1200}
1201
1202/// Publishes a DeFi block to subscribers on a topic.
1203#[cfg(feature = "defi")]
1204pub fn publish_defi_block(topic: MStr<Topic>, block: &Block) {
1205    publish_typed(
1206        topic,
1207        &DEFI_BLOCK_HANDLERS,
1208        |bus, h| bus.router_defi_blocks.fill_matching_handlers(topic, h),
1209        block,
1210    );
1211
1212    forward_to_external_egress(topic, BusPayloadType::Block, block);
1213}
1214
1215/// Publishes a DeFi pool to subscribers on a topic.
1216#[cfg(feature = "defi")]
1217pub fn publish_defi_pool(topic: MStr<Topic>, pool: &Pool) {
1218    publish_typed(
1219        topic,
1220        &DEFI_POOL_HANDLERS,
1221        |bus, h| bus.router_defi_pools.fill_matching_handlers(topic, h),
1222        pool,
1223    );
1224
1225    forward_to_external_egress(topic, BusPayloadType::Pool, pool);
1226}
1227
1228/// Publishes a DeFi pool swap to subscribers on a topic.
1229#[cfg(feature = "defi")]
1230pub fn publish_defi_swap(topic: MStr<Topic>, swap: &PoolSwap) {
1231    publish_typed(
1232        topic,
1233        &DEFI_SWAP_HANDLERS,
1234        |bus, h| bus.router_defi_swaps.fill_matching_handlers(topic, h),
1235        swap,
1236    );
1237}
1238
1239/// Publishes a DeFi liquidity update to subscribers on a topic.
1240#[cfg(feature = "defi")]
1241pub fn publish_defi_liquidity(topic: MStr<Topic>, update: &PoolLiquidityUpdate) {
1242    publish_typed(
1243        topic,
1244        &DEFI_LIQUIDITY_HANDLERS,
1245        |bus, h| bus.router_defi_liquidity.fill_matching_handlers(topic, h),
1246        update,
1247    );
1248
1249    forward_to_external_egress(topic, BusPayloadType::PoolLiquidityUpdate, update);
1250}
1251
1252/// Publishes a DeFi fee collect to subscribers on a topic.
1253#[cfg(feature = "defi")]
1254pub fn publish_defi_collect(topic: MStr<Topic>, collect: &PoolFeeCollect) {
1255    publish_typed(
1256        topic,
1257        &DEFI_COLLECT_HANDLERS,
1258        |bus, h| bus.router_defi_collects.fill_matching_handlers(topic, h),
1259        collect,
1260    );
1261
1262    forward_to_external_egress(topic, BusPayloadType::PoolFeeCollect, collect);
1263}
1264
1265/// Publishes a DeFi flash loan to subscribers on a topic.
1266#[cfg(feature = "defi")]
1267pub fn publish_defi_flash(topic: MStr<Topic>, flash: &PoolFlash) {
1268    publish_typed(
1269        topic,
1270        &DEFI_FLASH_HANDLERS,
1271        |bus, h| bus.router_defi_flash.fill_matching_handlers(topic, h),
1272        flash,
1273    );
1274
1275    forward_to_external_egress(topic, BusPayloadType::PoolFlash, flash);
1276}
1277
1278/// Publishes a message to typed handlers using thread-local buffer reuse.
1279///
1280/// The `fill_fn` receives a mutable reference to the `MessageBus`, avoiding
1281/// redundant TLS access and Rc clone/drop overhead per publish.
1282///
1283/// Before fanout the registered bus tap (if any) observes the message. Capture must
1284/// precede subscriber dispatch so the durable record exists before any handler reacts
1285/// to the message.
1286///
1287/// # Invariants
1288///
1289/// - `fill_fn` must not call any publish path (would panic from `RefCell` double-borrow).
1290/// - Handler panics drop the buffer, losing reuse optimization (acceptable as panics are fatal).
1291#[inline]
1292fn publish_typed<T: 'static>(
1293    topic: MStr<Topic>,
1294    tls: &'static LocalKey<RefCell<SmallVec<[TypedHandler<T>; HANDLER_BUFFER_CAP]>>>,
1295    fill_fn: impl FnOnce(&mut MessageBus, &mut SmallVec<[TypedHandler<T>; HANDLER_BUFFER_CAP]>),
1296    message: &T,
1297) {
1298    let _publication = PublicationScope::enter();
1299    dispatch_tap_publish(topic, message);
1300
1301    // Take buffer (re-entrancy safe)
1302    let mut handlers = tls.with_borrow_mut(std::mem::take);
1303
1304    // Borrow scope ends before dispatch to support re-entrant publishes
1305    let bus_rc = get_message_bus();
1306    {
1307        let mut bus = bus_rc.borrow_mut();
1308        fill_fn(&mut bus, &mut handlers);
1309        bus.increment_pub_count();
1310    }
1311
1312    for handler in &handlers {
1313        handler.handle(message);
1314    }
1315
1316    handlers.clear(); // Release refs before restore
1317    tls.with_borrow_mut(|buf| *buf = handlers);
1318}
1319
1320/// Sends a message to an endpoint handler using runtime type dispatch (Any).
1321pub fn send_any(endpoint: MStr<Endpoint>, message: &dyn Any) {
1322    send_any_inner(endpoint, message, "send_any");
1323}
1324
1325/// Sends a message to an endpoint, converting to Any (convenience wrapper).
1326pub fn send_any_value<T: 'static>(endpoint: MStr<Endpoint>, message: &T) {
1327    send_any_inner(endpoint, message, "send_any_value");
1328}
1329
1330#[inline]
1331fn send_any_inner(endpoint: MStr<Endpoint>, message: &dyn Any, fn_name: &str) {
1332    dispatch_tap_send(endpoint, message);
1333
1334    let handler = {
1335        let bus = get_message_bus();
1336        let mut bus = bus.borrow_mut();
1337        let handler = bus.get_endpoint(endpoint).cloned();
1338        if handler.is_some() {
1339            bus.increment_sent_count();
1340        }
1341        handler
1342    };
1343
1344    if let Some(handler) = handler {
1345        handler.0.handle(message);
1346    } else {
1347        log::error!("{fn_name}: no registered endpoint '{endpoint}'");
1348    }
1349}
1350
1351/// Sends the [`DataResponse`] to the registered correlation ID handler.
1352pub fn send_response(correlation_id: &UUID4, message: &DataResponse) {
1353    let source = (correlation_id != message.correlation_id()).then_some(*message.correlation_id());
1354    let envelope = DataResponseEnvelope::new(message.clone(), true, source)
1355        .with_correlation_id(*correlation_id);
1356    send_response_envelope(&envelope);
1357}
1358
1359/// Delivers an envelope and removes its correlation handler only on completion.
1360pub fn send_response_envelope(message: &DataResponseEnvelope) {
1361    let correlation_id = message.correlation_id();
1362    dispatch_tap_response(correlation_id, message);
1363
1364    let handler = {
1365        let bus = get_message_bus();
1366        let mut bus = bus.borrow_mut();
1367        let handler = if message.completed() {
1368            bus.take_response_handler(correlation_id)
1369        } else {
1370            bus.get_response_handler(correlation_id).cloned()
1371        };
1372
1373        bus.increment_res_count();
1374        handler
1375    };
1376
1377    if let Some(handler) = handler {
1378        handler.0.handle(message);
1379    } else {
1380        log::debug!("Response handler not found for correlation_id '{correlation_id}'");
1381    }
1382}
1383
1384/// Sends a quote tick to an endpoint handler.
1385pub fn send_quote(endpoint: MStr<Endpoint>, quote: &QuoteTick) {
1386    send_endpoint_ref(
1387        endpoint,
1388        quote,
1389        |bus| bus.endpoints_quotes.get(endpoint),
1390        "send_quote",
1391    );
1392}
1393
1394/// Sends a trade tick to an endpoint handler.
1395pub fn send_trade(endpoint: MStr<Endpoint>, trade: &TradeTick) {
1396    send_endpoint_ref(
1397        endpoint,
1398        trade,
1399        |bus| bus.endpoints_trades.get(endpoint),
1400        "send_trade",
1401    );
1402}
1403
1404/// Sends a bar to an endpoint handler.
1405pub fn send_bar(endpoint: MStr<Endpoint>, bar: &Bar) {
1406    send_endpoint_ref(
1407        endpoint,
1408        bar,
1409        |bus| bus.endpoints_bars.get(endpoint),
1410        "send_bar",
1411    );
1412}
1413
1414/// Sends an order event to an endpoint handler, transferring ownership.
1415pub fn send_order_event(endpoint: MStr<Endpoint>, event: OrderEventAny) {
1416    send_endpoint_owned(
1417        endpoint,
1418        event,
1419        |bus| bus.endpoints_order_events.get(endpoint),
1420        "send_order_event",
1421    );
1422}
1423
1424/// Sends an account state to an endpoint handler.
1425pub fn send_account_state(endpoint: MStr<Endpoint>, state: &AccountState) {
1426    send_endpoint_ref(
1427        endpoint,
1428        state,
1429        |bus| bus.endpoints_account_state.get(endpoint),
1430        "send_account_state",
1431    );
1432}
1433
1434/// Sends a trading command to an endpoint handler, transferring ownership.
1435pub fn send_trading_command(endpoint: MStr<Endpoint>, command: TradingCommand) {
1436    send_endpoint_owned(
1437        endpoint,
1438        command,
1439        |bus| bus.endpoints_trading_commands.get(endpoint),
1440        "send_trading_command",
1441    );
1442}
1443
1444/// Sends a data command to an endpoint handler, transferring ownership.
1445pub fn send_data_command(endpoint: MStr<Endpoint>, command: DataCommand) {
1446    let is_request = data_command_is_request(&command);
1447    send_endpoint_owned_counted(
1448        endpoint,
1449        command,
1450        |bus| bus.endpoints_data_commands.get(endpoint),
1451        "send_data_command",
1452        is_request,
1453    );
1454}
1455
1456/// Sends a data response to an endpoint handler, transferring ownership.
1457pub fn send_data_response(endpoint: MStr<Endpoint>, response: DataResponse) {
1458    send_endpoint_owned(
1459        endpoint,
1460        response,
1461        |bus| bus.endpoints_data_responses.get(endpoint),
1462        "send_data_response",
1463    );
1464}
1465
1466/// Sends an execution report to an endpoint handler, transferring ownership.
1467pub fn send_execution_report(endpoint: MStr<Endpoint>, report: ExecutionReport) {
1468    send_endpoint_owned(
1469        endpoint,
1470        report,
1471        |bus| bus.endpoints_exec_reports.get(endpoint),
1472        "send_execution_report",
1473    );
1474}
1475
1476/// Sends data to an endpoint handler, transferring ownership.
1477pub fn send_data(endpoint: MStr<Endpoint>, data: Data) {
1478    send_endpoint_owned(
1479        endpoint,
1480        data,
1481        |bus| bus.endpoints_data.get(endpoint),
1482        "send_data",
1483    );
1484}
1485
1486/// Sends DeFi data to an endpoint handler, transferring ownership.
1487#[cfg(feature = "defi")]
1488pub fn send_defi_data(endpoint: MStr<Endpoint>, data: DefiData) {
1489    send_endpoint_owned(
1490        endpoint,
1491        data,
1492        |bus| bus.endpoints_defi_data.get(endpoint),
1493        "send_defi_data",
1494    );
1495}
1496
1497#[inline]
1498fn send_endpoint_ref<T: 'static, F>(
1499    endpoint: MStr<Endpoint>,
1500    message: &T,
1501    get_handler: F,
1502    fn_name: &str,
1503) where
1504    F: FnOnce(&MessageBus) -> Option<&TypedHandler<T>>,
1505{
1506    dispatch_tap_send(endpoint, message);
1507
1508    let handler = {
1509        let bus = get_message_bus();
1510        let mut bus = bus.borrow_mut();
1511        let handler = get_handler(&bus).cloned();
1512        if handler.is_some() {
1513            bus.increment_sent_count();
1514        }
1515        handler
1516    };
1517
1518    if let Some(handler) = handler {
1519        handler.handle(message);
1520    } else {
1521        log::error!("{fn_name}: no registered endpoint '{endpoint}'");
1522    }
1523}
1524
1525#[inline]
1526fn send_endpoint_owned<T: 'static, F>(
1527    endpoint: MStr<Endpoint>,
1528    message: T,
1529    get_handler: F,
1530    fn_name: &str,
1531) where
1532    F: FnOnce(&MessageBus) -> Option<&TypedIntoHandler<T>>,
1533{
1534    send_endpoint_owned_counted(endpoint, message, get_handler, fn_name, false);
1535}
1536
1537#[inline]
1538fn send_endpoint_owned_counted<T: 'static, F>(
1539    endpoint: MStr<Endpoint>,
1540    message: T,
1541    get_handler: F,
1542    fn_name: &str,
1543    count_request: bool,
1544) where
1545    F: FnOnce(&MessageBus) -> Option<&TypedIntoHandler<T>>,
1546{
1547    // Capture before the dispatch consumes `message`
1548    dispatch_tap_send(endpoint, &message);
1549
1550    let handler = {
1551        let bus = get_message_bus();
1552        let mut bus = bus.borrow_mut();
1553        let handler = get_handler(&bus).cloned();
1554        if handler.is_some() {
1555            bus.increment_sent_count();
1556            if count_request {
1557                bus.increment_req_count();
1558            }
1559        }
1560        handler
1561    };
1562
1563    if let Some(handler) = handler {
1564        handler.handle(message);
1565    } else {
1566        log::error!("{fn_name}: no registered endpoint '{endpoint}'");
1567    }
1568}
1569
1570#[inline]
1571fn data_command_is_request(command: &DataCommand) -> bool {
1572    match command {
1573        DataCommand::Request(_) => true,
1574        #[cfg(feature = "defi")]
1575        DataCommand::DefiRequest(_) => true,
1576        _ => false,
1577    }
1578}
1579
1580#[cfg(test)]
1581mod tests {
1582    //! Tests for the message bus API functions.
1583    //!
1584    //! Includes re-entrancy tests that verify handlers can call back into the
1585    //! message bus without causing `RefCell` borrow conflicts. This is the scenario
1586    //! where `send_*` holds a borrow, calls the handler, and the handler needs to
1587    //! call `borrow_mut()` for topic getters or other operations.
1588
1589    use std::{
1590        cell::{Cell, RefCell},
1591        rc::Rc,
1592        sync::Arc,
1593        thread,
1594    };
1595
1596    #[cfg(feature = "defi")]
1597    use alloy_primitives::{U256, address};
1598    use bytes::Bytes;
1599    use nautilus_core::{UUID4, UnixNanos};
1600    #[cfg(feature = "defi")]
1601    use nautilus_model::defi::{
1602        AmmType, Chain, Dex, DexType, PoolIdentifier, PoolLiquidityUpdateType, Token,
1603    };
1604    #[cfg(feature = "sbe")]
1605    use nautilus_model::{data::OptionGreekValues, enums::GreeksConvention};
1606    use nautilus_model::{
1607        data::{
1608            Bar, BarType, CustomData, DataType, FundingRateUpdate, IndexPriceUpdate,
1609            MarkPriceUpdate, OptionGreeks, OrderBookDelta, OrderBookDeltas, OrderBookDepth,
1610            QuoteTick, TradeTick,
1611            stubs::{stub_custom_data, stub_deltas, stub_depth10},
1612        },
1613        enums::{
1614            AccountType, BookType, LiquiditySide, OrderSide, OrderStatus, OrderType, PositionSide,
1615            TimeInForce,
1616        },
1617        events::{OrderEventAny, PositionEvent, PositionOpened, order::spec::OrderDeniedSpec},
1618        identifiers::{
1619            AccountId, ClientId, ClientOrderId, InstrumentId, OptionSeriesId, PositionId,
1620            StrategyId, TradeId, TraderId, Venue, VenueOrderId,
1621        },
1622        instruments::{InstrumentAny, stubs::audusd_sim},
1623        orderbook::OrderBook,
1624        reports::{ExecutionMassStatus, FillReport, OrderStatusReport, PositionStatusReport},
1625        types::{Currency, Money, Price, Quantity},
1626    };
1627    #[cfg(feature = "sbe")]
1628    use nautilus_serialization::sbe::FromSbe;
1629    use rstest::rstest;
1630    use rust_decimal::Decimal;
1631
1632    use super::*;
1633    use crate::{
1634        enums::SerializationEncoding,
1635        messages::{
1636            data::{
1637                BarsResponse, BookDeltasResponse, BookDepthResponse, BookResponse,
1638                CustomDataResponse, DataCommand, DataResponse, DataResponseEnvelope,
1639                FundingRatesResponse, InstrumentResponse, InstrumentsResponse,
1640                OptionChainReferencePriceResponse, QuotesResponse, RequestCommand, RequestQuotes,
1641                SubscribeCommand, SubscribeQuotes, TradesResponse, UnsubscribeCommand,
1642                UnsubscribeQuotes,
1643            },
1644            execution::{CancelAllOrders, GenerateExecutionMassStatus, TradingCommand},
1645        },
1646        msgbus::{
1647            BusMessage, BusTap, MessageBusConfig, MessageBusExternalEgress, MessagingSwitchboard,
1648            SuppressExternalGuard, clear_bus_tap, set_bus_tap, set_message_bus,
1649            stubs::get_call_check_handler, switchboard::get_quotes_topic,
1650        },
1651    };
1652
1653    #[derive(Debug)]
1654    struct CapturedEgressMessage {
1655        topic: String,
1656        encoding: SerializationEncoding,
1657        payload_type: BusPayloadType,
1658        payload: Bytes,
1659    }
1660
1661    struct CapturingExternalEgress {
1662        publications: Rc<RefCell<Vec<CapturedEgressMessage>>>,
1663        closed: Cell<bool>,
1664    }
1665
1666    impl CapturingExternalEgress {
1667        fn new() -> (Self, Rc<RefCell<Vec<CapturedEgressMessage>>>) {
1668            let publications = Rc::new(RefCell::new(Vec::new()));
1669            (
1670                Self {
1671                    publications: publications.clone(),
1672                    closed: Cell::new(false),
1673                },
1674                publications,
1675            )
1676        }
1677    }
1678
1679    impl MessageBusExternalEgress for CapturingExternalEgress {
1680        fn is_closed(&self) -> bool {
1681            self.closed.get()
1682        }
1683
1684        fn publish(&self, message: BusMessage) {
1685            self.publications.borrow_mut().push(CapturedEgressMessage {
1686                topic: message.topic.to_string(),
1687                encoding: message.encoding,
1688                payload_type: message.payload_type,
1689                payload: message.payload,
1690            });
1691        }
1692
1693        fn close(&mut self) {
1694            self.closed.set(true);
1695        }
1696    }
1697
1698    fn install_capturing_external_egress(
1699        encoding: SerializationEncoding,
1700    ) -> Rc<RefCell<Vec<CapturedEgressMessage>>> {
1701        let msgbus = Rc::new(RefCell::new(MessageBus::default()));
1702        set_message_bus(msgbus.clone());
1703        let (external_egress, publications) = CapturingExternalEgress::new();
1704        msgbus
1705            .borrow_mut()
1706            .set_external_egress(Box::new(external_egress), encoding);
1707        publications
1708    }
1709
1710    fn install_capturing_external_egress_config(
1711        config: &MessageBusConfig,
1712    ) -> Rc<RefCell<Vec<CapturedEgressMessage>>> {
1713        let msgbus = Rc::new(RefCell::new(MessageBus::default()));
1714        set_message_bus(msgbus.clone());
1715        let (external_egress, publications) = CapturingExternalEgress::new();
1716        msgbus
1717            .borrow_mut()
1718            .set_external_egress_config(Box::new(external_egress), config)
1719            .expect("message bus config must be valid");
1720        publications
1721    }
1722
1723    fn install_capturing_external_stream_egress(
1724        encoding: SerializationEncoding,
1725    ) -> Rc<RefCell<Vec<CapturedEgressMessage>>> {
1726        install_capturing_external_egress_config(&MessageBusConfig {
1727            encoding,
1728            external_streams: Some(vec!["external.test".to_string()]),
1729            ..Default::default()
1730        })
1731    }
1732
1733    fn reset_message_bus() {
1734        get_message_bus().borrow_mut().dispose();
1735        set_message_bus(Rc::new(RefCell::new(MessageBus::default())));
1736    }
1737
1738    fn assert_response_handler_is_consumed(response: &DataResponse) {
1739        reset_message_bus();
1740
1741        let correlation_id = *response.correlation_id();
1742        let response_kind = response.kind();
1743        let calls = Rc::new(Cell::new(0));
1744        let handler_calls = calls.clone();
1745        register_response_handler(
1746            &correlation_id,
1747            TypedHandler::from(move |_response: &DataResponseEnvelope| {
1748                handler_calls.set(handler_calls.get() + 1);
1749            }),
1750        );
1751
1752        send_response(&correlation_id, response);
1753        send_response(&correlation_id, response);
1754
1755        assert_eq!(
1756            calls.get(),
1757            1,
1758            "{response_kind} response handler must only run once",
1759        );
1760        assert!(
1761            get_message_bus()
1762                .borrow()
1763                .get_response_handler(&correlation_id)
1764                .is_none(),
1765            "{response_kind} response handler must be removed after dispatch",
1766        );
1767        assert_eq!(
1768            get_message_bus().borrow().res_count(),
1769            2,
1770            "{response_kind} duplicate responses must still increment the response count",
1771        );
1772    }
1773
1774    #[rstest]
1775    #[case("")]
1776    #[case("   ")]
1777    #[case("\t\n")]
1778    #[case("*")]
1779    #[case("mailbox.*")]
1780    #[case("mail?ox")]
1781    fn has_endpoint_returns_false_for_invalid_name(#[case] endpoint: &str) {
1782        reset_message_bus();
1783
1784        assert!(!has_endpoint(endpoint));
1785    }
1786
1787    #[rstest]
1788    #[case(SerializationEncoding::MsgPack)]
1789    #[case(SerializationEncoding::Json)]
1790    fn publish_quote_forwards_decodable_payload_to_external_egress(
1791        #[case] encoding: SerializationEncoding,
1792    ) {
1793        let publications = install_capturing_external_egress(encoding);
1794        let quote = QuoteTick::default();
1795
1796        publish_quote("data.quotes.TEST".into(), &quote);
1797
1798        let publications = publications.borrow();
1799        assert_eq!(publications.len(), 1);
1800        assert_eq!(publications[0].topic, "data.quotes.TEST");
1801
1802        let decoded: QuoteTick = match encoding {
1803            SerializationEncoding::MsgPack => rmp_serde::from_slice(&publications[0].payload)
1804                .expect("MsgPack payload must decode as QuoteTick"),
1805            SerializationEncoding::Json => serde_json::from_slice(&publications[0].payload)
1806                .expect("JSON payload must decode as QuoteTick"),
1807            SerializationEncoding::Sbe => {
1808                unreachable!("schema encodings are tested separately")
1809            }
1810        };
1811        let payload_value: serde_json::Value = match encoding {
1812            SerializationEncoding::MsgPack => rmp_serde::from_slice(&publications[0].payload)
1813                .expect("MsgPack payload must decode as a value"),
1814            SerializationEncoding::Json => serde_json::from_slice(&publications[0].payload)
1815                .expect("JSON payload must decode as a value"),
1816            SerializationEncoding::Sbe => {
1817                unreachable!("schema encodings are tested separately")
1818            }
1819        };
1820        assert_eq!(
1821            payload_value.get("type").and_then(|value| value.as_str()),
1822            Some("QuoteTick")
1823        );
1824        assert_eq!(decoded, quote);
1825        drop(publications);
1826        reset_message_bus();
1827    }
1828
1829    fn assert_quote_round_trips(
1830        encoding: SerializationEncoding,
1831        with_data_endpoint: bool,
1832        external_data_ingress: bool,
1833    ) {
1834        let publications = install_capturing_external_egress(encoding);
1835        let quote = QuoteTick::default();
1836        let topic = get_quotes_topic(quote.instrument_id);
1837
1838        publish_quote(topic, &quote);
1839
1840        let bus_message = {
1841            let publications = publications.borrow();
1842            assert_eq!(publications.len(), 1);
1843            assert_eq!(publications[0].payload_type, BusPayloadType::QuoteTick);
1844            assert_eq!(publications[0].encoding, encoding);
1845            BusMessage::with_str_topic(
1846                publications[0].topic.clone(),
1847                publications[0].payload_type,
1848                publications[0].payload.clone(),
1849                publications[0].encoding,
1850            )
1851        };
1852        publications.borrow_mut().clear();
1853
1854        let received = Rc::new(RefCell::new(Vec::<QuoteTick>::new()));
1855        let received_handler = received.clone();
1856        let handler = TypedHandler::from(move |quote: &QuoteTick| {
1857            received_handler.borrow_mut().push(*quote);
1858        });
1859        subscribe_quotes("data.quotes.*".into(), handler, None);
1860
1861        let processed = Rc::new(RefCell::new(Vec::new()));
1862        if with_data_endpoint {
1863            let processed = Rc::clone(&processed);
1864            register_data_endpoint(
1865                MessagingSwitchboard::data_engine_process_data(),
1866                TypedIntoHandler::from(move |data: Data| {
1867                    let Data::Quote(quote) = data else {
1868                        panic!("expected quote data");
1869                    };
1870
1871                    processed.borrow_mut().push(quote);
1872                    publish_quote(topic, &quote);
1873                }),
1874            );
1875        }
1876
1877        get_message_bus()
1878            .borrow_mut()
1879            .set_external_data_ingress(external_data_ingress);
1880        get_message_bus()
1881            .borrow_mut()
1882            .add_streaming_type(BusPayloadType::QuoteTick);
1883        republish_external_message(&bus_message).unwrap();
1884
1885        assert_eq!(*received.borrow(), vec![quote]);
1886        assert_eq!(
1887            *processed.borrow(),
1888            if with_data_endpoint && external_data_ingress {
1889                vec![quote]
1890            } else {
1891                vec![]
1892            }
1893        );
1894        assert!(
1895            publications.borrow().is_empty(),
1896            "republished message must not be forwarded back out externally"
1897        );
1898        reset_message_bus();
1899    }
1900
1901    #[rstest]
1902    #[case(SerializationEncoding::Json)]
1903    #[case(SerializationEncoding::MsgPack)]
1904    fn republish_external_message_round_trips_quote(
1905        #[case] encoding: SerializationEncoding,
1906        #[values(false, true)] with_data_endpoint: bool,
1907        #[values(false, true)] external_data_ingress: bool,
1908    ) {
1909        assert_quote_round_trips(encoding, with_data_endpoint, external_data_ingress);
1910    }
1911
1912    #[cfg(feature = "sbe")]
1913    #[rstest]
1914    fn republish_external_message_round_trips_quote_sbe(
1915        #[values(false, true)] with_data_endpoint: bool,
1916        #[values(false, true)] external_data_ingress: bool,
1917    ) {
1918        assert_quote_round_trips(
1919            SerializationEncoding::Sbe,
1920            with_data_endpoint,
1921            external_data_ingress,
1922        );
1923    }
1924
1925    fn assert_typed_external_round_trips<T>(
1926        encoding: SerializationEncoding,
1927        payload_type: BusPayloadType,
1928        topic: &str,
1929        value: T,
1930        publish: fn(MStr<Topic>, &T),
1931        subscribe: fn(MStr<Pattern>, TypedHandler<T>, Option<u32>),
1932        assert_received: impl Fn(&T, &T),
1933    ) where
1934        T: Clone + 'static,
1935    {
1936        let publications = install_capturing_external_egress(encoding);
1937
1938        publish(topic.into(), &value);
1939
1940        let bus_message = {
1941            let publications = publications.borrow();
1942            assert_eq!(publications.len(), 1);
1943            assert_eq!(publications[0].payload_type, payload_type);
1944            assert_eq!(publications[0].encoding, encoding);
1945            BusMessage::with_str_topic(
1946                publications[0].topic.clone(),
1947                publications[0].payload_type,
1948                publications[0].payload.clone(),
1949                publications[0].encoding,
1950            )
1951        };
1952        publications.borrow_mut().clear();
1953
1954        let received = Rc::new(RefCell::new(Vec::<T>::new()));
1955        let received_handler = received.clone();
1956        let handler = TypedHandler::from(move |message: &T| {
1957            received_handler.borrow_mut().push(message.clone());
1958        });
1959        subscribe(topic.into(), handler, None);
1960
1961        get_message_bus()
1962            .borrow_mut()
1963            .add_streaming_type(payload_type);
1964        republish_external_message(&bus_message).unwrap();
1965
1966        let received = received.borrow();
1967        assert_eq!(received.len(), 1);
1968        assert_received(&received[0], &value);
1969        assert!(
1970            publications.borrow().is_empty(),
1971            "republished message must not be forwarded back out externally"
1972        );
1973        reset_message_bus();
1974    }
1975
1976    #[rstest]
1977    #[case(SerializationEncoding::Json)]
1978    #[case(SerializationEncoding::MsgPack)]
1979    fn republish_external_account_state_routes_to_portfolio(
1980        #[case] encoding: SerializationEncoding,
1981    ) {
1982        let publications = install_capturing_external_egress(encoding);
1983        let state = nautilus_model::events::account::stubs::cash_account_state();
1984        publish_account_state("events.account.SIM-001".into(), &state);
1985        let captured = publications.borrow_mut().pop().unwrap();
1986        assert_eq!(captured.payload_type, BusPayloadType::AccountState);
1987        assert_eq!(captured.encoding, encoding);
1988        let message = BusMessage::with_str_topic(
1989            captured.topic,
1990            captured.payload_type,
1991            captured.payload,
1992            captured.encoding,
1993        );
1994        let applied = Rc::new(RefCell::new(Vec::new()));
1995        let handler = TypedHandler::from({
1996            let applied = Rc::clone(&applied);
1997            move |event: &AccountState| applied.borrow_mut().push(event.clone())
1998        });
1999        register_account_state_endpoint(MessagingSwitchboard::portfolio_update_account(), handler);
2000        let received = Rc::new(RefCell::new(Vec::new()));
2001        let subscriber = TypedHandler::from({
2002            let received = Rc::clone(&received);
2003            move |event: &AccountState| received.borrow_mut().push(event.clone())
2004        });
2005        subscribe_account_state("events.account.*".into(), subscriber, None);
2006        get_message_bus()
2007            .borrow_mut()
2008            .add_streaming_type(BusPayloadType::AccountState);
2009
2010        republish_external_message(&message).unwrap();
2011
2012        assert_eq!(*applied.borrow(), vec![state]);
2013        assert!(
2014            received.borrow().is_empty(),
2015            "Portfolio owns account publication"
2016        );
2017        assert!(publications.borrow().is_empty());
2018        reset_message_bus();
2019    }
2020
2021    fn assert_eq_ref<T>(actual: &T, expected: &T)
2022    where
2023        T: PartialEq + std::fmt::Debug,
2024    {
2025        assert_eq!(actual, expected);
2026    }
2027
2028    fn assert_json_value_eq<T>(actual: &T, expected: &T)
2029    where
2030        T: serde::Serialize,
2031    {
2032        assert_eq!(
2033            serde_json::to_value(actual).expect("actual value must serialize"),
2034            serde_json::to_value(expected).expect("expected value must serialize"),
2035        );
2036    }
2037
2038    fn assert_depth_market_eq(actual: &OrderBookDepth, expected: &OrderBookDepth) {
2039        assert_eq!(actual.instrument_id, expected.instrument_id);
2040        assert_eq!(actual.bid_counts, expected.bid_counts);
2041        assert_eq!(actual.ask_counts, expected.ask_counts);
2042        assert_eq!(actual.flags, expected.flags);
2043        assert_eq!(actual.sequence, expected.sequence);
2044        assert_eq!(actual.ts_event, expected.ts_event);
2045        assert_eq!(actual.ts_init, expected.ts_init);
2046
2047        for (actual, expected) in actual.bids.iter().zip(expected.bids.iter()) {
2048            assert_eq!(actual.side, expected.side);
2049            assert_eq!(actual.price, expected.price);
2050            assert_eq!(actual.size, expected.size);
2051        }
2052
2053        for (actual, expected) in actual.asks.iter().zip(expected.asks.iter()) {
2054            assert_eq!(actual.side, expected.side);
2055            assert_eq!(actual.price, expected.price);
2056            assert_eq!(actual.size, expected.size);
2057        }
2058    }
2059
2060    fn mark_price_update() -> MarkPriceUpdate {
2061        MarkPriceUpdate::new(
2062            InstrumentId::from("AUDUSD.SIM"),
2063            Price::from("1.00010"),
2064            UnixNanos::from(1),
2065            UnixNanos::from(2),
2066        )
2067    }
2068
2069    fn index_price_update() -> IndexPriceUpdate {
2070        IndexPriceUpdate::new(
2071            InstrumentId::from("AUDUSD.SIM"),
2072            Price::from("1.00020"),
2073            UnixNanos::from(3),
2074            UnixNanos::from(4),
2075        )
2076    }
2077
2078    fn funding_rate_update() -> FundingRateUpdate {
2079        FundingRateUpdate::new(
2080            InstrumentId::from("AUDUSD.SIM"),
2081            Decimal::new(1, 4),
2082            Some(480),
2083            Some(UnixNanos::from(5)),
2084            UnixNanos::from(6),
2085            UnixNanos::from(7),
2086        )
2087    }
2088
2089    #[cfg(feature = "sbe")]
2090    fn option_greeks() -> OptionGreeks {
2091        OptionGreeks {
2092            instrument_id: InstrumentId::from("BTC-30JUN23-40000-C.DERIBIT"),
2093            convention: GreeksConvention::PriceAdjusted,
2094            greeks: OptionGreekValues {
2095                delta: 0.525,
2096                gamma: 0.00032,
2097                vega: 12.25,
2098                theta: -0.72,
2099                rho: 0.18,
2100            },
2101            mark_iv: Some(0.0),
2102            bid_iv: None,
2103            ask_iv: Some(0.54),
2104            underlying_price: Some(41_500.25),
2105            open_interest: Some(0.0),
2106            ts_event: UnixNanos::from(20),
2107            ts_init: UnixNanos::from(21),
2108        }
2109    }
2110
2111    fn portfolio_snapshot() -> PortfolioSnapshot {
2112        PortfolioSnapshot::new(
2113            AccountId::from("SIM-001"),
2114            AccountType::Cash,
2115            Some(Currency::USD()),
2116            vec![],
2117            vec![],
2118            vec![],
2119            vec![],
2120            vec![],
2121            None,
2122            false,
2123            vec![],
2124            vec![],
2125            vec![],
2126            UUID4::new(),
2127            UnixNanos::from(8),
2128            UnixNanos::from(9),
2129        )
2130    }
2131
2132    fn position_event() -> PositionEvent {
2133        PositionEvent::PositionOpened(PositionOpened {
2134            trader_id: TraderId::from("TRADER-001"),
2135            strategy_id: StrategyId::from("S-001"),
2136            instrument_id: InstrumentId::from("AUDUSD.SIM"),
2137            position_id: PositionId::from("P-001"),
2138            account_id: AccountId::from("SIM-001"),
2139            opening_order_id: ClientOrderId::from("O-19700101-000000-001-001-1"),
2140            entry: OrderSide::Buy,
2141            side: PositionSide::Long,
2142            signed_qty: 100.into(),
2143            quantity: Quantity::from("100"),
2144            last_qty: Quantity::from("100"),
2145            last_px: Price::from("1.00000"),
2146            currency: Currency::USD(),
2147            avg_px_open: 1.into(),
2148            realized_pnl: None,
2149            event_id: UUID4::new(),
2150            ts_event: UnixNanos::from(10),
2151            ts_init: UnixNanos::from(11),
2152        })
2153    }
2154
2155    #[cfg(feature = "defi")]
2156    fn defi_chain() -> Arc<Chain> {
2157        Arc::new(
2158            Chain::from_chain_id(42161)
2159                .expect("Arbitrum chain must be registered")
2160                .clone(),
2161        )
2162    }
2163
2164    #[cfg(feature = "defi")]
2165    fn defi_dex() -> Arc<Dex> {
2166        let chain = Chain::from_chain_id(42161)
2167            .expect("Arbitrum chain must be registered")
2168            .clone();
2169        Arc::new(Dex::new(
2170            chain,
2171            DexType::UniswapV3,
2172            "0x1F98431c8aD98523631AE4a59f267346ea31F984",
2173            0,
2174            AmmType::CLAMM,
2175            "PoolCreated",
2176            "Swap",
2177            "Mint",
2178            "Burn",
2179            "Collect",
2180        ))
2181    }
2182
2183    #[cfg(feature = "defi")]
2184    fn defi_pool() -> Pool {
2185        let chain = defi_chain();
2186        let dex = defi_dex();
2187        let rain = Token::new(
2188            chain.clone(),
2189            address!("0x25118290e6A5f4139381D072181157035864099d"),
2190            "RAIN".to_string(),
2191            "RAIN".to_string(),
2192            18,
2193        );
2194        let weth = Token::new(
2195            chain.clone(),
2196            address!("0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"),
2197            "Wrapped Ether".to_string(),
2198            "WETH".to_string(),
2199            18,
2200        );
2201        let pool_address = address!("0xd13040d4fe917EE704158CfCB3338dCd2838B245");
2202
2203        Pool::new(
2204            chain,
2205            dex,
2206            pool_address,
2207            PoolIdentifier::from_address(pool_address),
2208            0,
2209            rain,
2210            weth,
2211            Some(3000),
2212            Some(60),
2213            UnixNanos::from(12),
2214        )
2215    }
2216
2217    #[cfg(feature = "defi")]
2218    fn defi_block() -> Block {
2219        Block::new(
2220            "0x0000000000000000000000000000000000000000000000000000000000000100".to_string(),
2221            "0x0000000000000000000000000000000000000000000000000000000000000099".to_string(),
2222            100,
2223            Ustr::from("0x0000000000000000000000000000000000000001"),
2224            30_000_000,
2225            21_000,
2226            UnixNanos::from(13),
2227            None,
2228        )
2229    }
2230
2231    #[cfg(feature = "defi")]
2232    fn defi_transaction_hash() -> String {
2233        "0x1aa3506e78dd6e7e53986fa310c7ef1b7825042e19693c04eb56b2404067407b".to_string()
2234    }
2235
2236    #[cfg(feature = "defi")]
2237    fn defi_liquidity_update() -> PoolLiquidityUpdate {
2238        let pool = defi_pool();
2239        PoolLiquidityUpdate::new(
2240            pool.chain.clone(),
2241            pool.dex.clone(),
2242            pool.instrument_id,
2243            pool.pool_identifier,
2244            PoolLiquidityUpdateType::Mint,
2245            100_000,
2246            defi_transaction_hash(),
2247            0,
2248            1,
2249            None,
2250            address!("0x5E325eDA8064b456f4781070C0738d849c824258"),
2251            100,
2252            U256::from(10),
2253            U256::from(20),
2254            -120,
2255            120,
2256            UnixNanos::from(14),
2257            UnixNanos::from(15),
2258        )
2259    }
2260
2261    #[cfg(feature = "defi")]
2262    fn defi_collect() -> PoolFeeCollect {
2263        let pool = defi_pool();
2264        PoolFeeCollect::new(
2265            pool.chain.clone(),
2266            pool.dex.clone(),
2267            pool.instrument_id,
2268            pool.pool_identifier,
2269            100_000,
2270            defi_transaction_hash(),
2271            0,
2272            2,
2273            address!("0x5E325eDA8064b456f4781070C0738d849c824258"),
2274            10,
2275            20,
2276            -120,
2277            120,
2278            UnixNanos::from(16),
2279            UnixNanos::from(17),
2280        )
2281    }
2282
2283    #[cfg(feature = "defi")]
2284    fn defi_flash() -> PoolFlash {
2285        let pool = defi_pool();
2286        PoolFlash::new(
2287            pool.chain.clone(),
2288            pool.dex.clone(),
2289            pool.instrument_id,
2290            pool.pool_identifier,
2291            100_000,
2292            defi_transaction_hash(),
2293            0,
2294            3,
2295            UnixNanos::from(18),
2296            UnixNanos::from(19),
2297            address!("0x1aa3506e78dd6e7e53986fa310c7ef1b7825042e"),
2298            address!("0x1aa3506e78dd6e7e53986fa310c7ef1b7825042e"),
2299            U256::from(100),
2300            U256::from(200),
2301            U256::from(101),
2302            U256::from(202),
2303        )
2304    }
2305
2306    fn assert_publishable_json_msgpack_round_trips(encoding: SerializationEncoding) {
2307        assert_typed_external_round_trips(
2308            encoding,
2309            BusPayloadType::Instrument,
2310            "data.instruments.AUDUSD.SIM",
2311            InstrumentAny::CurrencyPair(audusd_sim()),
2312            publish_instrument,
2313            subscribe_instruments,
2314            assert_json_value_eq,
2315        );
2316        assert_typed_external_round_trips(
2317            encoding,
2318            BusPayloadType::OrderBookDeltas,
2319            "data.book.deltas.AAPL.XNAS",
2320            stub_deltas(),
2321            publish_deltas,
2322            subscribe_book_deltas,
2323            assert_eq_ref,
2324        );
2325        assert_typed_external_round_trips(
2326            encoding,
2327            BusPayloadType::OrderBookDepth,
2328            "data.book.depth.AAPL.XNAS",
2329            stub_depth10(),
2330            publish_depth,
2331            subscribe_book_depth,
2332            assert_depth_market_eq,
2333        );
2334        assert_typed_external_round_trips(
2335            encoding,
2336            BusPayloadType::TradeTick,
2337            "data.trades.AUDUSD.SIM",
2338            TradeTick::default(),
2339            publish_trade,
2340            subscribe_trades,
2341            assert_eq_ref,
2342        );
2343        assert_typed_external_round_trips(
2344            encoding,
2345            BusPayloadType::Bar,
2346            "data.bars.AUDUSD.SIM",
2347            Bar::default(),
2348            publish_bar,
2349            subscribe_bars,
2350            assert_eq_ref,
2351        );
2352        assert_typed_external_round_trips(
2353            encoding,
2354            BusPayloadType::MarkPriceUpdate,
2355            "data.mark_prices.AUDUSD.SIM",
2356            mark_price_update(),
2357            publish_mark_price,
2358            subscribe_mark_prices,
2359            assert_eq_ref,
2360        );
2361        assert_typed_external_round_trips(
2362            encoding,
2363            BusPayloadType::IndexPriceUpdate,
2364            "data.index_prices.AUDUSD.SIM",
2365            index_price_update(),
2366            publish_index_price,
2367            subscribe_index_prices,
2368            assert_eq_ref,
2369        );
2370        assert_typed_external_round_trips(
2371            encoding,
2372            BusPayloadType::FundingRateUpdate,
2373            "data.funding_rates.AUDUSD.SIM",
2374            funding_rate_update(),
2375            publish_funding_rate,
2376            subscribe_funding_rates,
2377            assert_eq_ref,
2378        );
2379        assert_typed_external_round_trips(
2380            encoding,
2381            BusPayloadType::OptionGreeks,
2382            "data.option_greeks.AUDUSD.SIM",
2383            OptionGreeks::default(),
2384            publish_option_greeks,
2385            subscribe_option_greeks,
2386            assert_eq_ref,
2387        );
2388        assert_typed_external_round_trips(
2389            encoding,
2390            BusPayloadType::PortfolioSnapshot,
2391            "events.portfolio.SIM-001",
2392            portfolio_snapshot(),
2393            publish_portfolio_snapshot,
2394            subscribe_portfolio_snapshot,
2395            assert_eq_ref,
2396        );
2397        assert_typed_external_round_trips(
2398            encoding,
2399            BusPayloadType::OrderEvent,
2400            "events.orders.SIM-001",
2401            OrderEventAny::Denied(OrderDeniedSpec::builder().build()),
2402            publish_order_event,
2403            subscribe_order_events,
2404            assert_eq_ref,
2405        );
2406        assert_typed_external_round_trips(
2407            encoding,
2408            BusPayloadType::PositionEvent,
2409            "events.positions.SIM-001",
2410            position_event(),
2411            publish_position_event,
2412            subscribe_position_events,
2413            assert_json_value_eq,
2414        );
2415    }
2416
2417    #[cfg(feature = "defi")]
2418    fn assert_publishable_defi_json_msgpack_round_trips(encoding: SerializationEncoding) {
2419        assert_typed_external_round_trips(
2420            encoding,
2421            BusPayloadType::Block,
2422            "data.defi.blocks.ARBITRUM",
2423            defi_block(),
2424            publish_defi_block,
2425            subscribe_defi_blocks,
2426            assert_json_value_eq,
2427        );
2428        assert_typed_external_round_trips(
2429            encoding,
2430            BusPayloadType::Pool,
2431            "data.defi.pools.RAIN-WETH",
2432            defi_pool(),
2433            publish_defi_pool,
2434            subscribe_defi_pools,
2435            assert_json_value_eq,
2436        );
2437        assert_typed_external_round_trips(
2438            encoding,
2439            BusPayloadType::PoolLiquidityUpdate,
2440            "data.defi.liquidity.RAIN-WETH",
2441            defi_liquidity_update(),
2442            publish_defi_liquidity,
2443            subscribe_defi_liquidity,
2444            assert_json_value_eq,
2445        );
2446        assert_typed_external_round_trips(
2447            encoding,
2448            BusPayloadType::PoolFeeCollect,
2449            "data.defi.collects.RAIN-WETH",
2450            defi_collect(),
2451            publish_defi_collect,
2452            subscribe_defi_collects,
2453            assert_json_value_eq,
2454        );
2455        assert_typed_external_round_trips(
2456            encoding,
2457            BusPayloadType::PoolFlash,
2458            "data.defi.flash.RAIN-WETH",
2459            defi_flash(),
2460            publish_defi_flash,
2461            subscribe_defi_flash,
2462            assert_json_value_eq,
2463        );
2464    }
2465
2466    #[rstest]
2467    #[case(SerializationEncoding::Json)]
2468    #[case(SerializationEncoding::MsgPack)]
2469    fn republish_external_message_round_trips_publishable_payloads(
2470        #[case] encoding: SerializationEncoding,
2471    ) {
2472        assert_publishable_json_msgpack_round_trips(encoding);
2473    }
2474
2475    #[cfg(feature = "defi")]
2476    #[rstest]
2477    #[case(SerializationEncoding::Json)]
2478    #[case(SerializationEncoding::MsgPack)]
2479    fn republish_external_message_round_trips_publishable_defi_payloads(
2480        #[case] encoding: SerializationEncoding,
2481    ) {
2482        assert_publishable_defi_json_msgpack_round_trips(encoding);
2483    }
2484
2485    fn assert_custom_data_round_trips(encoding: SerializationEncoding) {
2486        let publications = install_capturing_external_egress(encoding);
2487        let custom = stub_custom_data(100, 42, None, Some("stub-id".to_string()));
2488
2489        publish_any("data.custom.StubCustomData".into(), &custom);
2490
2491        let bus_message = {
2492            let publications = publications.borrow();
2493            assert_eq!(publications.len(), 1);
2494            assert_eq!(
2495                publications[0].payload_type,
2496                BusPayloadType::Custom(Ustr::from("StubCustomData"))
2497            );
2498            assert_eq!(publications[0].encoding, encoding);
2499            BusMessage::with_str_topic(
2500                publications[0].topic.clone(),
2501                publications[0].payload_type,
2502                publications[0].payload.clone(),
2503                publications[0].encoding,
2504            )
2505        };
2506        publications.borrow_mut().clear();
2507
2508        let received = Rc::new(RefCell::new(Vec::<CustomData>::new()));
2509        let received_handler = received.clone();
2510        subscribe_any(
2511            "data.custom.StubCustomData".into(),
2512            ShareableMessageHandler::from_typed(move |message: &CustomData| {
2513                received_handler.borrow_mut().push(message.clone());
2514            }),
2515            None,
2516        );
2517
2518        get_message_bus()
2519            .borrow_mut()
2520            .add_streaming_type(BusPayloadType::Custom(Ustr::from("StubCustomData")));
2521        republish_external_message(&bus_message).unwrap();
2522
2523        assert_eq!(*received.borrow(), vec![custom]);
2524        assert!(
2525            publications.borrow().is_empty(),
2526            "republished message must not be forwarded back out externally"
2527        );
2528        reset_message_bus();
2529    }
2530
2531    fn assert_typed_payload_round_trips<T>(
2532        encoding: SerializationEncoding,
2533        payload_type: BusPayloadType,
2534        topic: &str,
2535        value: T,
2536    ) where
2537        T: serde::Serialize + Any + 'static,
2538    {
2539        let publications = install_capturing_external_stream_egress(encoding);
2540        let expected = serde_json::to_value(&value).expect("typed payload must map to JSON");
2541        let received = Rc::new(RefCell::new(Vec::<serde_json::Value>::new()));
2542        let received_handler = received.clone();
2543        subscribe_any(
2544            topic.into(),
2545            ShareableMessageHandler::from_typed(move |message: &T| {
2546                received_handler.borrow_mut().push(
2547                    serde_json::to_value(message).expect("received payload must map to JSON"),
2548                );
2549            }),
2550            None,
2551        );
2552
2553        publish_any(topic.into(), &value);
2554
2555        let bus_message = {
2556            let publications = publications.borrow();
2557            assert_eq!(publications.len(), 1);
2558            assert_eq!(publications[0].topic, topic);
2559            assert_eq!(publications[0].payload_type, payload_type);
2560            assert_eq!(publications[0].encoding, encoding);
2561            BusMessage::with_str_topic(
2562                topic,
2563                publications[0].payload_type,
2564                publications[0].payload.clone(),
2565                publications[0].encoding,
2566            )
2567        };
2568        received.borrow_mut().clear();
2569        get_message_bus()
2570            .borrow_mut()
2571            .add_streaming_type(payload_type);
2572
2573        republish_external_message(&bus_message).expect("typed payload must republish");
2574
2575        assert_eq!(*received.borrow(), vec![expected]);
2576        assert_eq!(
2577            publications.borrow().len(),
2578            1,
2579            "republished typed payload must not echo to external egress"
2580        );
2581        reset_message_bus();
2582    }
2583
2584    fn typed_processor_mapping<T>(
2585        payload_type: BusPayloadType,
2586        topic: &str,
2587        value: &T,
2588    ) -> serde_json::Value
2589    where
2590        T: serde::Serialize,
2591    {
2592        let message = BusMessage::with_str_topic(
2593            topic,
2594            payload_type,
2595            Bytes::from(serde_json::to_vec(value).expect("typed payload must serialize")),
2596            SerializationEncoding::Json,
2597        );
2598        let mut received = None;
2599        let mut processor = |_: &dyn Any, mapping: &serde_json::Value| {
2600            received = Some(mapping.clone());
2601            Ok(())
2602        };
2603
2604        process_external_typed_message(&message, &mut processor)
2605            .expect("typed payload must process");
2606
2607        received.expect("processor must receive the typed mapping")
2608    }
2609
2610    #[rstest]
2611    fn typed_processor_mapping_identifies_subscription_action() {
2612        let instrument_id = InstrumentId::from("AUD/USD.SIM");
2613        let client_id = Some(ClientId::from("EXTERNAL"));
2614        let venue = Some(Venue::from("SIM"));
2615        let ts_init = UnixNanos::from(1_000_000_000);
2616        let subscribe = SubscribeCommand::Quotes(SubscribeQuotes::new(
2617            instrument_id,
2618            client_id,
2619            venue,
2620            UUID4::from("00000000-0000-4000-8000-000000000001"),
2621            ts_init,
2622            None,
2623            None,
2624        ));
2625        let unsubscribe = UnsubscribeCommand::Quotes(UnsubscribeQuotes::new(
2626            instrument_id,
2627            client_id,
2628            venue,
2629            UUID4::from("00000000-0000-4000-8000-000000000002"),
2630            ts_init,
2631            None,
2632            None,
2633        ));
2634
2635        let mut subscribe_mapping = typed_processor_mapping(
2636            BusPayloadType::SubscribeCommand,
2637            "external.test",
2638            &subscribe,
2639        );
2640        let mut unsubscribe_mapping = typed_processor_mapping(
2641            BusPayloadType::UnsubscribeCommand,
2642            "external.test",
2643            &unsubscribe,
2644        );
2645
2646        assert_eq!(
2647            subscribe_mapping
2648                .as_object_mut()
2649                .expect("subscribe payload must map to an object")
2650                .remove("payload_type"),
2651            Some(serde_json::json!("SubscribeCommand"))
2652        );
2653        assert_eq!(
2654            unsubscribe_mapping
2655                .as_object_mut()
2656                .expect("unsubscribe payload must map to an object")
2657                .remove("payload_type"),
2658            Some(serde_json::json!("UnsubscribeCommand"))
2659        );
2660        assert_eq!(
2661            subscribe_mapping,
2662            serde_json::to_value(subscribe).expect("subscribe command must map to JSON")
2663        );
2664        assert_eq!(
2665            unsubscribe_mapping,
2666            serde_json::to_value(unsubscribe).expect("unsubscribe command must map to JSON")
2667        );
2668        reset_message_bus();
2669    }
2670
2671    #[rstest]
2672    fn typed_processor_publications_do_not_echo_to_external_egress() {
2673        let publications = install_capturing_external_stream_egress(SerializationEncoding::Json);
2674        let command = SubscribeCommand::Quotes(SubscribeQuotes::new(
2675            InstrumentId::from("AUD/USD.SIM"),
2676            Some(ClientId::from("EXTERNAL")),
2677            Some(Venue::from("SIM")),
2678            UUID4::from("00000000-0000-4000-8000-000000000001"),
2679            UnixNanos::from(1_000_000_000),
2680            None,
2681            None,
2682        ));
2683
2684        publish_any("external.test".into(), &command);
2685        let message = {
2686            let publications = publications.borrow();
2687            assert_eq!(publications.len(), 1);
2688            BusMessage::with_str_topic(
2689                publications[0].topic.clone(),
2690                publications[0].payload_type,
2691                publications[0].payload.clone(),
2692                publications[0].encoding,
2693            )
2694        };
2695        let mut processor = |value: &dyn Any, _: &serde_json::Value| {
2696            let command = value
2697                .downcast_ref::<SubscribeCommand>()
2698                .expect("processor must receive a subscribe command");
2699            publish_any("external.test".into(), command);
2700            Ok(())
2701        };
2702
2703        process_external_typed_message(&message, &mut processor)
2704            .expect("typed payload must process");
2705        assert_eq!(
2706            publications.borrow().len(),
2707            1,
2708            "processor publication must remain local"
2709        );
2710
2711        publish_any("external.test".into(), &command);
2712        assert_eq!(
2713            publications.borrow().len(),
2714            2,
2715            "external egress must resume after processing"
2716        );
2717        reset_message_bus();
2718    }
2719
2720    #[rstest]
2721    fn typed_processor_error_skips_internal_republishing() {
2722        let command = SubscribeCommand::Quotes(SubscribeQuotes::new(
2723            InstrumentId::from("AUD/USD.SIM"),
2724            Some(ClientId::from("EXTERNAL")),
2725            Some(Venue::from("SIM")),
2726            UUID4::from("00000000-0000-4000-8000-000000000001"),
2727            UnixNanos::from(1_000_000_000),
2728            None,
2729            None,
2730        ));
2731        let received = Rc::new(RefCell::new(Vec::new()));
2732        let received_handler = received.clone();
2733        subscribe_any(
2734            "external.test".into(),
2735            ShareableMessageHandler::from_typed(move |command: &SubscribeCommand| {
2736                received_handler.borrow_mut().push(command.clone());
2737            }),
2738            None,
2739        );
2740        get_message_bus()
2741            .borrow_mut()
2742            .add_streaming_type(BusPayloadType::SubscribeCommand);
2743        let message = BusMessage::with_str_topic(
2744            "external.test",
2745            BusPayloadType::SubscribeCommand,
2746            Bytes::from(serde_json::to_vec(&command).expect("typed payload must serialize")),
2747            SerializationEncoding::Json,
2748        );
2749        let mut processor =
2750            |_: &dyn Any, _: &serde_json::Value| anyhow::bail!("processor rejected payload");
2751
2752        let error = process_external_typed_message(&message, &mut processor)
2753            .expect_err("processor failure must stop processing");
2754
2755        assert_eq!(error.to_string(), "processor rejected payload");
2756        assert!(received.borrow().is_empty());
2757        reset_message_bus();
2758    }
2759
2760    #[rstest]
2761    #[case(SerializationEncoding::Json)]
2762    #[case(SerializationEncoding::MsgPack)]
2763    fn typed_payloads_round_trip_supported_encodings(#[case] encoding: SerializationEncoding) {
2764        let trader_id = TraderId::from("TRADER-001");
2765        let client_id = ClientId::from("EXTERNAL");
2766        let venue = Venue::from("SIM");
2767        let instrument_id = InstrumentId::from("AUD/USD.SIM");
2768        let account_id = AccountId::from("SIM-001");
2769        let venue_order_id = VenueOrderId::from("ORDER-001");
2770        let ts_init = UnixNanos::from(1_000_000_000);
2771
2772        assert_typed_payload_round_trips(
2773            encoding,
2774            BusPayloadType::SubscribeCommand,
2775            "external.test",
2776            SubscribeCommand::Quotes(SubscribeQuotes::new(
2777                instrument_id,
2778                Some(client_id),
2779                Some(venue),
2780                UUID4::from("00000000-0000-4000-8000-000000000001"),
2781                ts_init,
2782                None,
2783                None,
2784            )),
2785        );
2786        assert_typed_payload_round_trips(
2787            encoding,
2788            BusPayloadType::UnsubscribeCommand,
2789            "external.test",
2790            UnsubscribeCommand::Quotes(UnsubscribeQuotes::new(
2791                instrument_id,
2792                Some(client_id),
2793                Some(venue),
2794                UUID4::from("00000000-0000-4000-8000-000000000002"),
2795                ts_init,
2796                None,
2797                None,
2798            )),
2799        );
2800        assert_typed_payload_round_trips(
2801            encoding,
2802            BusPayloadType::TradingCommand,
2803            "external.test",
2804            TradingCommand::CancelAllOrders(CancelAllOrders::new(
2805                trader_id,
2806                Some(client_id),
2807                StrategyId::from("STRATEGY-001"),
2808                instrument_id,
2809                Some(OrderSide::Buy),
2810                UUID4::from("00000000-0000-4000-8000-000000000003"),
2811                ts_init,
2812                None,
2813                Some(UUID4::from("00000000-0000-4000-8000-000000000004")),
2814            )),
2815        );
2816        assert_typed_payload_round_trips(
2817            encoding,
2818            BusPayloadType::GenerateExecutionMassStatus,
2819            "external.test",
2820            GenerateExecutionMassStatus::new(
2821                trader_id,
2822                client_id,
2823                Some(venue),
2824                UUID4::from("00000000-0000-4000-8000-000000000005"),
2825                ts_init,
2826                None,
2827                Some(UUID4::from("00000000-0000-4000-8000-000000000006")),
2828            ),
2829        );
2830
2831        let order_report = OrderStatusReport::new(
2832            account_id,
2833            instrument_id,
2834            Some(ClientOrderId::from("O-001")),
2835            venue_order_id,
2836            Some(OrderSide::Buy),
2837            OrderType::Limit,
2838            TimeInForce::Gtc,
2839            OrderStatus::Accepted,
2840            Quantity::from("10"),
2841            Quantity::from("2"),
2842            UnixNanos::from(1_000_000_001),
2843            UnixNanos::from(1_000_000_002),
2844            UnixNanos::from(1_000_000_003),
2845            Some(UUID4::from("00000000-0000-4000-8000-000000000007")),
2846        );
2847        let fill_report = FillReport::new(
2848            account_id,
2849            instrument_id,
2850            venue_order_id,
2851            TradeId::from("TRADE-001"),
2852            OrderSide::Buy,
2853            Quantity::from("2"),
2854            Price::from("1.25"),
2855            Money::from("0.10 USD"),
2856            LiquiditySide::Maker,
2857            Some(ClientOrderId::from("O-001")),
2858            Some(PositionId::from("P-001")),
2859            UnixNanos::from(1_000_000_004),
2860            UnixNanos::from(1_000_000_005),
2861            Some(UUID4::from("00000000-0000-4000-8000-000000000008")),
2862        );
2863        let position_report = PositionStatusReport::new(
2864            account_id,
2865            instrument_id,
2866            PositionSide::Long,
2867            Quantity::from("2"),
2868            UnixNanos::from(1_000_000_006),
2869            UnixNanos::from(1_000_000_007),
2870            Some(UUID4::from("00000000-0000-4000-8000-000000000009")),
2871            Some(PositionId::from("P-001")),
2872            Some(Decimal::new(125, 2)),
2873        );
2874
2875        assert_typed_payload_round_trips(
2876            encoding,
2877            BusPayloadType::OrderStatusReport,
2878            "external.test",
2879            order_report.clone(),
2880        );
2881        assert_typed_payload_round_trips(
2882            encoding,
2883            BusPayloadType::FillReport,
2884            "external.test",
2885            fill_report.clone(),
2886        );
2887        assert_typed_payload_round_trips(
2888            encoding,
2889            BusPayloadType::PositionStatusReport,
2890            "external.test",
2891            position_report.clone(),
2892        );
2893
2894        let mut mass_status = ExecutionMassStatus::new(
2895            client_id,
2896            account_id,
2897            venue,
2898            UnixNanos::from(1_000_000_008),
2899            Some(UUID4::from("00000000-0000-4000-8000-000000000010")),
2900        );
2901        mass_status.add_order_reports(vec![order_report]);
2902        mass_status.add_fill_reports(vec![fill_report]);
2903        mass_status.add_position_reports(vec![position_report]);
2904        assert_typed_payload_round_trips(
2905            encoding,
2906            BusPayloadType::ExecutionMassStatus,
2907            "external.test",
2908            mass_status,
2909        );
2910    }
2911
2912    #[rstest]
2913    #[case(SerializationEncoding::Json)]
2914    #[case(SerializationEncoding::MsgPack)]
2915    fn republish_external_message_round_trips_custom_data(#[case] encoding: SerializationEncoding) {
2916        assert_custom_data_round_trips(encoding);
2917    }
2918
2919    #[rstest]
2920    #[case(SerializationEncoding::Json)]
2921    #[case(SerializationEncoding::MsgPack)]
2922    fn republish_external_message_rejects_reserved_custom_metadata(
2923        #[case] encoding: SerializationEncoding,
2924    ) {
2925        let custom = stub_custom_data(317, 42, None, Some("catalog/317".to_string()));
2926        let mut envelope = serde_json::to_value(custom).unwrap();
2927        envelope["data_type"]["metadata"]["identifier"] = serde_json::json!("shadow");
2928        let payload = match encoding {
2929            SerializationEncoding::Json => serde_json::to_vec(&envelope).unwrap(),
2930            SerializationEncoding::MsgPack => rmp_serde::to_vec_named(&envelope).unwrap(),
2931            SerializationEncoding::Sbe => unreachable!("custom payloads require JSON or MsgPack"),
2932        };
2933
2934        let payload_type = BusPayloadType::Custom(Ustr::from("StubCustomData"));
2935        let message = BusMessage::with_str_topic(
2936            "data.custom.StubCustomData",
2937            payload_type,
2938            Bytes::from(payload),
2939            encoding,
2940        );
2941        let received = Rc::new(RefCell::new(Vec::<CustomData>::new()));
2942        let received_handler = received.clone();
2943        subscribe_any(
2944            "data.custom.StubCustomData".into(),
2945            ShareableMessageHandler::from_typed(move |value: &CustomData| {
2946                received_handler.borrow_mut().push(value.clone());
2947            }),
2948            None,
2949        );
2950
2951        republish_external_message(&message).unwrap();
2952        get_message_bus()
2953            .borrow_mut()
2954            .add_streaming_type(payload_type);
2955        let error = republish_external_message(&message).unwrap_err();
2956
2957        assert_eq!(
2958            error.root_cause().to_string(),
2959            "`identifier` is reserved for DataType catalog identity"
2960        );
2961        assert!(received.borrow().is_empty());
2962        reset_message_bus();
2963    }
2964
2965    #[rstest]
2966    #[case(SerializationEncoding::Json)]
2967    #[case(SerializationEncoding::MsgPack)]
2968    fn typed_processor_rejects_reserved_nested_custom_metadata(
2969        #[case] encoding: SerializationEncoding,
2970        #[values(false, true)] batch: bool,
2971    ) {
2972        let custom = stub_custom_data(317, 42, None, Some("catalog/317".to_string()));
2973
2974        let data: Arc<dyn Any + Send + Sync> = if batch {
2975            Arc::new(vec![custom.clone()])
2976        } else {
2977            Arc::new(custom.clone())
2978        };
2979
2980        let response = DataResponse::Data(CustomDataResponse {
2981            correlation_id: UUID4::new(),
2982            client_id: ClientId::from("CLIENT-001"),
2983            venue: Some(Venue::from("SIM")),
2984            data_type: custom.data_type,
2985            data,
2986            start: Some(UnixNanos::from(301)),
2987            end: Some(UnixNanos::from(313)),
2988            ts_init: UnixNanos::from(319),
2989            params: None,
2990        });
2991
2992        let mut envelope = serde_json::to_value(response).unwrap();
2993        let item = if batch {
2994            &mut envelope["Data"]["data"]["Batch"][0]
2995        } else {
2996            &mut envelope["Data"]["data"]["Scalar"]
2997        };
2998
2999        item["value"]["data_type"]["metadata"]["identifier"] = serde_json::Value::Null;
3000
3001        let payload = match encoding {
3002            SerializationEncoding::Json => serde_json::to_vec(&envelope).unwrap(),
3003            SerializationEncoding::MsgPack => rmp_serde::to_vec_named(&envelope).unwrap(),
3004            SerializationEncoding::Sbe => unreachable!("custom payloads require JSON or MsgPack"),
3005        };
3006
3007        let message = BusMessage::with_str_topic(
3008            "data.responses",
3009            BusPayloadType::DataResponse,
3010            Bytes::from(payload),
3011            encoding,
3012        );
3013        let mut processed = false;
3014        let error = process_external_typed_message(&message, &mut |_, _| {
3015            processed = true;
3016            Ok(())
3017        })
3018        .unwrap_err();
3019
3020        assert!(
3021            error
3022                .root_cause()
3023                .to_string()
3024                .contains("`identifier` is reserved for DataType catalog identity")
3025        );
3026        assert!(!processed);
3027        reset_message_bus();
3028    }
3029
3030    #[rstest]
3031    #[case(SerializationEncoding::Json)]
3032    #[case(SerializationEncoding::MsgPack)]
3033    fn republish_external_message_skips_unregistered_custom_payload(
3034        #[case] encoding: SerializationEncoding,
3035    ) {
3036        let envelope = serde_json::json!({
3037            "type": "UnregisteredCustomData",
3038            "data_type": {
3039                "type_name": "UnregisteredCustomData",
3040                "metadata": {"identifier": "shadow"},
3041            },
3042            "payload": {
3043                "value": 1,
3044            },
3045        });
3046        let payload = match encoding {
3047            SerializationEncoding::Json => {
3048                serde_json::to_vec(&envelope).expect("JSON envelope must serialize")
3049            }
3050            SerializationEncoding::MsgPack => {
3051                rmp_serde::to_vec_named(&envelope).expect("MsgPack envelope must serialize")
3052            }
3053            SerializationEncoding::Sbe => {
3054                unreachable!("schema encodings do not support custom payloads")
3055            }
3056        };
3057        let message = BusMessage::with_str_topic(
3058            "data.custom.UnregisteredCustomData",
3059            BusPayloadType::Custom(Ustr::from("UnregisteredCustomData")),
3060            Bytes::from(payload),
3061            encoding,
3062        );
3063
3064        get_message_bus()
3065            .borrow_mut()
3066            .add_streaming_type(BusPayloadType::Custom(Ustr::from("UnregisteredCustomData")));
3067        republish_external_message(&message).unwrap();
3068        reset_message_bus();
3069    }
3070
3071    #[rstest]
3072    fn republish_external_message_skips_untyped_custom_payload() {
3073        let message = BusMessage::with_str_topic(
3074            "events/control",
3075            BusPayloadType::Custom(Ustr::default()),
3076            Bytes::new(),
3077            SerializationEncoding::Json,
3078        );
3079
3080        republish_external_message(&message).unwrap();
3081        reset_message_bus();
3082    }
3083
3084    #[rstest]
3085    fn republish_external_message_skips_unregistered_streaming_type_before_decode() {
3086        let received = Rc::new(RefCell::new(Vec::<QuoteTick>::new()));
3087        let received_handler = received.clone();
3088        let handler = TypedHandler::from(move |quote: &QuoteTick| {
3089            received_handler.borrow_mut().push(*quote);
3090        });
3091        subscribe_quotes("data.quotes.*".into(), handler, None);
3092
3093        let message = BusMessage::with_str_topic(
3094            "data.quotes.AUDUSD.SIM",
3095            BusPayloadType::QuoteTick,
3096            Bytes::from_static(b"not-json"),
3097            SerializationEncoding::Json,
3098        );
3099
3100        republish_external_message(&message).unwrap();
3101
3102        assert!(received.borrow().is_empty());
3103        reset_message_bus();
3104    }
3105
3106    #[cfg(feature = "sbe")]
3107    fn assert_market_data_binary_round_trips(encoding: SerializationEncoding) {
3108        assert_typed_external_round_trips(
3109            encoding,
3110            BusPayloadType::OrderBookDeltas,
3111            "data.book.deltas.AAPL.XNAS",
3112            stub_deltas(),
3113            publish_deltas,
3114            subscribe_book_deltas,
3115            assert_eq_ref,
3116        );
3117        assert_typed_external_round_trips(
3118            encoding,
3119            BusPayloadType::OrderBookDepth,
3120            "data.book.depth.AAPL.XNAS",
3121            stub_depth10(),
3122            publish_depth,
3123            subscribe_book_depth,
3124            assert_depth_market_eq,
3125        );
3126        assert_typed_external_round_trips(
3127            encoding,
3128            BusPayloadType::QuoteTick,
3129            "data.quotes.AUDUSD.SIM",
3130            QuoteTick::default(),
3131            publish_quote,
3132            subscribe_quotes,
3133            assert_eq_ref,
3134        );
3135        assert_typed_external_round_trips(
3136            encoding,
3137            BusPayloadType::TradeTick,
3138            "data.trades.AUDUSD.SIM",
3139            TradeTick::default(),
3140            publish_trade,
3141            subscribe_trades,
3142            assert_eq_ref,
3143        );
3144        assert_typed_external_round_trips(
3145            encoding,
3146            BusPayloadType::Bar,
3147            "data.bars.AUDUSD.SIM",
3148            Bar::default(),
3149            publish_bar,
3150            subscribe_bars,
3151            assert_eq_ref,
3152        );
3153        assert_typed_external_round_trips(
3154            encoding,
3155            BusPayloadType::MarkPriceUpdate,
3156            "data.mark_prices.AUDUSD.SIM",
3157            mark_price_update(),
3158            publish_mark_price,
3159            subscribe_mark_prices,
3160            assert_eq_ref,
3161        );
3162        assert_typed_external_round_trips(
3163            encoding,
3164            BusPayloadType::IndexPriceUpdate,
3165            "data.index_prices.AUDUSD.SIM",
3166            index_price_update(),
3167            publish_index_price,
3168            subscribe_index_prices,
3169            assert_eq_ref,
3170        );
3171        assert_typed_external_round_trips(
3172            encoding,
3173            BusPayloadType::FundingRateUpdate,
3174            "data.funding_rates.AUDUSD.SIM",
3175            funding_rate_update(),
3176            publish_funding_rate,
3177            subscribe_funding_rates,
3178            assert_eq_ref,
3179        );
3180        assert_typed_external_round_trips(
3181            encoding,
3182            BusPayloadType::OptionGreeks,
3183            "data.option_greeks.BTC-30JUN23-40000-C.DERIBIT",
3184            option_greeks(),
3185            publish_option_greeks,
3186            subscribe_option_greeks,
3187            assert_eq_ref,
3188        );
3189    }
3190
3191    #[cfg(feature = "sbe")]
3192    #[rstest]
3193    fn republish_external_message_round_trips_market_data_sbe() {
3194        assert_market_data_binary_round_trips(SerializationEncoding::Sbe);
3195    }
3196
3197    #[rstest]
3198    #[case(BusPayloadType::AccountState)]
3199    fn republish_external_message_skips_unsupported_binary_payload(
3200        #[case] payload_type: BusPayloadType,
3201    ) {
3202        let received = Rc::new(RefCell::new(Vec::<serde_json::Value>::new()));
3203        let account_received = received.clone();
3204        subscribe_account_state(
3205            "events.unsupported.*".into(),
3206            TypedHandler::from(move |state: &AccountState| {
3207                account_received
3208                    .borrow_mut()
3209                    .push(serde_json::to_value(state).unwrap());
3210            }),
3211            None,
3212        );
3213
3214        let message = BusMessage::with_str_topic(
3215            "events.unsupported.payload",
3216            payload_type,
3217            Bytes::from_static(b"malformed unsupported payload"),
3218            SerializationEncoding::Sbe,
3219        );
3220        get_message_bus()
3221            .borrow_mut()
3222            .add_streaming_type(payload_type);
3223        republish_external_message(&message).unwrap();
3224
3225        assert!(received.borrow().is_empty());
3226        reset_message_bus();
3227    }
3228
3229    #[rstest]
3230    fn republish_external_message_errors_for_malformed_supported_payload() {
3231        let message = BusMessage::with_str_topic(
3232            "data.quotes.AUDUSD.SIM",
3233            BusPayloadType::QuoteTick,
3234            Bytes::from_static(b"not-json"),
3235            SerializationEncoding::Json,
3236        );
3237
3238        get_message_bus()
3239            .borrow_mut()
3240            .add_streaming_type(BusPayloadType::QuoteTick);
3241        let error = republish_external_message(&message).unwrap_err();
3242
3243        assert!(
3244            error
3245                .to_string()
3246                .contains("failed to decode JSON QuoteTick"),
3247            "{error:?}"
3248        );
3249        reset_message_bus();
3250    }
3251
3252    #[rstest]
3253    fn republish_external_message_rejects_invalid_topic_and_processes_next_message() {
3254        let quote = QuoteTick::default();
3255        let payload = serde_json::to_vec(&quote).unwrap();
3256        let invalid_message = BusMessage::with_str_topic(
3257            "data.quotes.AUDUSD.SIM*",
3258            BusPayloadType::Custom(Ustr::from("UnregisteredCustomData")),
3259            Bytes::from(payload.clone()),
3260            SerializationEncoding::Json,
3261        );
3262        let valid_message = BusMessage::with_str_topic(
3263            "data.quotes.AUDUSD.SIM",
3264            BusPayloadType::QuoteTick,
3265            Bytes::from(payload),
3266            SerializationEncoding::Json,
3267        );
3268        let received = Rc::new(RefCell::new(Vec::<QuoteTick>::new()));
3269        let received_handler = received.clone();
3270        subscribe_quotes(
3271            "data.quotes.*".into(),
3272            TypedHandler::from(move |quote: &QuoteTick| {
3273                received_handler.borrow_mut().push(*quote);
3274            }),
3275            None,
3276        );
3277        get_message_bus()
3278            .borrow_mut()
3279            .add_streaming_type(BusPayloadType::QuoteTick);
3280
3281        let error = republish_external_message(&invalid_message).unwrap_err();
3282        republish_external_message(&valid_message).unwrap();
3283
3284        assert_eq!(
3285            format!("{error:#}"),
3286            "invalid external message topic: Topic `value` contained invalid characters, was data.quotes.AUDUSD.SIM*"
3287        );
3288        assert_eq!(*received.borrow(), vec![quote]);
3289        reset_message_bus();
3290    }
3291
3292    #[cfg(feature = "sbe")]
3293    #[rstest]
3294    fn publish_quote_sbe_forwards_decodable_payload_to_external_egress() {
3295        let publications = install_capturing_external_egress(SerializationEncoding::Sbe);
3296        let quote = QuoteTick::default();
3297
3298        publish_quote("data.quotes.TEST".into(), &quote);
3299
3300        let publications = publications.borrow();
3301        assert_eq!(publications.len(), 1);
3302        assert_eq!(publications[0].topic, "data.quotes.TEST");
3303        assert_eq!(
3304            QuoteTick::from_sbe(&publications[0].payload)
3305                .expect("SBE payload must decode as QuoteTick"),
3306            quote
3307        );
3308        drop(publications);
3309        reset_message_bus();
3310    }
3311
3312    #[cfg(feature = "sbe")]
3313    #[rstest]
3314    fn publish_option_greeks_sbe_forwards_decodable_payload_to_external_egress() {
3315        let publications = install_capturing_external_egress(SerializationEncoding::Sbe);
3316        let greeks = option_greeks();
3317
3318        publish_option_greeks("data.option_greeks.TEST".into(), &greeks);
3319
3320        let publications = publications.borrow();
3321        assert_eq!(publications.len(), 1);
3322        assert_eq!(publications[0].topic, "data.option_greeks.TEST");
3323        assert_eq!(
3324            OptionGreeks::from_sbe(&publications[0].payload)
3325                .expect("SBE payload must decode as OptionGreeks"),
3326            greeks
3327        );
3328        drop(publications);
3329        reset_message_bus();
3330    }
3331
3332    #[cfg(not(feature = "sbe"))]
3333    #[rstest]
3334    fn publish_quote_sbe_without_feature_drops_payload() {
3335        let publications = install_capturing_external_egress(SerializationEncoding::Sbe);
3336        let quote = QuoteTick::default();
3337
3338        publish_quote("data.quotes.TEST".into(), &quote);
3339
3340        assert!(publications.borrow().is_empty());
3341        reset_message_bus();
3342    }
3343
3344    #[rstest]
3345    fn publish_quote_external_egress_respects_filter_and_suppress_guard() {
3346        let publications = install_capturing_external_egress(SerializationEncoding::MsgPack);
3347        let quote = QuoteTick::default();
3348
3349        get_message_bus()
3350            .borrow_mut()
3351            .set_types_filter(vec!["QuoteTick".to_string()]);
3352        publish_quote("data.quotes.FILTERED".into(), &quote);
3353
3354        get_message_bus().borrow_mut().set_types_filter(Vec::new());
3355        {
3356            let _guard = SuppressExternalGuard::new();
3357            publish_quote("data.quotes.SUPPRESSED".into(), &quote);
3358        }
3359        publish_quote("data.quotes.PUBLISHED".into(), &quote);
3360
3361        let publications = publications.borrow();
3362        assert_eq!(publications.len(), 1);
3363        assert_eq!(publications[0].topic, "data.quotes.PUBLISHED");
3364        drop(publications);
3365        reset_message_bus();
3366    }
3367
3368    #[rstest]
3369    #[case(None)]
3370    #[case(Some(Vec::new()))]
3371    fn publish_typed_report_external_egress_requires_external_streams(
3372        #[case] external_streams: Option<Vec<String>>,
3373    ) {
3374        let publications = install_capturing_external_egress_config(&MessageBusConfig {
3375            external_streams,
3376            ..Default::default()
3377        });
3378
3379        publish_any(
3380            "reconciliation.raw.OrderStatusReport".into(),
3381            &order_status_report(),
3382        );
3383
3384        assert!(publications.borrow().is_empty());
3385        reset_message_bus();
3386    }
3387
3388    #[rstest]
3389    fn publish_typed_report_external_egress_respects_filter() {
3390        let publications = install_capturing_external_stream_egress(SerializationEncoding::Json);
3391
3392        get_message_bus()
3393            .borrow_mut()
3394            .set_types_filter(vec!["OrderStatusReport".to_string()]);
3395        publish_any(
3396            "reconciliation.raw.OrderStatusReport".into(),
3397            &order_status_report(),
3398        );
3399
3400        assert!(publications.borrow().is_empty());
3401        reset_message_bus();
3402    }
3403
3404    fn order_status_report() -> OrderStatusReport {
3405        OrderStatusReport::new(
3406            AccountId::from("SIM-001"),
3407            InstrumentId::from("AUD/USD.SIM"),
3408            Some(ClientOrderId::from("O-001")),
3409            VenueOrderId::from("ORDER-001"),
3410            Some(OrderSide::Buy),
3411            OrderType::Limit,
3412            TimeInForce::Gtc,
3413            OrderStatus::Accepted,
3414            Quantity::from("10"),
3415            Quantity::from("2"),
3416            UnixNanos::from(1_000_000_001),
3417            UnixNanos::from(1_000_000_002),
3418            UnixNanos::from(1_000_000_003),
3419            Some(UUID4::from("00000000-0000-4000-8000-000000000001")),
3420        )
3421    }
3422
3423    #[rstest]
3424    fn publish_quote_uses_market_data_encoding_override() {
3425        let publications = install_capturing_external_egress_config(&MessageBusConfig {
3426            encoding: SerializationEncoding::Json,
3427            encoding_market_data: Some(SerializationEncoding::MsgPack),
3428            ..Default::default()
3429        });
3430        let quote = QuoteTick::default();
3431
3432        publish_quote("data.quotes.TEST".into(), &quote);
3433
3434        let publications = publications.borrow();
3435        assert_eq!(publications.len(), 1);
3436        assert_eq!(publications[0].encoding, SerializationEncoding::MsgPack);
3437        assert_eq!(
3438            rmp_serde::from_slice::<QuoteTick>(&publications[0].payload)
3439                .expect("MsgPack payload must decode as QuoteTick"),
3440            quote
3441        );
3442        drop(publications);
3443        reset_message_bus();
3444    }
3445
3446    #[rstest]
3447    fn publish_custom_data_forwards_envelope_to_external_egress_and_respects_filter() {
3448        let publications = install_capturing_external_egress(SerializationEncoding::Json);
3449        let custom = stub_custom_data(100, 42, None, Some("stub-id".to_string()));
3450
3451        publish_any("data.custom.StubCustomData".into(), &custom);
3452
3453        get_message_bus()
3454            .borrow_mut()
3455            .set_types_filter(vec!["StubCustomData".to_string()]);
3456        publish_any("data.custom.FILTERED".into(), &custom);
3457
3458        let publications = publications.borrow();
3459        assert_eq!(publications.len(), 1);
3460        assert_eq!(publications[0].topic, "data.custom.StubCustomData");
3461
3462        let payload_value: serde_json::Value = serde_json::from_slice(&publications[0].payload)
3463            .expect("JSON payload must decode as a CustomData envelope");
3464        assert_eq!(
3465            payload_value.get("type").and_then(|value| value.as_str()),
3466            Some("StubCustomData")
3467        );
3468        assert_eq!(
3469            payload_value
3470                .pointer("/data_type/type_name")
3471                .and_then(|value| value.as_str()),
3472            Some("StubCustomData")
3473        );
3474        assert_eq!(
3475            payload_value
3476                .pointer("/data_type/identifier")
3477                .and_then(|value| value.as_str()),
3478            Some("stub-id")
3479        );
3480        assert_eq!(
3481            payload_value
3482                .pointer("/payload/value")
3483                .and_then(serde_json::Value::as_i64),
3484            Some(42)
3485        );
3486        drop(publications);
3487        reset_message_bus();
3488    }
3489
3490    #[rstest]
3491    fn test_typed_quote_publish_subscribe_integration() {
3492        let msgbus = get_message_bus();
3493        let pub_count = msgbus.borrow().pub_count();
3494        let received = Rc::new(RefCell::new(Vec::new()));
3495        let received_clone = received.clone();
3496
3497        let handler = TypedHandler::from(move |quote: &QuoteTick| {
3498            received_clone.borrow_mut().push(*quote);
3499        });
3500
3501        subscribe_quotes("data.quotes.*".into(), handler, None);
3502
3503        let quote = QuoteTick::default();
3504        publish_quote("data.quotes.TEST".into(), &quote);
3505        publish_quote("data.quotes.TEST".into(), &quote);
3506
3507        assert_eq!(received.borrow().len(), 2);
3508        assert_eq!(msgbus.borrow().pub_count(), pub_count + 2);
3509    }
3510
3511    #[rstest]
3512    fn test_typed_trade_publish_subscribe_integration() {
3513        let _msgbus = get_message_bus();
3514        let received = Rc::new(RefCell::new(Vec::new()));
3515        let received_clone = received.clone();
3516
3517        let handler = TypedHandler::from(move |trade: &TradeTick| {
3518            received_clone.borrow_mut().push(*trade);
3519        });
3520
3521        subscribe_trades("data.trades.*".into(), handler, None);
3522
3523        let trade = TradeTick::default();
3524        publish_trade("data.trades.TEST".into(), &trade);
3525
3526        assert_eq!(received.borrow().len(), 1);
3527    }
3528
3529    #[rstest]
3530    fn test_typed_bar_publish_subscribe_integration() {
3531        let _msgbus = get_message_bus();
3532        let received = Rc::new(RefCell::new(Vec::new()));
3533        let received_clone = received.clone();
3534
3535        let handler = TypedHandler::from(move |bar: &Bar| {
3536            received_clone.borrow_mut().push(*bar);
3537        });
3538
3539        subscribe_bars("data.bars.*".into(), handler, None);
3540
3541        let bar = Bar::default();
3542        publish_bar("data.bars.TEST".into(), &bar);
3543
3544        assert_eq!(received.borrow().len(), 1);
3545    }
3546
3547    #[rstest]
3548    fn test_typed_deltas_publish_subscribe_integration() {
3549        let _msgbus = get_message_bus();
3550        let received = Rc::new(RefCell::new(Vec::new()));
3551        let received_clone = received.clone();
3552
3553        let handler = TypedHandler::from(move |deltas: &OrderBookDeltas| {
3554            received_clone.borrow_mut().push(deltas.clone());
3555        });
3556
3557        subscribe_book_deltas("data.book.deltas.*".into(), handler, None);
3558
3559        let instrument_id = InstrumentId::from("TEST.VENUE");
3560        let delta = OrderBookDelta::clear(instrument_id, 0, 1.into(), 2.into());
3561        let deltas = OrderBookDeltas::new(instrument_id, vec![delta]);
3562        publish_deltas("data.book.deltas.TEST".into(), &deltas);
3563
3564        assert_eq!(received.borrow().len(), 1);
3565    }
3566
3567    #[rstest]
3568    fn test_typed_unsubscribe_stops_delivery() {
3569        let _msgbus = get_message_bus();
3570        let received = Rc::new(RefCell::new(Vec::new()));
3571        let received_clone = received.clone();
3572
3573        let handler = TypedHandler::from_with_id("unsub-test", move |quote: &QuoteTick| {
3574            received_clone.borrow_mut().push(*quote);
3575        });
3576
3577        subscribe_quotes("data.quotes.UNSUB".into(), handler.clone(), None);
3578
3579        let quote = QuoteTick::default();
3580        publish_quote("data.quotes.UNSUB".into(), &quote);
3581        assert_eq!(received.borrow().len(), 1);
3582
3583        unsubscribe_quotes("data.quotes.UNSUB".into(), &handler);
3584
3585        publish_quote("data.quotes.UNSUB".into(), &quote);
3586        assert_eq!(received.borrow().len(), 1);
3587    }
3588
3589    #[rstest]
3590    fn test_typed_wildcard_pattern_matching() {
3591        let _msgbus = get_message_bus();
3592        let received = Rc::new(RefCell::new(Vec::new()));
3593        let received_clone = received.clone();
3594
3595        let handler = TypedHandler::from(move |quote: &QuoteTick| {
3596            received_clone.borrow_mut().push(*quote);
3597        });
3598
3599        subscribe_quotes("data.quotes.WILD.*".into(), handler, None);
3600
3601        let quote = QuoteTick::default();
3602        publish_quote("data.quotes.WILD.AAPL".into(), &quote);
3603        publish_quote("data.quotes.WILD.MSFT".into(), &quote);
3604        publish_quote("data.quotes.OTHER.AAPL".into(), &quote);
3605
3606        assert_eq!(received.borrow().len(), 2);
3607    }
3608
3609    #[rstest]
3610    fn test_typed_priority_ordering() {
3611        let _msgbus = get_message_bus();
3612        let order = Rc::new(RefCell::new(Vec::new()));
3613
3614        let order1 = order.clone();
3615        let handler_low = TypedHandler::from_with_id("low-priority", move |_: &QuoteTick| {
3616            order1.borrow_mut().push("low");
3617        });
3618
3619        let order2 = order.clone();
3620        let handler_high = TypedHandler::from_with_id("high-priority", move |_: &QuoteTick| {
3621            order2.borrow_mut().push("high");
3622        });
3623
3624        subscribe_quotes("data.quotes.PRIO.*".into(), handler_low, Some(1));
3625        subscribe_quotes("data.quotes.PRIO.*".into(), handler_high, Some(10));
3626
3627        let quote = QuoteTick::default();
3628        publish_quote("data.quotes.PRIO.TEST".into(), &quote);
3629
3630        assert_eq!(*order.borrow(), vec!["high", "low"]);
3631    }
3632
3633    #[rstest]
3634    fn test_typed_routing_isolation() {
3635        let _msgbus = get_message_bus();
3636        let quote_received = Rc::new(RefCell::new(false));
3637        let trade_received = Rc::new(RefCell::new(false));
3638
3639        let qr = quote_received.clone();
3640        let quote_handler = TypedHandler::from(move |_: &QuoteTick| {
3641            *qr.borrow_mut() = true;
3642        });
3643
3644        let tr = trade_received.clone();
3645        let trade_handler = TypedHandler::from(move |_: &TradeTick| {
3646            *tr.borrow_mut() = true;
3647        });
3648
3649        subscribe_quotes("data.iso.*".into(), quote_handler, None);
3650        subscribe_trades("data.iso.*".into(), trade_handler, None);
3651
3652        let quote = QuoteTick::default();
3653        publish_quote("data.iso.TEST".into(), &quote);
3654
3655        assert!(*quote_received.borrow());
3656        assert!(!*trade_received.borrow());
3657    }
3658
3659    #[rstest]
3660    fn test_send_data_allows_reentrant_topic_access() {
3661        use crate::msgbus::switchboard::get_quotes_topic;
3662
3663        let _msgbus = get_message_bus();
3664        let topic_retrieved = Rc::new(RefCell::new(false));
3665        let topic_clone = topic_retrieved.clone();
3666
3667        let handler = TypedIntoHandler::from(move |data: Data| {
3668            let instrument_id = data.instrument_id();
3669            let _topic = get_quotes_topic(instrument_id);
3670            *topic_clone.borrow_mut() = true;
3671        });
3672
3673        let endpoint: MStr<Endpoint> = "ReentrantTest.data".into();
3674        register_data_endpoint(endpoint, handler);
3675
3676        let quote = QuoteTick::default();
3677        send_data(endpoint, Data::Quote(quote));
3678
3679        assert!(*topic_retrieved.borrow());
3680    }
3681
3682    #[rstest]
3683    fn test_send_trading_command_allows_reentrant_topic_access() {
3684        use nautilus_model::identifiers::{StrategyId, TraderId};
3685
3686        use crate::{
3687            messages::execution::{TradingCommand, cancel::CancelAllOrders},
3688            msgbus::switchboard::get_trades_topic,
3689        };
3690
3691        let _msgbus = get_message_bus();
3692        let topic_retrieved = Rc::new(RefCell::new(false));
3693        let topic_clone = topic_retrieved.clone();
3694
3695        let handler = TypedIntoHandler::from(move |cmd: TradingCommand| {
3696            let instrument_id = cmd.instrument_id();
3697            let _topic = get_trades_topic(instrument_id);
3698            *topic_clone.borrow_mut() = true;
3699        });
3700
3701        let endpoint: MStr<Endpoint> = "ReentrantTest.tradingCmd".into();
3702        register_trading_command_endpoint(endpoint, handler);
3703
3704        let cmd = TradingCommand::CancelAllOrders(CancelAllOrders::new(
3705            TraderId::new("TESTER-001"),
3706            None,
3707            StrategyId::new("S-001"),
3708            InstrumentId::from("TEST.VENUE"),
3709            None,
3710            UUID4::new(),
3711            0.into(),
3712            None,
3713            None, // correlation_id
3714        ));
3715        send_trading_command(endpoint, cmd);
3716
3717        assert!(*topic_retrieved.borrow());
3718    }
3719
3720    #[rstest]
3721    fn test_send_account_state_allows_reentrant_topic_access() {
3722        use nautilus_model::{enums::AccountType, identifiers::AccountId, types::Currency};
3723
3724        use crate::msgbus::switchboard::get_quotes_topic;
3725
3726        let _msgbus = get_message_bus();
3727        let topic_retrieved = Rc::new(RefCell::new(false));
3728        let topic_clone = topic_retrieved.clone();
3729
3730        let handler = TypedHandler::from(move |_state: &AccountState| {
3731            let instrument_id = InstrumentId::from("TEST.VENUE");
3732            let _topic = get_quotes_topic(instrument_id);
3733            *topic_clone.borrow_mut() = true;
3734        });
3735
3736        let endpoint: MStr<Endpoint> = "ReentrantTest.accountState".into();
3737        register_account_state_endpoint(endpoint, handler);
3738
3739        let state = AccountState::new(
3740            AccountId::new("SIM-001"),
3741            AccountType::Cash,
3742            vec![],
3743            vec![],
3744            true,
3745            UUID4::new(),
3746            0.into(),
3747            0.into(),
3748            Some(Currency::USD()),
3749        );
3750        send_account_state(endpoint, &state);
3751
3752        assert!(*topic_retrieved.borrow());
3753    }
3754
3755    #[rstest]
3756    fn test_send_order_event_allows_reentrant_topic_access() {
3757        use crate::msgbus::switchboard::get_quotes_topic;
3758
3759        let _msgbus = get_message_bus();
3760        let topic_retrieved = Rc::new(RefCell::new(false));
3761        let topic_clone = topic_retrieved.clone();
3762
3763        let handler = TypedIntoHandler::from(move |_event: OrderEventAny| {
3764            let instrument_id = InstrumentId::from("TEST.VENUE");
3765            let _topic = get_quotes_topic(instrument_id);
3766            *topic_clone.borrow_mut() = true;
3767        });
3768
3769        let endpoint: MStr<Endpoint> = "ReentrantTest.orderEvent".into();
3770        register_order_event_endpoint(endpoint, handler);
3771
3772        let event = OrderEventAny::Denied(OrderDeniedSpec::builder().build());
3773        send_order_event(endpoint, event);
3774
3775        assert!(*topic_retrieved.borrow());
3776    }
3777
3778    #[rstest]
3779    fn test_send_data_command_allows_reentrant_topic_access() {
3780        use crate::msgbus::switchboard::get_trades_topic;
3781
3782        let msgbus = get_message_bus();
3783        let sent_count = msgbus.borrow().sent_count();
3784        let req_count = msgbus.borrow().req_count();
3785        let topic_retrieved = Rc::new(RefCell::new(false));
3786        let topic_clone = topic_retrieved.clone();
3787
3788        let handler = TypedIntoHandler::from(move |_cmd: DataCommand| {
3789            let _topic = get_trades_topic(InstrumentId::from("TEST.VENUE"));
3790            *topic_clone.borrow_mut() = true;
3791        });
3792
3793        let endpoint: MStr<Endpoint> = "ReentrantTest.dataCmd".into();
3794        register_data_command_endpoint(endpoint, handler);
3795
3796        let cmd = DataCommand::Subscribe(SubscribeCommand::Quotes(SubscribeQuotes::new(
3797            InstrumentId::from("TEST.VENUE"),
3798            Some(ClientId::new("SIM")),
3799            None,
3800            UUID4::new(),
3801            0.into(),
3802            None,
3803            None,
3804        )));
3805        send_data_command(endpoint, cmd);
3806
3807        assert!(*topic_retrieved.borrow());
3808        assert_eq!(msgbus.borrow().sent_count(), sent_count + 1);
3809        assert_eq!(msgbus.borrow().req_count(), req_count);
3810
3811        let request = DataCommand::Request(RequestCommand::Quotes(RequestQuotes::new(
3812            InstrumentId::from("TEST.VENUE"),
3813            None,
3814            None,
3815            None,
3816            Some(ClientId::new("SIM")),
3817            UUID4::new(),
3818            0.into(),
3819            None,
3820        )));
3821        send_data_command(endpoint, request);
3822
3823        assert_eq!(msgbus.borrow().sent_count(), sent_count + 2);
3824        assert_eq!(msgbus.borrow().req_count(), req_count + 1);
3825    }
3826
3827    #[rstest]
3828    fn test_send_data_request_without_endpoint_does_not_increment_counts() {
3829        let msgbus = get_message_bus();
3830        let sent_count = msgbus.borrow().sent_count();
3831        let req_count = msgbus.borrow().req_count();
3832
3833        let request = DataCommand::Request(RequestCommand::Quotes(RequestQuotes::new(
3834            InstrumentId::from("MISSING.VENUE"),
3835            None,
3836            None,
3837            None,
3838            Some(ClientId::new("SIM")),
3839            UUID4::new(),
3840            0.into(),
3841            None,
3842        )));
3843        send_data_command("Missing.dataCmd".into(), request);
3844
3845        assert_eq!(msgbus.borrow().sent_count(), sent_count);
3846        assert_eq!(msgbus.borrow().req_count(), req_count);
3847    }
3848
3849    #[rstest]
3850    fn test_send_data_response_allows_reentrant_topic_access() {
3851        use nautilus_model::identifiers::ClientId;
3852
3853        use crate::{
3854            messages::data::{DataResponse, QuotesResponse},
3855            msgbus::switchboard::get_quotes_topic,
3856        };
3857
3858        let _msgbus = get_message_bus();
3859        let topic_retrieved = Rc::new(RefCell::new(false));
3860        let topic_clone = topic_retrieved.clone();
3861
3862        let handler = TypedIntoHandler::from(move |_resp: DataResponse| {
3863            let _topic = get_quotes_topic(InstrumentId::from("TEST.VENUE"));
3864            *topic_clone.borrow_mut() = true;
3865        });
3866
3867        let endpoint: MStr<Endpoint> = "ReentrantTest.dataResp".into();
3868        register_data_response_endpoint(endpoint, handler);
3869
3870        let resp = DataResponse::Quotes(QuotesResponse {
3871            correlation_id: UUID4::new(),
3872            client_id: ClientId::new("SIM"),
3873            instrument_ids: vec![InstrumentId::from("TEST.VENUE")],
3874            data: (vec![]).into(),
3875            start: None,
3876            end: None,
3877            ts_init: 0.into(),
3878            params: None,
3879        });
3880        send_data_response(endpoint, resp);
3881
3882        assert!(*topic_retrieved.borrow());
3883    }
3884
3885    #[rstest]
3886    fn test_send_response_increments_response_count() {
3887        use nautilus_model::identifiers::ClientId;
3888
3889        use crate::messages::data::{DataResponse, QuotesResponse};
3890
3891        let msgbus = get_message_bus();
3892        let res_count = msgbus.borrow().res_count();
3893        let resp = DataResponse::Quotes(QuotesResponse {
3894            correlation_id: UUID4::new(),
3895            client_id: ClientId::new("SIM"),
3896            instrument_ids: vec![InstrumentId::from("TEST.VENUE")],
3897            data: (vec![]).into(),
3898            start: None,
3899            end: None,
3900            ts_init: 0.into(),
3901            params: None,
3902        });
3903
3904        send_response(&UUID4::new(), &resp);
3905
3906        assert_eq!(msgbus.borrow().res_count(), res_count + 1);
3907    }
3908
3909    #[rstest]
3910    fn test_send_response_consumes_handler_for_all_variants() {
3911        let client_id = ClientId::new("SIM");
3912        let instrument = audusd_sim();
3913        let instrument_id = instrument.id;
3914        let venue = Venue::new("SIM");
3915        let bar_type = BarType::from("AUD/USD.SIM-1-MINUTE-LAST-EXTERNAL");
3916
3917        let correlation_id = UUID4::new();
3918        assert_response_handler_is_consumed(&DataResponse::Data(CustomDataResponse::new(
3919            correlation_id,
3920            client_id,
3921            Some(venue),
3922            DataType::new("TestData", None, None),
3923            Vec::<u8>::new(),
3924            None,
3925            None,
3926            UnixNanos::default(),
3927            None,
3928        )));
3929
3930        let correlation_id = UUID4::new();
3931        assert_response_handler_is_consumed(&DataResponse::Instrument(Box::new(
3932            InstrumentResponse::new(
3933                correlation_id,
3934                client_id,
3935                instrument_id,
3936                InstrumentAny::CurrencyPair(instrument),
3937                None,
3938                None,
3939                UnixNanos::default(),
3940                None,
3941            ),
3942        )));
3943
3944        let correlation_id = UUID4::new();
3945        assert_response_handler_is_consumed(&DataResponse::Instruments(InstrumentsResponse::new(
3946            correlation_id,
3947            client_id,
3948            venue,
3949            Vec::new(),
3950            None,
3951            None,
3952            UnixNanos::default(),
3953            None,
3954        )));
3955
3956        let correlation_id = UUID4::new();
3957        assert_response_handler_is_consumed(&DataResponse::Book(BookResponse::new(
3958            correlation_id,
3959            client_id,
3960            instrument_id,
3961            OrderBook::new(instrument_id, BookType::L2_MBP),
3962            None,
3963            None,
3964            UnixNanos::default(),
3965            None,
3966        )));
3967
3968        let correlation_id = UUID4::new();
3969        assert_response_handler_is_consumed(&DataResponse::BookDeltas(BookDeltasResponse::new(
3970            correlation_id,
3971            client_id,
3972            instrument_id,
3973            Vec::new(),
3974            None,
3975            None,
3976            UnixNanos::default(),
3977            None,
3978        )));
3979
3980        let correlation_id = UUID4::new();
3981        assert_response_handler_is_consumed(&DataResponse::BookDepth(BookDepthResponse::new(
3982            correlation_id,
3983            client_id,
3984            instrument_id,
3985            Vec::new(),
3986            None,
3987            None,
3988            UnixNanos::default(),
3989            None,
3990        )));
3991
3992        let correlation_id = UUID4::new();
3993        assert_response_handler_is_consumed(&DataResponse::Quotes(QuotesResponse::new(
3994            correlation_id,
3995            client_id,
3996            instrument_id,
3997            Vec::new(),
3998            None,
3999            None,
4000            UnixNanos::default(),
4001            None,
4002        )));
4003
4004        let correlation_id = UUID4::new();
4005        assert_response_handler_is_consumed(&DataResponse::Trades(TradesResponse::new(
4006            correlation_id,
4007            client_id,
4008            instrument_id,
4009            Vec::new(),
4010            None,
4011            None,
4012            UnixNanos::default(),
4013            None,
4014        )));
4015
4016        let correlation_id = UUID4::new();
4017        assert_response_handler_is_consumed(&DataResponse::FundingRates(
4018            FundingRatesResponse::new(
4019                correlation_id,
4020                client_id,
4021                instrument_id,
4022                Vec::new(),
4023                None,
4024                None,
4025                UnixNanos::default(),
4026                None,
4027            ),
4028        ));
4029
4030        let correlation_id = UUID4::new();
4031        assert_response_handler_is_consumed(&DataResponse::OptionChainReferencePrice(
4032            OptionChainReferencePriceResponse::new(
4033                correlation_id,
4034                client_id,
4035                OptionSeriesId::new_derived(
4036                    venue,
4037                    Ustr::from("BTC"),
4038                    Ustr::from("BTC"),
4039                    UnixNanos::from(100),
4040                ),
4041                Some(Price::from("50123.45")),
4042                UnixNanos::default(),
4043                None,
4044            ),
4045        ));
4046
4047        let correlation_id = UUID4::new();
4048        assert_response_handler_is_consumed(&DataResponse::Bars(BarsResponse::new(
4049            correlation_id,
4050            client_id,
4051            bar_type,
4052            Vec::new(),
4053            None,
4054            None,
4055            UnixNanos::default(),
4056            None,
4057        )));
4058    }
4059
4060    #[rstest]
4061    fn test_send_response_allows_reentrant_same_correlation_registration() {
4062        reset_message_bus();
4063
4064        let correlation_id = UUID4::new();
4065        let first_calls = Rc::new(Cell::new(0));
4066        let second_calls = Rc::new(Cell::new(0));
4067        let first_handler_calls = first_calls.clone();
4068        let second_handler_calls = second_calls.clone();
4069        register_response_handler(
4070            &correlation_id,
4071            TypedHandler::from(move |_response: &DataResponseEnvelope| {
4072                first_handler_calls.set(first_handler_calls.get() + 1);
4073                let second_handler_calls = second_handler_calls.clone();
4074                register_response_handler(
4075                    &correlation_id,
4076                    TypedHandler::from(move |_response: &DataResponseEnvelope| {
4077                        second_handler_calls.set(second_handler_calls.get() + 1);
4078                    }),
4079                );
4080            }),
4081        );
4082
4083        let response = DataResponse::Quotes(QuotesResponse::new(
4084            correlation_id,
4085            ClientId::new("SIM"),
4086            InstrumentId::from("TEST.VENUE"),
4087            Vec::new(),
4088            None,
4089            None,
4090            UnixNanos::default(),
4091            None,
4092        ));
4093
4094        send_response(&correlation_id, &response);
4095        assert_eq!(first_calls.get(), 1);
4096        assert_eq!(second_calls.get(), 0);
4097        assert!(
4098            get_message_bus()
4099                .borrow()
4100                .get_response_handler(&correlation_id)
4101                .is_some(),
4102        );
4103
4104        send_response(&correlation_id, &response);
4105        assert_eq!(first_calls.get(), 1);
4106        assert_eq!(second_calls.get(), 1);
4107        assert!(
4108            get_message_bus()
4109                .borrow()
4110                .get_response_handler(&correlation_id)
4111                .is_none(),
4112        );
4113    }
4114
4115    #[rstest]
4116    fn test_send_execution_report_allows_reentrant_topic_access() {
4117        use nautilus_model::{
4118            identifiers::{AccountId, ClientId, Venue},
4119            reports::ExecutionMassStatus,
4120        };
4121
4122        use crate::{messages::execution::ExecutionReport, msgbus::switchboard::get_trades_topic};
4123
4124        let _msgbus = get_message_bus();
4125        let topic_retrieved = Rc::new(RefCell::new(false));
4126        let topic_clone = topic_retrieved.clone();
4127
4128        let handler = TypedIntoHandler::from(move |_report: ExecutionReport| {
4129            let _topic = get_trades_topic(InstrumentId::from("TEST.VENUE"));
4130            *topic_clone.borrow_mut() = true;
4131        });
4132
4133        let endpoint: MStr<Endpoint> = "ReentrantTest.execReport".into();
4134        register_execution_report_endpoint(endpoint, handler);
4135
4136        let report = ExecutionReport::MassStatus(Box::new(ExecutionMassStatus::new(
4137            ClientId::new("SIM"),
4138            AccountId::new("SIM-001"),
4139            Venue::new("TEST"),
4140            0.into(),
4141            None,
4142        )));
4143        send_execution_report(endpoint, report);
4144
4145        assert!(*topic_retrieved.borrow());
4146    }
4147
4148    #[rstest]
4149    fn test_order_event_handler_can_send_trading_command() {
4150        // Tests that a handler processing an order event can send a trading command
4151        // without causing a borrow conflict. This simulates the scenario where a
4152        // strategy's on_order_accepted() handler calls cancel_order().
4153        let _msgbus = get_message_bus();
4154        let command_sent = Rc::new(RefCell::new(false));
4155        let command_sent_clone = command_sent.clone();
4156
4157        let cmd_received = Rc::new(RefCell::new(false));
4158        let cmd_received_clone = cmd_received.clone();
4159        let cmd_handler = TypedIntoHandler::from(move |_cmd: TradingCommand| {
4160            *cmd_received_clone.borrow_mut() = true;
4161        });
4162        let cmd_endpoint: MStr<Endpoint> = "ReentrantTest.execCmd".into();
4163        register_trading_command_endpoint(cmd_endpoint, cmd_handler);
4164
4165        let event_handler = TypedIntoHandler::from(move |_event: OrderEventAny| {
4166            // Simulate strategy calling cancel_order from on_order_accepted
4167            let command = TradingCommand::CancelAllOrders(CancelAllOrders::new(
4168                TraderId::new("TESTER-001"),
4169                None,
4170                StrategyId::new("S-001"),
4171                InstrumentId::from("TEST.VENUE"),
4172                Some(OrderSide::Buy),
4173                UUID4::new(),
4174                0.into(),
4175                None,
4176                None, // correlation_id
4177            ));
4178            send_trading_command(cmd_endpoint, command);
4179            *command_sent_clone.borrow_mut() = true;
4180        });
4181
4182        let event_endpoint: MStr<Endpoint> = "ReentrantTest.orderEvt".into();
4183        register_order_event_endpoint(event_endpoint, event_handler);
4184
4185        let event = OrderEventAny::Denied(OrderDeniedSpec::builder().build());
4186        send_order_event(event_endpoint, event);
4187
4188        assert!(
4189            *command_sent.borrow(),
4190            "Order event handler should have run"
4191        );
4192        assert!(
4193            *cmd_received.borrow(),
4194            "Trading command should have been received"
4195        );
4196    }
4197
4198    #[rstest]
4199    fn test_data_handler_can_send_data_command() {
4200        // Tests that a handler processing data can send a data command
4201        // without causing a borrow conflict.
4202        let _msgbus = get_message_bus();
4203        let command_sent = Rc::new(RefCell::new(false));
4204        let command_sent_clone = command_sent.clone();
4205
4206        let cmd_received = Rc::new(RefCell::new(false));
4207        let cmd_received_clone = cmd_received.clone();
4208        let cmd_handler = TypedIntoHandler::from(move |_cmd: DataCommand| {
4209            *cmd_received_clone.borrow_mut() = true;
4210        });
4211        let cmd_endpoint: MStr<Endpoint> = "ReentrantTest.dataCmd2".into();
4212        register_data_command_endpoint(cmd_endpoint, cmd_handler);
4213
4214        let data_handler = TypedIntoHandler::from(move |_data: Data| {
4215            let command = DataCommand::Subscribe(SubscribeCommand::Quotes(SubscribeQuotes::new(
4216                InstrumentId::from("TEST.VENUE"),
4217                Some(ClientId::new("SIM")),
4218                None,
4219                UUID4::new(),
4220                0.into(),
4221                None,
4222                None,
4223            )));
4224            send_data_command(cmd_endpoint, command);
4225            *command_sent_clone.borrow_mut() = true;
4226        });
4227
4228        let data_endpoint: MStr<Endpoint> = "ReentrantTest.data2".into();
4229        register_data_endpoint(data_endpoint, data_handler);
4230
4231        let quote = QuoteTick::default();
4232        send_data(data_endpoint, Data::Quote(quote));
4233
4234        assert!(*command_sent.borrow(), "Data handler should have run");
4235        assert!(
4236            *cmd_received.borrow(),
4237            "Data command should have been received"
4238        );
4239    }
4240
4241    #[rstest]
4242    fn test_trading_command_handler_can_send_order_event() {
4243        // Tests that a handler processing a trading command can send an order event
4244        // without causing a borrow conflict. This is the reverse direction of the
4245        // common re-entrancy scenario.
4246        let _msgbus = get_message_bus();
4247        let event_sent = Rc::new(RefCell::new(false));
4248        let event_sent_clone = event_sent.clone();
4249
4250        let evt_received = Rc::new(RefCell::new(false));
4251        let evt_received_clone = evt_received.clone();
4252        let evt_handler = TypedIntoHandler::from(move |_event: OrderEventAny| {
4253            *evt_received_clone.borrow_mut() = true;
4254        });
4255        let evt_endpoint: MStr<Endpoint> = "ReentrantTest.orderEvt2".into();
4256        register_order_event_endpoint(evt_endpoint, evt_handler);
4257
4258        let cmd_handler = TypedIntoHandler::from(move |_cmd: TradingCommand| {
4259            let event = OrderEventAny::Denied(OrderDeniedSpec::builder().build());
4260            send_order_event(evt_endpoint, event);
4261            *event_sent_clone.borrow_mut() = true;
4262        });
4263
4264        let cmd_endpoint: MStr<Endpoint> = "ReentrantTest.execCmd2".into();
4265        register_trading_command_endpoint(cmd_endpoint, cmd_handler);
4266
4267        let command = TradingCommand::CancelAllOrders(CancelAllOrders::new(
4268            TraderId::new("TESTER-001"),
4269            None,
4270            StrategyId::new("S-001"),
4271            InstrumentId::from("TEST.VENUE"),
4272            Some(OrderSide::Buy),
4273            UUID4::new(),
4274            0.into(),
4275            None,
4276            None, // correlation_id
4277        ));
4278        send_trading_command(cmd_endpoint, command);
4279
4280        assert!(
4281            *event_sent.borrow(),
4282            "Trading command handler should have run"
4283        );
4284        assert!(
4285            *evt_received.borrow(),
4286            "Order event should have been received"
4287        );
4288    }
4289
4290    #[rstest]
4291    fn test_nested_reentrant_calls() {
4292        // Tests deeply nested re-entrant calls: order event -> trading command -> order event.
4293        // This simulates a complex scenario where handlers chain multiple calls.
4294        let _msgbus = get_message_bus();
4295        let call_depth = Rc::new(RefCell::new(0u32));
4296
4297        let final_received = Rc::new(RefCell::new(false));
4298        let final_received_clone = final_received.clone();
4299        let final_evt_handler = TypedIntoHandler::from(move |_event: OrderEventAny| {
4300            *final_received_clone.borrow_mut() = true;
4301        });
4302        let final_evt_endpoint: MStr<Endpoint> = "ReentrantTest.finalEvt".into();
4303        register_order_event_endpoint(final_evt_endpoint, final_evt_handler);
4304
4305        let call_depth_clone2 = call_depth.clone();
4306        let mid_cmd_handler = TypedIntoHandler::from(move |_cmd: TradingCommand| {
4307            *call_depth_clone2.borrow_mut() += 1;
4308            let event = OrderEventAny::Denied(OrderDeniedSpec::builder().build());
4309            send_order_event(final_evt_endpoint, event);
4310        });
4311        let mid_cmd_endpoint: MStr<Endpoint> = "ReentrantTest.midCmd".into();
4312        register_trading_command_endpoint(mid_cmd_endpoint, mid_cmd_handler);
4313
4314        let call_depth_clone1 = call_depth.clone();
4315        let init_evt_handler = TypedIntoHandler::from(move |_event: OrderEventAny| {
4316            *call_depth_clone1.borrow_mut() += 1;
4317            let command = TradingCommand::CancelAllOrders(CancelAllOrders::new(
4318                TraderId::new("TESTER-001"),
4319                None,
4320                StrategyId::new("S-001"),
4321                InstrumentId::from("TEST.VENUE"),
4322                Some(OrderSide::Buy),
4323                UUID4::new(),
4324                0.into(),
4325                None,
4326                None, // correlation_id
4327            ));
4328            send_trading_command(mid_cmd_endpoint, command);
4329        });
4330        let init_evt_endpoint: MStr<Endpoint> = "ReentrantTest.initEvt".into();
4331        register_order_event_endpoint(init_evt_endpoint, init_evt_handler);
4332
4333        let event = OrderEventAny::Denied(OrderDeniedSpec::builder().build());
4334        send_order_event(init_evt_endpoint, event);
4335
4336        assert_eq!(
4337            *call_depth.borrow(),
4338            2,
4339            "Both intermediate handlers should have run"
4340        );
4341        assert!(
4342            *final_received.borrow(),
4343            "Final event handler should have received the event"
4344        );
4345    }
4346
4347    /// Recording tap used by the bus-tap registration tests. Stores every dispatched
4348    /// topic / endpoint plus a digest of the message so a test can assert the tap
4349    /// observed the exact dispatches it expected.
4350    #[derive(Default)]
4351    struct RecordingTap {
4352        publishes: RefCell<Vec<(String, std::any::TypeId)>>,
4353        sends: RefCell<Vec<(String, std::any::TypeId)>>,
4354        responses: RefCell<Vec<(UUID4, std::any::TypeId)>>,
4355    }
4356
4357    impl RecordingTap {
4358        fn publish_topics(&self) -> Vec<String> {
4359            self.publishes
4360                .borrow()
4361                .iter()
4362                .map(|(t, _)| t.clone())
4363                .collect()
4364        }
4365
4366        fn send_endpoints(&self) -> Vec<String> {
4367            self.sends.borrow().iter().map(|(e, _)| e.clone()).collect()
4368        }
4369
4370        fn response_correlation_ids(&self) -> Vec<UUID4> {
4371            self.responses.borrow().iter().map(|(id, _)| *id).collect()
4372        }
4373    }
4374
4375    impl BusTap for RecordingTap {
4376        fn on_publish(&self, topic: MStr<Topic>, message: &dyn std::any::Any) {
4377            self.publishes
4378                .borrow_mut()
4379                .push((topic.to_string(), message.type_id()));
4380        }
4381
4382        fn on_send(&self, endpoint: MStr<Endpoint>, message: &dyn std::any::Any) {
4383            self.sends
4384                .borrow_mut()
4385                .push((endpoint.to_string(), message.type_id()));
4386        }
4387
4388        fn on_response(&self, correlation_id: &UUID4, message: &dyn std::any::Any) {
4389            self.responses
4390                .borrow_mut()
4391                .push((*correlation_id, message.type_id()));
4392        }
4393    }
4394
4395    #[rstest]
4396    fn try_publish_any_dispatches_handler_and_tap() {
4397        let msgbus = Rc::new(RefCell::new(MessageBus::default()));
4398        set_message_bus(msgbus.clone());
4399        clear_bus_tap();
4400
4401        let tap = Rc::new(RecordingTap::default());
4402        set_bus_tap(tap.clone());
4403
4404        let topic = "data.any.try.test";
4405        let (handler, checker) = get_call_check_handler(None);
4406        let pub_count = msgbus.borrow().pub_count();
4407        subscribe_any(topic.into(), handler, None);
4408
4409        let payload: u32 = 42;
4410        let published = try_publish_any(topic.into(), &payload);
4411
4412        clear_bus_tap();
4413
4414        assert!(published);
4415        assert!(checker.was_called());
4416        assert_eq!(msgbus.borrow().pub_count(), pub_count + 1);
4417        assert_eq!(tap.publish_topics(), vec![topic]);
4418    }
4419
4420    #[rstest]
4421    fn try_publish_any_without_registered_bus_returns_false() {
4422        let published = thread::spawn(|| {
4423            let payload: u32 = 42;
4424            try_publish_any("data.any.no-bus.test".into(), &payload)
4425        })
4426        .join()
4427        .expect("thread should join");
4428
4429        assert!(!published);
4430    }
4431
4432    #[rstest]
4433    fn try_publish_any_with_borrowed_bus_returns_false_without_tap() {
4434        let msgbus = Rc::new(RefCell::new(MessageBus::default()));
4435        set_message_bus(msgbus.clone());
4436        clear_bus_tap();
4437
4438        let tap = Rc::new(RecordingTap::default());
4439        set_bus_tap(tap.clone());
4440
4441        let bus_borrow = msgbus.borrow_mut();
4442        let payload: u32 = 42;
4443        let published = try_publish_any("data.any.borrowed.test".into(), &payload);
4444        drop(bus_borrow);
4445
4446        clear_bus_tap();
4447
4448        assert!(!published);
4449        assert_eq!(msgbus.borrow().pub_count(), 0);
4450        assert!(tap.publish_topics().is_empty());
4451    }
4452
4453    #[rstest]
4454    fn set_bus_tap_then_publish_typed_invokes_tap() {
4455        let _msgbus = get_message_bus();
4456        let tap = Rc::new(RecordingTap::default());
4457        set_bus_tap(tap.clone());
4458
4459        let quote = QuoteTick::default();
4460        publish_quote("data.quotes.tap.test".into(), &quote);
4461
4462        clear_bus_tap();
4463
4464        assert_eq!(tap.publish_topics(), vec!["data.quotes.tap.test"]);
4465    }
4466
4467    #[rstest]
4468    fn set_bus_tap_then_publish_any_invokes_tap() {
4469        let _msgbus = get_message_bus();
4470        let tap = Rc::new(RecordingTap::default());
4471        set_bus_tap(tap.clone());
4472
4473        let payload: u32 = 42;
4474        publish_any("data.any.tap.test".into(), &payload);
4475
4476        clear_bus_tap();
4477
4478        assert_eq!(tap.publish_topics(), vec!["data.any.tap.test"]);
4479    }
4480
4481    #[rstest]
4482    fn set_bus_tap_then_send_any_value_invokes_tap() {
4483        let _msgbus = get_message_bus();
4484        let tap = Rc::new(RecordingTap::default());
4485        set_bus_tap(tap.clone());
4486
4487        let payload: u32 = 7;
4488        send_any_value("endpoint.send.any.value.test".into(), &payload);
4489
4490        clear_bus_tap();
4491
4492        assert_eq!(tap.send_endpoints(), vec!["endpoint.send.any.value.test"],);
4493    }
4494
4495    #[rstest]
4496    fn send_any_variants_update_tap_and_count_before_handler() {
4497        let msgbus = Rc::new(RefCell::new(MessageBus::default()));
4498        set_message_bus(msgbus.clone());
4499        clear_bus_tap();
4500
4501        let endpoint: MStr<Endpoint> = "endpoint.send.any.order.test".into();
4502        let tap = Rc::new(RecordingTap::default());
4503        set_bus_tap(tap.clone());
4504
4505        let observations = Rc::new(RefCell::new(Vec::new()));
4506        let observations_clone = observations.clone();
4507        let handler = ShareableMessageHandler::from_any(move |message| {
4508            let value = *message.downcast_ref::<u32>().unwrap();
4509            observations_clone.borrow_mut().push((
4510                value,
4511                tap.send_endpoints(),
4512                get_message_bus().borrow().sent_count(),
4513            ));
4514        });
4515        register_any(endpoint, handler);
4516
4517        send_any(endpoint, &11_u32);
4518        send_any_value(endpoint, &22_u32);
4519
4520        clear_bus_tap();
4521
4522        assert_eq!(
4523            *observations.borrow(),
4524            vec![
4525                (11, vec![endpoint.to_string()], 1),
4526                (22, vec![endpoint.to_string(), endpoint.to_string()], 2),
4527            ]
4528        );
4529        assert_eq!(msgbus.borrow().sent_count(), 2);
4530    }
4531
4532    #[rstest]
4533    fn set_bus_tap_then_send_endpoint_owned_invokes_tap() {
4534        // send_trading_command and the other owned send functions reach the tap
4535        // through send_endpoint_owned_counted. Without this site instrumented, real
4536        // production order commands would bypass the audit log.
4537        let _msgbus = get_message_bus();
4538        let tap = Rc::new(RecordingTap::default());
4539        set_bus_tap(tap.clone());
4540
4541        let cancel_all = CancelAllOrders::new(
4542            TraderId::from("TRADER-001"),
4543            Some(ClientId::from("BINANCE")),
4544            StrategyId::from("S-001"),
4545            InstrumentId::from("ETHUSDT-PERP.BINANCE"),
4546            Some(OrderSide::Buy),
4547            UUID4::new(),
4548            nautilus_core::UnixNanos::from(1),
4549            None,
4550            None, // correlation_id
4551        );
4552        send_trading_command(
4553            "endpoint.send.trading.command.test".into(),
4554            TradingCommand::CancelAllOrders(cancel_all),
4555        );
4556
4557        clear_bus_tap();
4558
4559        assert_eq!(
4560            tap.send_endpoints(),
4561            vec!["endpoint.send.trading.command.test"],
4562        );
4563    }
4564
4565    #[rstest]
4566    fn set_bus_tap_then_send_endpoint_ref_invokes_tap() {
4567        // send_quote and the other typed-reference send functions reach the tap through
4568        // send_endpoint_ref. Mirrors the owned path coverage.
4569        let _msgbus = get_message_bus();
4570        let tap = Rc::new(RecordingTap::default());
4571        set_bus_tap(tap.clone());
4572
4573        let quote = QuoteTick::default();
4574        send_quote("endpoint.send.quote.test".into(), &quote);
4575
4576        clear_bus_tap();
4577
4578        assert_eq!(tap.send_endpoints(), vec!["endpoint.send.quote.test"]);
4579    }
4580
4581    #[rstest]
4582    fn has_quote_endpoint_returns_registration_state() {
4583        let _msgbus = get_message_bus();
4584        let endpoint: MStr<Endpoint> = "endpoint.has.quote.registered".into();
4585
4586        assert!(!has_quote_endpoint(endpoint));
4587
4588        let handler = TypedHandler::from_with_id(endpoint, |_quote: &QuoteTick| {});
4589        register_quote_endpoint(endpoint, handler);
4590
4591        assert!(has_quote_endpoint(endpoint));
4592    }
4593
4594    #[rstest]
4595    fn set_bus_tap_then_send_response_invokes_tap() {
4596        reset_message_bus();
4597        clear_bus_tap();
4598        let msgbus = get_message_bus();
4599        let initial_response_count = msgbus.borrow().res_count();
4600        let tap = Rc::new(RecordingTap::default());
4601        set_bus_tap(tap.clone());
4602
4603        let correlation_id = UUID4::new();
4604        let handler_calls = Rc::new(Cell::new(0));
4605        let handler_calls_clone = handler_calls.clone();
4606        register_response_handler(
4607            &correlation_id,
4608            TypedHandler::from(move |_resp: &DataResponseEnvelope| {
4609                handler_calls_clone.set(handler_calls_clone.get() + 1);
4610            }),
4611        );
4612
4613        let response = DataResponse::Quotes(QuotesResponse {
4614            correlation_id,
4615            client_id: ClientId::new("SIM"),
4616            instrument_ids: vec![InstrumentId::from("TEST.VENUE")],
4617            data: (vec![]).into(),
4618            start: None,
4619            end: None,
4620            ts_init: 0.into(),
4621            params: None,
4622        });
4623        send_response(&correlation_id, &response);
4624        send_response(&correlation_id, &response);
4625
4626        clear_bus_tap();
4627
4628        assert_eq!(handler_calls.get(), 1);
4629        assert_eq!(
4630            tap.response_correlation_ids(),
4631            vec![correlation_id, correlation_id],
4632        );
4633        assert_eq!(msgbus.borrow().res_count(), initial_response_count + 2);
4634        assert!(
4635            msgbus
4636                .borrow()
4637                .get_response_handler(&correlation_id)
4638                .is_none(),
4639        );
4640    }
4641
4642    #[rstest]
4643    fn clear_bus_tap_prevents_subsequent_dispatches_from_invoking_tap() {
4644        let _msgbus = get_message_bus();
4645        let tap = Rc::new(RecordingTap::default());
4646        set_bus_tap(tap.clone());
4647        clear_bus_tap();
4648
4649        let quote = QuoteTick::default();
4650        publish_quote("data.quotes.after.clear".into(), &quote);
4651        send_quote("endpoint.send.after.clear".into(), &quote);
4652
4653        let correlation_id = UUID4::new();
4654        register_response_handler(
4655            &correlation_id,
4656            TypedHandler::from(|_resp: &DataResponseEnvelope| {}),
4657        );
4658        let response = DataResponse::Quotes(QuotesResponse {
4659            correlation_id,
4660            client_id: ClientId::new("SIM"),
4661            instrument_ids: vec![InstrumentId::from("TEST.VENUE")],
4662            data: (vec![]).into(),
4663            start: None,
4664            end: None,
4665            ts_init: 0.into(),
4666            params: None,
4667        });
4668        send_response(&correlation_id, &response);
4669
4670        assert!(tap.publish_topics().is_empty());
4671        assert!(tap.send_endpoints().is_empty());
4672        assert!(tap.response_correlation_ids().is_empty());
4673    }
4674
4675    #[rstest]
4676    fn dispatch_with_no_tap_installed_is_a_noop() {
4677        // A fresh thread starts with BUS_TAP=None; dispatches must not panic and must
4678        // not allocate any tap state. Sanity check that the Option::None branch in
4679        // dispatch_tap_* is hit cleanly.
4680        let _msgbus = get_message_bus();
4681
4682        let quote = QuoteTick::default();
4683        publish_quote("data.quotes.no.tap".into(), &quote);
4684        send_quote("endpoint.no.tap".into(), &quote);
4685    }
4686
4687    struct ReinstallTap;
4688
4689    impl BusTap for ReinstallTap {
4690        fn on_publish(&self, _topic: MStr<Topic>, _message: &dyn std::any::Any) {
4691            // Replace ourselves mid-dispatch; must not deadlock the RefCell
4692            set_bus_tap(Rc::new(NoopTap));
4693        }
4694
4695        fn on_send(&self, _endpoint: MStr<Endpoint>, _message: &dyn std::any::Any) {}
4696    }
4697
4698    struct NoopTap;
4699
4700    impl BusTap for NoopTap {
4701        fn on_publish(&self, _topic: MStr<Topic>, _message: &dyn std::any::Any) {}
4702        fn on_send(&self, _endpoint: MStr<Endpoint>, _message: &dyn std::any::Any) {}
4703    }
4704
4705    #[rstest]
4706    fn reentrant_set_bus_tap_during_dispatch_does_not_panic() {
4707        // dispatch_tap_publish clones the Rc out of BUS_TAP before invoking on_publish,
4708        // so a tap whose on_publish reinstalls a different tap must not panic on the
4709        // cell. The replaced tap stays alive through the cloned Rc until the dispatch
4710        // returns.
4711        let _msgbus = get_message_bus();
4712        set_bus_tap(Rc::new(ReinstallTap));
4713
4714        let quote = QuoteTick::default();
4715        publish_quote("data.quotes.reentrant".into(), &quote);
4716
4717        clear_bus_tap();
4718    }
4719}