Skip to main content

nautilus_common/msgbus/
switchboard.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//! Built-in message bus endpoint, topic, and pattern names.
17//!
18//! The `DataEngine`, `ExecEngine`, and `RiskEngine` command endpoints use a queued entry point
19//! plus a direct dispatch endpoint:
20//!
21//! - `*.queue_execute` is the normal entry point for runtime command producers. It routes through
22//!   the current runner queue or channel before the engine sees the command.
23//! - `*.execute` is the lower-level dispatch point used by runner drains and internal paths that
24//!   intentionally bypass the queue.
25//!
26//! Prefer queued endpoints for runtime command producers unless the caller owns the ordering and
27//! re-entrancy implications of direct dispatch. The risk and execution queued endpoints can fall
28//! back to direct dispatch when no trading command sender is installed.
29
30use std::{fmt::Write, num::NonZeroUsize, sync::OnceLock};
31
32use ahash::AHashMap;
33use nautilus_model::{
34    data::{BarType, DataType, data_type::IDENTIFIER_TOPIC_SUFFIX},
35    identifiers::{
36        ClientId, ClientOrderId, InstrumentId, OptionSeriesId, PositionId, StrategyId, Venue,
37    },
38};
39
40use super::mstr::{Endpoint, MStr, Pattern, Topic};
41use crate::{msgbus::get_message_bus, runner::SystemChannel};
42
43pub const CLOSE_TOPIC: &str = "CLOSE";
44pub const TIME_EVENT_TOPIC: &str = "clock.time_event";
45
46static DATA_QUEUE_COMMAND_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
47static DATA_EXECUTE_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
48static DATA_PROCESS_ANY_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
49static DATA_PROCESS_DATA_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
50static DATA_RESPONSE_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
51static DATA_RESPONSE_TOPIC: OnceLock<MStr<Topic>> = OnceLock::new();
52static TIME_EVENT_TOPIC_MSTR: OnceLock<MStr<Topic>> = OnceLock::new();
53static EXEC_QUEUE_COMMAND_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
54static EXEC_EXECUTE_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
55static EXEC_PROCESS_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
56static EXEC_RECONCILE_REPORT_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
57static RISK_EXECUTE_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
58static RISK_QUEUE_EXECUTE_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
59static RISK_PROCESS_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
60static RISK_EVENTS_TOPIC: OnceLock<MStr<Topic>> = OnceLock::new();
61static ORDER_EMULATOR_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
62static PORTFOLIO_ACCOUNT_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
63static PORTFOLIO_ORDER_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
64static SYSTEM_SHUTDOWN_TOPIC: OnceLock<MStr<Topic>> = OnceLock::new();
65static SUBMISSION_RECOVERY_EXHAUSTED_TOPIC: OnceLock<MStr<Topic>> = OnceLock::new();
66static RECONCILIATION_RAW_ORDER_REPORT_TOPIC: OnceLock<MStr<Topic>> = OnceLock::new();
67static RECONCILIATION_RAW_FILL_REPORT_TOPIC: OnceLock<MStr<Topic>> = OnceLock::new();
68static RECONCILIATION_RAW_POSITION_REPORT_TOPIC: OnceLock<MStr<Topic>> = OnceLock::new();
69
70#[cfg(feature = "defi")]
71static DATA_PROCESS_DEFI_DATA_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
72
73macro_rules! define_switchboard {
74    ($(
75        $field:ident: $key_ty:ty,
76        $method:ident($($arg_name:ident: $arg_ty:ty),*) -> $key_expr:expr,
77        $val_fmt:expr,
78        $($val_args:expr),*
79    );* $(;)?) => {
80        /// Represents a switchboard of built-in messaging endpoint names.
81        #[derive(Clone, Debug)]
82        pub struct MessagingSwitchboard {
83            $(
84                $field: AHashMap<$key_ty, MStr<Topic>>,
85            )*
86            pipeline_topics: AHashMap<MStr<Topic>, MStr<Topic>>,
87            instruments_patterns: AHashMap<Venue, MStr<Pattern>>,
88            book_deltas_patterns: AHashMap<InstrumentId, MStr<Pattern>>,
89            book_depth_patterns: AHashMap<InstrumentId, MStr<Pattern>>,
90            book_snapshots_patterns: AHashMap<(InstrumentId, NonZeroUsize), MStr<Pattern>>,
91            signal_topics: AHashMap<String, MStr<Topic>>,
92            signal_patterns: AHashMap<String, MStr<Pattern>>,
93            #[cfg(feature = "defi")]
94            pub(crate) defi: crate::defi::switchboard::DefiSwitchboard,
95        }
96
97        impl Default for MessagingSwitchboard {
98            /// Creates a new default [`MessagingSwitchboard`] instance.
99            fn default() -> Self {
100                Self {
101                    $(
102                        $field: AHashMap::new(),
103                    )*
104                    pipeline_topics: AHashMap::new(),
105                    instruments_patterns: AHashMap::new(),
106                    book_deltas_patterns: AHashMap::new(),
107                    book_depth_patterns: AHashMap::new(),
108                    book_snapshots_patterns: AHashMap::new(),
109                    signal_topics: AHashMap::new(),
110                    signal_patterns: AHashMap::new(),
111                    #[cfg(feature = "defi")]
112                    defi: crate::defi::switchboard::DefiSwitchboard::default(),
113                }
114            }
115        }
116
117        impl MessagingSwitchboard {
118            // Static endpoints
119
120            /// Queued entry point for `DataEngine` commands.
121            #[inline]
122            #[must_use]
123            pub fn data_engine_queue_execute() -> MStr<Endpoint> {
124                *DATA_QUEUE_COMMAND_ENDPOINT.get_or_init(|| "DataEngine.queue_execute".into())
125            }
126
127            /// Direct dispatch endpoint for `DataEngine` commands.
128            #[inline]
129            #[must_use]
130            pub fn data_engine_execute() -> MStr<Endpoint> {
131                *DATA_EXECUTE_ENDPOINT.get_or_init(|| "DataEngine.execute".into())
132            }
133
134            #[inline]
135            #[must_use]
136            pub fn data_engine_process() -> MStr<Endpoint> {
137                *DATA_PROCESS_ANY_ENDPOINT.get_or_init(|| "DataEngine.process".into())
138            }
139
140            #[inline]
141            #[must_use]
142            pub fn data_engine_process_data() -> MStr<Endpoint> {
143                *DATA_PROCESS_DATA_ENDPOINT.get_or_init(|| "DataEngine.process_data".into())
144            }
145
146            #[cfg(feature = "defi")]
147            #[inline]
148            #[must_use]
149            pub fn data_engine_process_defi_data() -> MStr<Endpoint> {
150                *DATA_PROCESS_DEFI_DATA_ENDPOINT
151                    .get_or_init(|| "DataEngine.process_defi_data".into())
152            }
153
154            #[inline]
155            #[must_use]
156            pub fn data_engine_response() -> MStr<Endpoint> {
157                *DATA_RESPONSE_ENDPOINT.get_or_init(|| "DataEngine.response".into())
158            }
159
160            #[inline]
161            #[must_use]
162            pub fn data_response_topic() -> MStr<Topic> {
163                *DATA_RESPONSE_TOPIC.get_or_init(|| "data.response".into())
164            }
165
166            /// Pub/sub topic used by the event-store tap for fired clock events.
167            #[inline]
168            #[must_use]
169            pub fn time_event_topic() -> MStr<Topic> {
170                *TIME_EVENT_TOPIC_MSTR.get_or_init(|| TIME_EVENT_TOPIC.into())
171            }
172
173            /// Direct dispatch endpoint for `ExecEngine` commands.
174            #[inline]
175            #[must_use]
176            pub fn exec_engine_execute() -> MStr<Endpoint> {
177                *EXEC_EXECUTE_ENDPOINT.get_or_init(|| "ExecEngine.execute".into())
178            }
179
180            /// Queued entry point for `ExecEngine` commands.
181            #[inline]
182            #[must_use]
183            pub fn exec_engine_queue_execute() -> MStr<Endpoint> {
184                *EXEC_QUEUE_COMMAND_ENDPOINT.get_or_init(|| "ExecEngine.queue_execute".into())
185            }
186
187            #[inline]
188            #[must_use]
189            pub fn exec_engine_process() -> MStr<Endpoint> {
190                *EXEC_PROCESS_ENDPOINT.get_or_init(|| "ExecEngine.process".into())
191            }
192
193            #[inline]
194            #[must_use]
195            pub fn exec_engine_reconcile_execution_report() -> MStr<Endpoint> {
196                *EXEC_RECONCILE_REPORT_ENDPOINT.get_or_init(|| "ExecEngine.reconcile_execution_report".into())
197            }
198
199            /// Direct dispatch endpoint for `RiskEngine` commands.
200            #[inline]
201            #[must_use]
202            pub fn risk_engine_execute() -> MStr<Endpoint> {
203                *RISK_EXECUTE_ENDPOINT.get_or_init(|| "RiskEngine.execute".into())
204            }
205
206            /// Queued entry point for `RiskEngine` commands.
207            #[inline]
208            #[must_use]
209            pub fn risk_engine_queue_execute() -> MStr<Endpoint> {
210                *RISK_QUEUE_EXECUTE_ENDPOINT.get_or_init(|| "RiskEngine.queue_execute".into())
211            }
212
213            #[inline]
214            #[must_use]
215            pub fn risk_engine_process() -> MStr<Endpoint> {
216                *RISK_PROCESS_ENDPOINT.get_or_init(|| "RiskEngine.process".into())
217            }
218
219            /// Pub/sub topic carrying risk engine state events.
220            #[inline]
221            #[must_use]
222            pub fn risk_events_topic() -> MStr<Topic> {
223                *RISK_EVENTS_TOPIC.get_or_init(|| "events.risk".into())
224            }
225
226            #[inline]
227            #[must_use]
228            pub fn order_emulator_execute() -> MStr<Endpoint> {
229                *ORDER_EMULATOR_ENDPOINT.get_or_init(|| "OrderEmulator.execute".into())
230            }
231
232            #[inline]
233            #[must_use]
234            pub fn portfolio_update_account() -> MStr<Endpoint> {
235                *PORTFOLIO_ACCOUNT_ENDPOINT.get_or_init(|| "Portfolio.update_account".into())
236            }
237
238            #[inline]
239            #[must_use]
240            pub fn portfolio_update_order() -> MStr<Endpoint> {
241                *PORTFOLIO_ORDER_ENDPOINT.get_or_init(|| "Portfolio.update_order".into())
242            }
243
244            /// Pub/sub topic carrying queue state changes for one runner channel.
245            #[must_use]
246            pub fn queue_state_changed_topic(channel: SystemChannel) -> MStr<Topic> {
247                Self::queue_state_changed_pattern(Some(channel)).as_ref().into()
248            }
249
250            /// Subscription pattern for queue state changes. `None` matches every channel.
251            #[must_use]
252            pub fn queue_state_changed_pattern(channel: Option<SystemChannel>) -> MStr<Pattern> {
253                let channel = channel.map_or_else(|| "*".to_string(), |value| format!("{value:?}"));
254                format!("events.system.QueueStateChanged.{channel}").into()
255            }
256
257            /// Pub/sub topic carrying socket state changes for one client endpoint.
258            #[must_use]
259            pub fn socket_state_changed_topic(client_id: ClientId, endpoint: &str) -> MStr<Topic> {
260                Self::socket_state_changed_pattern(Some(client_id), Some(endpoint)).as_ref().into()
261            }
262
263            /// Subscription pattern for socket state changes.
264            ///
265            /// Each `None` matches every value of that field. Supplied values match literally;
266            /// topic components percent-encode bytes other than ASCII letters, digits, `-`, and `_`.
267            #[must_use]
268            pub fn socket_state_changed_pattern(
269                client_id: Option<ClientId>,
270                endpoint: Option<&str>,
271            ) -> MStr<Pattern> {
272                let client_id = client_id.map_or_else(
273                    || "*".to_string(),
274                    |value| state_topic_component(value.as_str()),
275                );
276                let endpoint = endpoint.map_or_else(|| "*".to_string(), state_topic_component);
277                format!("events.system.SocketStateChanged.{client_id}.{endpoint}").into()
278            }
279
280            /// Pub/sub topic carrying `ShutdownSystem` commands published by
281            /// actors, engines, and strategies.
282            ///
283            /// Matches the Python topic. The kernel subscribes to validate the
284            /// command and signal graceful shutdown; additional components may
285            /// subscribe to react to the same signal.
286            #[inline]
287            #[must_use]
288            pub fn shutdown_system_topic() -> MStr<Topic> {
289                *SYSTEM_SHUTDOWN_TOPIC.get_or_init(|| "commands.system.shutdown".into())
290            }
291
292            /// Pub/sub topic carrying native submission recovery exhaustion diagnostics.
293            #[inline]
294            #[must_use]
295            pub fn submission_recovery_exhausted_topic() -> MStr<Topic> {
296                *SUBMISSION_RECOVERY_EXHAUSTED_TOPIC
297                    .get_or_init(|| "reconciliation.SubmissionRecoveryExhausted".into())
298            }
299
300            /// Pub/sub topic carrying raw `OrderStatusReport`s that arrived from
301            /// a venue client, published by the execution engine at the top of
302            /// reconciliation before any state mutation.
303            ///
304            /// The event store bus tap captures publications on this topic so
305            /// forensic replay can re-run reconciliation against the same raw
306            /// inputs the live engine saw. Subscribers are not expected in
307            /// production; the capture surface is the sole consumer today.
308            #[inline]
309            #[must_use]
310            pub fn reconciliation_raw_order_status_report_topic() -> MStr<Topic> {
311                *RECONCILIATION_RAW_ORDER_REPORT_TOPIC
312                    .get_or_init(|| "reconciliation.raw.OrderStatusReport".into())
313            }
314
315            /// Pub/sub topic carrying raw `FillReport`s that arrived from a
316            /// venue client, published by the execution engine at the top of
317            /// reconciliation before any state mutation.
318            ///
319            /// See [`Self::reconciliation_raw_order_status_report_topic`] for the
320            /// capture contract.
321            #[inline]
322            #[must_use]
323            pub fn reconciliation_raw_fill_report_topic() -> MStr<Topic> {
324                *RECONCILIATION_RAW_FILL_REPORT_TOPIC
325                    .get_or_init(|| "reconciliation.raw.FillReport".into())
326            }
327
328            /// Pub/sub topic carrying raw `PositionStatusReport`s that arrived
329            /// from a venue client, published by the execution engine at the
330            /// top of reconciliation before any state mutation.
331            ///
332            /// See [`Self::reconciliation_raw_order_status_report_topic`] for the
333            /// capture contract.
334            #[inline]
335            #[must_use]
336            pub fn reconciliation_raw_position_status_report_topic() -> MStr<Topic> {
337                *RECONCILIATION_RAW_POSITION_REPORT_TOPIC
338                    .get_or_init(|| "reconciliation.raw.PositionStatusReport".into())
339            }
340
341            /// Returns a wildcard pattern for matching all instrument topics for a venue.
342            #[must_use]
343            pub fn instruments_pattern(&mut self, venue: Venue) -> MStr<Pattern> {
344                *self.instruments_patterns
345                    .entry(venue)
346                    .or_insert_with(|| format!("data.instrument.{venue}.*").into())
347            }
348
349            /// Returns the exact signal publish topic for `name`
350            /// (`data.Signal<TitleName>`).
351            ///
352            /// The title-cased encoding mirrors the v1 Python convention so
353            /// subscribers keyed on either a specific name or the global
354            /// `data.Signal*` wildcard receive published signals.
355            #[must_use]
356            pub fn signal_topic(&mut self, name: &str) -> MStr<Topic> {
357                *self
358                    .signal_topics
359                    .entry(name.to_string())
360                    .or_insert_with(|| {
361                        format!(
362                            "data.Signal{}",
363                            nautilus_core::string::conversions::title_case(name)
364                        )
365                        .into()
366                    })
367            }
368
369            /// Returns the subscription pattern for `name`
370            /// (`data.Signal<TitleName>*`).
371            ///
372            /// An empty `name` yields the wildcard `data.Signal*` that matches
373            /// every signal topic.
374            #[must_use]
375            pub fn signal_pattern(&mut self, name: &str) -> MStr<Pattern> {
376                *self
377                    .signal_patterns
378                    .entry(name.to_string())
379                    .or_insert_with(|| {
380                        format!(
381                            "data.Signal{}*",
382                            nautilus_core::string::conversions::title_case(name)
383                        )
384                        .into()
385                    })
386            }
387
388            // Dynamic topics
389            $(
390                #[must_use]
391                pub fn $method(&mut self, $($arg_name: $arg_ty),*) -> MStr<Topic> {
392                    let key = $key_expr;
393                    *self.$field
394                        .entry(key)
395                        .or_insert_with(|| format!($val_fmt, $($val_args),*).into())
396                }
397            )*
398        }
399    };
400}
401
402define_switchboard! {
403    custom_topics: DataType,
404    get_custom_topic(data_type: &DataType) -> data_type.clone(),
405    "data.{}", data_type.topic();
406
407    instruments_topics: Venue,
408    get_instruments_topic(venue: Venue) -> venue,
409    "data.instrument.{}", venue;
410
411    instrument_topics: InstrumentId,
412    get_instrument_topic(instrument_id: InstrumentId) -> instrument_id,
413    "data.instrument.{}.{}", instrument_id.venue, instrument_id.symbol;
414
415    book_deltas_topics: InstrumentId,
416    get_book_deltas_topic(instrument_id: InstrumentId) -> instrument_id,
417    "data.book.deltas.{}.{}", instrument_id.venue, instrument_id.symbol;
418
419    book_depth_topics: InstrumentId,
420    get_book_depth_topic(instrument_id: InstrumentId) -> instrument_id,
421    "data.book.depth.{}.{}", instrument_id.venue, instrument_id.symbol;
422
423    book_snapshots_topics: (InstrumentId, NonZeroUsize),
424    get_book_snapshots_topic(instrument_id: InstrumentId, interval_ms: NonZeroUsize) -> (instrument_id, interval_ms),
425    "data.book.snapshots.{}.{}.{}", instrument_id.venue, instrument_id.symbol, interval_ms;
426
427    quote_topics: InstrumentId,
428    get_quotes_topic(instrument_id: InstrumentId) -> instrument_id,
429    "data.quotes.{}.{}", instrument_id.venue, instrument_id.symbol;
430
431    trade_topics: InstrumentId,
432    get_trades_topic(instrument_id: InstrumentId) -> instrument_id,
433    "data.trades.{}.{}", instrument_id.venue, instrument_id.symbol;
434
435    bar_topics: BarType,
436    get_bars_topic(bar_type: BarType) -> bar_type,
437    "data.bars.{}", bar_type;
438
439    mark_price_topics: InstrumentId,
440    get_mark_price_topic(instrument_id: InstrumentId) -> instrument_id,
441    "data.mark_prices.{}.{}", instrument_id.venue, instrument_id.symbol;
442
443    index_price_topics: InstrumentId,
444    get_index_price_topic(instrument_id: InstrumentId) -> instrument_id,
445    "data.index_prices.{}.{}", instrument_id.venue, instrument_id.symbol;
446
447    funding_rate_topics: InstrumentId,
448    get_funding_rate_topic(instrument_id: InstrumentId) -> instrument_id,
449    "data.funding_rates.{}.{}", instrument_id.venue, instrument_id.symbol;
450
451    funding_settlement_topics: InstrumentId,
452    get_funding_settlement_topic(instrument_id: InstrumentId) -> instrument_id,
453    "events.funding_settlements.{}.{}", instrument_id.venue, instrument_id.symbol;
454
455    instrument_status_topics: InstrumentId,
456    get_instrument_status_topic(instrument_id: InstrumentId) -> instrument_id,
457    "data.status.{}.{}", instrument_id.venue, instrument_id.symbol;
458
459    instrument_close_topics: InstrumentId,
460    get_instrument_close_topic(instrument_id: InstrumentId) -> instrument_id,
461    "data.close.{}.{}", instrument_id.venue, instrument_id.symbol;
462
463    option_greeks_topics: InstrumentId,
464    get_option_greeks_topic(instrument_id: InstrumentId) -> instrument_id,
465    "data.option_greeks.{}.{}", instrument_id.venue, instrument_id.symbol;
466
467    option_chain_topics: OptionSeriesId,
468    get_option_chain_topic(series_id: OptionSeriesId) -> series_id,
469    "data.option_chain.{}", series_id;
470
471    order_submitted_topics: InstrumentId,
472    get_order_submitted_topic(instrument_id: InstrumentId) -> instrument_id,
473    "events.order_submitted.{}", instrument_id;
474
475    order_rejected_topics: InstrumentId,
476    get_order_rejected_topic(instrument_id: InstrumentId) -> instrument_id,
477    "events.order_rejected.{}", instrument_id;
478
479    order_pending_update_topics: InstrumentId,
480    get_order_pending_update_topic(instrument_id: InstrumentId) -> instrument_id,
481    "events.order_pending_update.{}", instrument_id;
482
483    order_pending_cancel_topics: InstrumentId,
484    get_order_pending_cancel_topic(instrument_id: InstrumentId) -> instrument_id,
485    "events.order_pending_cancel.{}", instrument_id;
486
487    order_modify_denied_topics: InstrumentId,
488    get_order_modify_denied_topic(instrument_id: InstrumentId) -> instrument_id,
489    "events.order_modify_denied.{}", instrument_id;
490
491    order_modify_rejected_topics: InstrumentId,
492    get_order_modify_rejected_topic(instrument_id: InstrumentId) -> instrument_id,
493    "events.order_modify_rejected.{}", instrument_id;
494
495    order_cancel_denied_topics: InstrumentId,
496    get_order_cancel_denied_topic(instrument_id: InstrumentId) -> instrument_id,
497    "events.order_cancel_denied.{}", instrument_id;
498
499    order_cancel_rejected_topics: InstrumentId,
500    get_order_cancel_rejected_topic(instrument_id: InstrumentId) -> instrument_id,
501    "events.order_cancel_rejected.{}", instrument_id;
502
503    order_canceled_topics: InstrumentId,
504    get_order_canceled_topic(instrument_id: InstrumentId) -> instrument_id,
505    "events.order_canceled.{}", instrument_id;
506
507    order_filled_topics: InstrumentId,
508    get_order_filled_topic(instrument_id: InstrumentId) -> instrument_id,
509    "events.order_filled.{}", instrument_id;
510
511    order_fill_voided_topics: InstrumentId,
512    get_order_fill_voided_topic(instrument_id: InstrumentId) -> instrument_id,
513    "events.order_fill_voided.{}", instrument_id;
514
515    order_fill_declined_topics: InstrumentId,
516    get_order_fill_declined_topic(instrument_id: InstrumentId) -> instrument_id,
517    "events.order_fill_declined.{}", instrument_id;
518
519    event_order_topics: StrategyId,
520    get_event_order_topic(strategy_id: StrategyId) -> strategy_id,
521    "events.order.{}", strategy_id;
522
523    event_position_topics: StrategyId,
524    get_event_position_topic(strategy_id: StrategyId) -> strategy_id,
525    "events.position.{}", strategy_id;
526
527    snapshot_order_topics: ClientOrderId,
528    get_snapshot_order_topic(client_order_id: ClientOrderId) -> client_order_id,
529    "snapshots.order.{}", client_order_id;
530
531    snapshot_position_topics: PositionId,
532    get_snapshot_position_topic(position_id: PositionId) -> position_id,
533    "snapshots.position.{}", position_id;
534
535}
536
537impl MessagingSwitchboard {
538    #[inline]
539    fn pipeline_topic(&mut self, live: MStr<Topic>) -> MStr<Topic> {
540        *self.pipeline_topics.entry(live).or_insert_with(|| {
541            let live = live.as_ref();
542            let suffix = live
543                .strip_prefix("data.")
544                .expect("live data topic must start with data.");
545            MStr::<Topic>::from(format!("data.pipeline.{suffix}"))
546        })
547    }
548
549    #[must_use]
550    pub fn get_pipeline_custom_topic(&mut self, data_type: &DataType) -> MStr<Topic> {
551        let live = self.get_custom_topic(data_type);
552        self.pipeline_topic(live)
553    }
554
555    #[must_use]
556    pub fn get_pipeline_book_deltas_topic(&mut self, instrument_id: InstrumentId) -> MStr<Topic> {
557        let live = self.get_book_deltas_topic(instrument_id);
558        self.pipeline_topic(live)
559    }
560
561    #[must_use]
562    pub fn get_pipeline_book_depth_topic(&mut self, instrument_id: InstrumentId) -> MStr<Topic> {
563        let live = self.get_book_depth_topic(instrument_id);
564        self.pipeline_topic(live)
565    }
566
567    #[must_use]
568    pub fn get_pipeline_quotes_topic(&mut self, instrument_id: InstrumentId) -> MStr<Topic> {
569        let live = self.get_quotes_topic(instrument_id);
570        self.pipeline_topic(live)
571    }
572
573    #[must_use]
574    pub fn get_pipeline_trades_topic(&mut self, instrument_id: InstrumentId) -> MStr<Topic> {
575        let live = self.get_trades_topic(instrument_id);
576        self.pipeline_topic(live)
577    }
578
579    #[must_use]
580    pub fn get_pipeline_bars_topic(&mut self, bar_type: BarType) -> MStr<Topic> {
581        let live = self.get_bars_topic(bar_type);
582        self.pipeline_topic(live)
583    }
584
585    #[must_use]
586    pub fn get_pipeline_mark_price_topic(&mut self, instrument_id: InstrumentId) -> MStr<Topic> {
587        let live = self.get_mark_price_topic(instrument_id);
588        self.pipeline_topic(live)
589    }
590
591    #[must_use]
592    pub fn get_pipeline_index_price_topic(&mut self, instrument_id: InstrumentId) -> MStr<Topic> {
593        let live = self.get_index_price_topic(instrument_id);
594        self.pipeline_topic(live)
595    }
596
597    #[must_use]
598    pub fn get_pipeline_funding_rate_topic(&mut self, instrument_id: InstrumentId) -> MStr<Topic> {
599        let live = self.get_funding_rate_topic(instrument_id);
600        self.pipeline_topic(live)
601    }
602
603    #[must_use]
604    pub fn get_pipeline_instrument_status_topic(
605        &mut self,
606        instrument_id: InstrumentId,
607    ) -> MStr<Topic> {
608        let live = self.get_instrument_status_topic(instrument_id);
609        self.pipeline_topic(live)
610    }
611
612    #[must_use]
613    pub fn get_pipeline_option_greeks_topic(&mut self, instrument_id: InstrumentId) -> MStr<Topic> {
614        let live = self.get_option_greeks_topic(instrument_id);
615        self.pipeline_topic(live)
616    }
617
618    #[must_use]
619    pub fn get_pipeline_instrument_close_topic(
620        &mut self,
621        instrument_id: InstrumentId,
622    ) -> MStr<Topic> {
623        let live = self.get_instrument_close_topic(instrument_id);
624        self.pipeline_topic(live)
625    }
626
627    /// Returns the subscription pattern for order book deltas on `instrument_id`.
628    #[must_use]
629    pub fn get_book_deltas_pattern(&mut self, instrument_id: InstrumentId) -> MStr<Pattern> {
630        *self
631            .book_deltas_patterns
632            .entry(instrument_id)
633            .or_insert_with(|| {
634                format!(
635                    "data.book.deltas.{}.{}",
636                    instrument_id.venue,
637                    instrument_id.symbol.topic(),
638                )
639                .into()
640            })
641    }
642
643    /// Returns the subscription pattern for order book depth snapshots on `instrument_id`.
644    #[must_use]
645    pub fn get_book_depth_pattern(&mut self, instrument_id: InstrumentId) -> MStr<Pattern> {
646        *self
647            .book_depth_patterns
648            .entry(instrument_id)
649            .or_insert_with(|| {
650                format!(
651                    "data.book.depth.{}.{}",
652                    instrument_id.venue,
653                    instrument_id.symbol.topic(),
654                )
655                .into()
656            })
657    }
658
659    /// Returns the subscription pattern for periodic order book snapshots on `instrument_id`.
660    #[must_use]
661    pub fn get_book_snapshots_pattern(
662        &mut self,
663        instrument_id: InstrumentId,
664        interval_ms: NonZeroUsize,
665    ) -> MStr<Pattern> {
666        *self
667            .book_snapshots_patterns
668            .entry((instrument_id, interval_ms))
669            .or_insert_with(|| {
670                format!(
671                    "data.book.snapshots.{}.{}.{}",
672                    instrument_id.venue,
673                    instrument_id.symbol.topic(),
674                    interval_ms,
675                )
676                .into()
677            })
678    }
679}
680
681macro_rules! define_wrappers {
682    ($($method:ident($($arg_name:ident: $arg_ty:ty),*) -> $ret:ty),* $(,)?) => {
683        $(
684            #[must_use]
685            pub fn $method($($arg_name: $arg_ty),*) -> $ret {
686                get_message_bus()
687                    .borrow_mut()
688                    .switchboard
689                    .$method($($arg_name),*)
690            }
691        )*
692    }
693}
694
695define_wrappers! {
696    get_custom_topic(data_type: &DataType) -> MStr<Topic>,
697    get_instruments_topic(venue: Venue) -> MStr<Topic>,
698    get_instrument_topic(instrument_id: InstrumentId) -> MStr<Topic>,
699    get_book_deltas_topic(instrument_id: InstrumentId) -> MStr<Topic>,
700    get_book_depth_topic(instrument_id: InstrumentId) -> MStr<Topic>,
701    get_book_snapshots_topic(instrument_id: InstrumentId, interval_ms: NonZeroUsize) -> MStr<Topic>,
702    get_quotes_topic(instrument_id: InstrumentId) -> MStr<Topic>,
703    get_trades_topic(instrument_id: InstrumentId) -> MStr<Topic>,
704    get_bars_topic(bar_type: BarType) -> MStr<Topic>,
705    get_mark_price_topic(instrument_id: InstrumentId) -> MStr<Topic>,
706    get_index_price_topic(instrument_id: InstrumentId) -> MStr<Topic>,
707    get_funding_rate_topic(instrument_id: InstrumentId) -> MStr<Topic>,
708    get_funding_settlement_topic(instrument_id: InstrumentId) -> MStr<Topic>,
709    get_instrument_status_topic(instrument_id: InstrumentId) -> MStr<Topic>,
710    get_instrument_close_topic(instrument_id: InstrumentId) -> MStr<Topic>,
711    get_option_greeks_topic(instrument_id: InstrumentId) -> MStr<Topic>,
712    get_option_chain_topic(series_id: OptionSeriesId) -> MStr<Topic>,
713    get_pipeline_custom_topic(data_type: &DataType) -> MStr<Topic>,
714    get_pipeline_book_deltas_topic(instrument_id: InstrumentId) -> MStr<Topic>,
715    get_pipeline_book_depth_topic(instrument_id: InstrumentId) -> MStr<Topic>,
716    get_pipeline_quotes_topic(instrument_id: InstrumentId) -> MStr<Topic>,
717    get_pipeline_trades_topic(instrument_id: InstrumentId) -> MStr<Topic>,
718    get_pipeline_bars_topic(bar_type: BarType) -> MStr<Topic>,
719    get_pipeline_mark_price_topic(instrument_id: InstrumentId) -> MStr<Topic>,
720    get_pipeline_index_price_topic(instrument_id: InstrumentId) -> MStr<Topic>,
721    get_pipeline_funding_rate_topic(instrument_id: InstrumentId) -> MStr<Topic>,
722    get_pipeline_instrument_status_topic(instrument_id: InstrumentId) -> MStr<Topic>,
723    get_pipeline_option_greeks_topic(instrument_id: InstrumentId) -> MStr<Topic>,
724    get_pipeline_instrument_close_topic(instrument_id: InstrumentId) -> MStr<Topic>,
725    get_order_submitted_topic(instrument_id: InstrumentId) -> MStr<Topic>,
726    get_order_rejected_topic(instrument_id: InstrumentId) -> MStr<Topic>,
727    get_order_pending_update_topic(instrument_id: InstrumentId) -> MStr<Topic>,
728    get_order_pending_cancel_topic(instrument_id: InstrumentId) -> MStr<Topic>,
729    get_order_modify_denied_topic(instrument_id: InstrumentId) -> MStr<Topic>,
730    get_order_modify_rejected_topic(instrument_id: InstrumentId) -> MStr<Topic>,
731    get_order_cancel_denied_topic(instrument_id: InstrumentId) -> MStr<Topic>,
732    get_order_cancel_rejected_topic(instrument_id: InstrumentId) -> MStr<Topic>,
733    get_order_canceled_topic(instrument_id: InstrumentId) -> MStr<Topic>,
734    get_order_filled_topic(instrument_id: InstrumentId) -> MStr<Topic>,
735    get_order_fill_voided_topic(instrument_id: InstrumentId) -> MStr<Topic>,
736    get_order_fill_declined_topic(instrument_id: InstrumentId) -> MStr<Topic>,
737    get_snapshot_order_topic(client_order_id: ClientOrderId) -> MStr<Topic>,
738    get_snapshot_position_topic(position_id: PositionId) -> MStr<Topic>,
739    get_event_order_topic(strategy_id: StrategyId) -> MStr<Topic>,
740    get_event_position_topic(strategy_id: StrategyId) -> MStr<Topic>,
741}
742
743/// Returns a wildcard subscription pattern that matches all instrument topics
744/// for the given `venue`.
745///
746/// For example, venue `BINANCE` produces pattern `data.instrument.BINANCE.*`,
747/// which matches per-instrument topics like `data.instrument.BINANCE.BTCUSDT`.
748#[must_use]
749pub fn get_instruments_pattern(venue: Venue) -> MStr<Pattern> {
750    get_message_bus()
751        .borrow_mut()
752        .switchboard
753        .instruments_pattern(venue)
754}
755
756/// Returns the subscription pattern for order book deltas on `instrument_id`.
757#[must_use]
758pub fn get_book_deltas_pattern(instrument_id: InstrumentId) -> MStr<Pattern> {
759    get_message_bus()
760        .borrow_mut()
761        .switchboard
762        .get_book_deltas_pattern(instrument_id)
763}
764
765/// Returns the subscription pattern for order book depth snapshots on `instrument_id`.
766#[must_use]
767pub fn get_book_depth_pattern(instrument_id: InstrumentId) -> MStr<Pattern> {
768    get_message_bus()
769        .borrow_mut()
770        .switchboard
771        .get_book_depth_pattern(instrument_id)
772}
773
774/// Returns the subscription pattern for periodic order book snapshots on `instrument_id`.
775#[must_use]
776pub fn get_book_snapshots_pattern(
777    instrument_id: InstrumentId,
778    interval_ms: NonZeroUsize,
779) -> MStr<Pattern> {
780    get_message_bus()
781        .borrow_mut()
782        .switchboard
783        .get_book_snapshots_pattern(instrument_id, interval_ms)
784}
785
786/// Returns the exact signal publish topic for `name` (`data.Signal<TitleName>`).
787#[must_use]
788pub fn get_signal_topic(name: &str) -> MStr<Topic> {
789    get_message_bus()
790        .borrow_mut()
791        .switchboard
792        .signal_topic(name)
793}
794
795/// Returns the signal subscription pattern for `name` (`data.Signal<TitleName>*`).
796///
797/// An empty `name` yields the wildcard `data.Signal*` matching every signal topic.
798#[must_use]
799pub fn get_signal_pattern(name: &str) -> MStr<Pattern> {
800    get_message_bus()
801        .borrow_mut()
802        .switchboard
803        .signal_pattern(name)
804}
805
806/// Returns subscriptions for a custom data type and its optional identifier scope.
807#[must_use]
808pub fn get_custom_subscription_topics(data_type: &DataType) -> Vec<MStr<Pattern>> {
809    let topic = get_custom_topic(data_type);
810    let mut topics = vec![topic.into()];
811    if data_type.identifier().is_none() {
812        topics.push(MStr::pattern(format!("{topic}{IDENTIFIER_TOPIC_SUFFIX}*")));
813    }
814    topics
815}
816
817fn state_topic_component(value: &str) -> String {
818    let mut encoded = String::with_capacity(value.len());
819    for byte in value.bytes() {
820        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_') {
821            encoded.push(char::from(byte));
822        } else {
823            write!(encoded, "%{byte:02X}").expect("String formatting cannot fail");
824        }
825    }
826
827    encoded
828}
829
830#[cfg(test)]
831mod tests {
832    use nautilus_model::{
833        data::{BarType, DataType},
834        identifiers::{InstrumentId, Venue},
835    };
836    use rstest::*;
837
838    use super::*;
839    use crate::msgbus::matching::is_matching_backtracking;
840
841    #[fixture]
842    fn switchboard() -> MessagingSwitchboard {
843        MessagingSwitchboard::default()
844    }
845
846    #[fixture]
847    fn instrument_id() -> InstrumentId {
848        InstrumentId::from("ESZ24.XCME")
849    }
850
851    #[rstest]
852    fn test_data_response_topic() {
853        let expected_topic = "data.response".into();
854        let result = MessagingSwitchboard::data_response_topic();
855        assert_eq!(result, expected_topic);
856    }
857
858    #[rstest]
859    fn test_time_event_topic() {
860        let expected_topic = "clock.time_event".into();
861        let result = MessagingSwitchboard::time_event_topic();
862        assert_eq!(result, expected_topic);
863    }
864
865    #[rstest]
866    fn test_reconciliation_raw_order_status_report_topic() {
867        let expected_topic = "reconciliation.raw.OrderStatusReport".into();
868        let result = MessagingSwitchboard::reconciliation_raw_order_status_report_topic();
869        assert_eq!(result, expected_topic);
870    }
871
872    #[rstest]
873    fn test_reconciliation_raw_fill_report_topic() {
874        let expected_topic = "reconciliation.raw.FillReport".into();
875        let result = MessagingSwitchboard::reconciliation_raw_fill_report_topic();
876        assert_eq!(result, expected_topic);
877    }
878
879    #[rstest]
880    fn test_reconciliation_raw_position_status_report_topic() {
881        let expected_topic = "reconciliation.raw.PositionStatusReport".into();
882        let result = MessagingSwitchboard::reconciliation_raw_position_status_report_topic();
883        assert_eq!(result, expected_topic);
884    }
885
886    #[rstest]
887    fn test_get_custom_topic(mut switchboard: MessagingSwitchboard) {
888        let data_type = DataType::new("ExampleDataType", None, None);
889        let expected_topic = "data.ExampleDataType".into();
890        let result = switchboard.get_custom_topic(&data_type);
891        assert_eq!(result, expected_topic);
892        assert!(switchboard.custom_topics.contains_key(&data_type));
893    }
894
895    #[rstest]
896    fn test_get_instrument_topic(
897        mut switchboard: MessagingSwitchboard,
898        instrument_id: InstrumentId,
899    ) {
900        let expected_topic = "data.instrument.XCME.ESZ24".into();
901        let result = switchboard.get_instrument_topic(instrument_id);
902        assert_eq!(result, expected_topic);
903        assert!(switchboard.instrument_topics.contains_key(&instrument_id));
904    }
905
906    #[rstest]
907    fn test_get_book_deltas_topic(
908        mut switchboard: MessagingSwitchboard,
909        instrument_id: InstrumentId,
910    ) {
911        let expected_topic = "data.book.deltas.XCME.ESZ24".into();
912        let result = switchboard.get_book_deltas_topic(instrument_id);
913        assert_eq!(result, expected_topic);
914        assert!(switchboard.book_deltas_topics.contains_key(&instrument_id));
915    }
916
917    #[rstest]
918    fn test_get_book_depth_topic(
919        mut switchboard: MessagingSwitchboard,
920        instrument_id: InstrumentId,
921    ) {
922        let expected_topic = "data.book.depth.XCME.ESZ24".into();
923        let result = switchboard.get_book_depth_topic(instrument_id);
924        assert_eq!(result, expected_topic);
925        assert!(switchboard.book_depth_topics.contains_key(&instrument_id));
926    }
927
928    #[rstest]
929    fn test_get_book_snapshots_topic(
930        mut switchboard: MessagingSwitchboard,
931        instrument_id: InstrumentId,
932    ) {
933        let expected_topic = "data.book.snapshots.XCME.ESZ24.1000".into();
934        let interval_ms = NonZeroUsize::new(1000).unwrap();
935        let result = switchboard.get_book_snapshots_topic(instrument_id, interval_ms);
936        assert_eq!(result, expected_topic);
937
938        assert!(
939            switchboard
940                .book_snapshots_topics
941                .contains_key(&(instrument_id, interval_ms))
942        );
943    }
944
945    #[rstest]
946    fn test_get_quotes_topic(mut switchboard: MessagingSwitchboard, instrument_id: InstrumentId) {
947        let expected_topic = "data.quotes.XCME.ESZ24".into();
948        let result = switchboard.get_quotes_topic(instrument_id);
949        assert_eq!(result, expected_topic);
950        assert!(switchboard.quote_topics.contains_key(&instrument_id));
951    }
952
953    #[rstest]
954    fn test_get_trades_topic(mut switchboard: MessagingSwitchboard, instrument_id: InstrumentId) {
955        let expected_topic = "data.trades.XCME.ESZ24".into();
956        let result = switchboard.get_trades_topic(instrument_id);
957        assert_eq!(result, expected_topic);
958        assert!(switchboard.trade_topics.contains_key(&instrument_id));
959    }
960
961    #[rstest]
962    fn test_get_bars_topic(mut switchboard: MessagingSwitchboard) {
963        let bar_type = BarType::from("ESZ24.XCME-1-MINUTE-LAST-INTERNAL");
964        let expected_topic = format!("data.bars.{bar_type}").into();
965        let result = switchboard.get_bars_topic(bar_type);
966        assert_eq!(result, expected_topic);
967        assert!(switchboard.bar_topics.contains_key(&bar_type));
968    }
969
970    #[rstest]
971    fn test_get_pipeline_custom_topic(mut switchboard: MessagingSwitchboard) {
972        let data_type = DataType::new("ExampleDataType", None, None);
973        let expected_topic = "data.pipeline.ExampleDataType".into();
974        let result = switchboard.get_pipeline_custom_topic(&data_type);
975        assert_eq!(result, expected_topic);
976        assert!(switchboard.custom_topics.contains_key(&data_type));
977        assert_eq!(switchboard.pipeline_topics.len(), 1);
978    }
979
980    type PipelineInstrumentIdTopicFn = fn(&mut MessagingSwitchboard, InstrumentId) -> MStr<Topic>;
981
982    #[rstest]
983    #[case::book_deltas(
984        MessagingSwitchboard::get_pipeline_book_deltas_topic as PipelineInstrumentIdTopicFn,
985        "data.pipeline.book.deltas.XCME.ESZ24",
986    )]
987    #[case::book_depth(
988        MessagingSwitchboard::get_pipeline_book_depth_topic as PipelineInstrumentIdTopicFn,
989        "data.pipeline.book.depth.XCME.ESZ24",
990    )]
991    #[case::quotes(
992        MessagingSwitchboard::get_pipeline_quotes_topic as PipelineInstrumentIdTopicFn,
993        "data.pipeline.quotes.XCME.ESZ24",
994    )]
995    #[case::trades(
996        MessagingSwitchboard::get_pipeline_trades_topic as PipelineInstrumentIdTopicFn,
997        "data.pipeline.trades.XCME.ESZ24",
998    )]
999    #[case::mark_prices(
1000        MessagingSwitchboard::get_pipeline_mark_price_topic as PipelineInstrumentIdTopicFn,
1001        "data.pipeline.mark_prices.XCME.ESZ24",
1002    )]
1003    #[case::index_prices(
1004        MessagingSwitchboard::get_pipeline_index_price_topic as PipelineInstrumentIdTopicFn,
1005        "data.pipeline.index_prices.XCME.ESZ24",
1006    )]
1007    #[case::funding_rates(
1008        MessagingSwitchboard::get_pipeline_funding_rate_topic as PipelineInstrumentIdTopicFn,
1009        "data.pipeline.funding_rates.XCME.ESZ24",
1010    )]
1011    #[case::status(
1012        MessagingSwitchboard::get_pipeline_instrument_status_topic as PipelineInstrumentIdTopicFn,
1013        "data.pipeline.status.XCME.ESZ24",
1014    )]
1015    #[case::close(
1016        MessagingSwitchboard::get_pipeline_instrument_close_topic as PipelineInstrumentIdTopicFn,
1017        "data.pipeline.close.XCME.ESZ24",
1018    )]
1019    fn test_get_pipeline_instrument_id_topic(
1020        mut switchboard: MessagingSwitchboard,
1021        instrument_id: InstrumentId,
1022        #[case] topic_fn: PipelineInstrumentIdTopicFn,
1023        #[case] expected: &str,
1024    ) {
1025        let result = topic_fn(&mut switchboard, instrument_id);
1026        assert_eq!(result.as_ref(), expected);
1027        assert_eq!(switchboard.pipeline_topics.len(), 1);
1028    }
1029
1030    #[rstest]
1031    fn test_get_pipeline_bars_topic(mut switchboard: MessagingSwitchboard) {
1032        let bar_type = BarType::from("ESZ24.XCME-1-MINUTE-LAST-INTERNAL");
1033        let expected_topic = format!("data.pipeline.bars.{bar_type}").into();
1034        let result = switchboard.get_pipeline_bars_topic(bar_type);
1035        assert_eq!(result, expected_topic);
1036        assert!(switchboard.bar_topics.contains_key(&bar_type));
1037        assert_eq!(switchboard.pipeline_topics.len(), 1);
1038    }
1039
1040    type OrderEventTopicFn = fn(&mut MessagingSwitchboard, InstrumentId) -> MStr<Topic>;
1041
1042    #[rstest]
1043    #[case::submitted(
1044        MessagingSwitchboard::get_order_submitted_topic as OrderEventTopicFn,
1045        "events.order_submitted.ESZ24.XCME",
1046    )]
1047    #[case::rejected(
1048        MessagingSwitchboard::get_order_rejected_topic as OrderEventTopicFn,
1049        "events.order_rejected.ESZ24.XCME",
1050    )]
1051    #[case::pending_update(
1052        MessagingSwitchboard::get_order_pending_update_topic as OrderEventTopicFn,
1053        "events.order_pending_update.ESZ24.XCME",
1054    )]
1055    #[case::pending_cancel(
1056        MessagingSwitchboard::get_order_pending_cancel_topic as OrderEventTopicFn,
1057        "events.order_pending_cancel.ESZ24.XCME",
1058    )]
1059    #[case::modify_rejected(
1060        MessagingSwitchboard::get_order_modify_rejected_topic as OrderEventTopicFn,
1061        "events.order_modify_rejected.ESZ24.XCME",
1062    )]
1063    #[case::cancel_rejected(
1064        MessagingSwitchboard::get_order_cancel_rejected_topic as OrderEventTopicFn,
1065        "events.order_cancel_rejected.ESZ24.XCME",
1066    )]
1067    #[case::canceled(
1068        MessagingSwitchboard::get_order_canceled_topic as OrderEventTopicFn,
1069        "events.order_canceled.ESZ24.XCME",
1070    )]
1071    #[case::filled(
1072        MessagingSwitchboard::get_order_filled_topic as OrderEventTopicFn,
1073        "events.order_filled.ESZ24.XCME",
1074    )]
1075    #[case::fill_voided(
1076        MessagingSwitchboard::get_order_fill_voided_topic as OrderEventTopicFn,
1077        "events.order_fill_voided.ESZ24.XCME",
1078    )]
1079    fn test_get_order_event_topic(
1080        mut switchboard: MessagingSwitchboard,
1081        instrument_id: InstrumentId,
1082        #[case] topic_fn: OrderEventTopicFn,
1083        #[case] expected: &str,
1084    ) {
1085        let result = topic_fn(&mut switchboard, instrument_id);
1086        assert_eq!(result.as_ref(), expected);
1087    }
1088
1089    #[rstest]
1090    #[case::submitted(MessagingSwitchboard::get_order_submitted_topic as OrderEventTopicFn)]
1091    #[case::rejected(MessagingSwitchboard::get_order_rejected_topic as OrderEventTopicFn)]
1092    #[case::pending_update(MessagingSwitchboard::get_order_pending_update_topic as OrderEventTopicFn)]
1093    #[case::pending_cancel(MessagingSwitchboard::get_order_pending_cancel_topic as OrderEventTopicFn)]
1094    #[case::modify_denied(MessagingSwitchboard::get_order_modify_denied_topic as OrderEventTopicFn)]
1095    #[case::modify_rejected(MessagingSwitchboard::get_order_modify_rejected_topic as OrderEventTopicFn)]
1096    #[case::cancel_denied(MessagingSwitchboard::get_order_cancel_denied_topic as OrderEventTopicFn)]
1097    #[case::cancel_rejected(MessagingSwitchboard::get_order_cancel_rejected_topic as OrderEventTopicFn)]
1098    #[case::canceled(MessagingSwitchboard::get_order_canceled_topic as OrderEventTopicFn)]
1099    #[case::filled(MessagingSwitchboard::get_order_filled_topic as OrderEventTopicFn)]
1100    #[case::fill_voided(MessagingSwitchboard::get_order_fill_voided_topic as OrderEventTopicFn)]
1101    fn test_order_event_topic_does_not_match_strategy_order_pattern(
1102        mut switchboard: MessagingSwitchboard,
1103        instrument_id: InstrumentId,
1104        #[case] topic_fn: OrderEventTopicFn,
1105    ) {
1106        let topic = topic_fn(&mut switchboard, instrument_id);
1107        assert!(!is_matching_backtracking(topic, "events.order.*".into()));
1108    }
1109
1110    #[rstest]
1111    fn test_get_snapshot_order_topic(mut switchboard: MessagingSwitchboard) {
1112        let client_order_id = ClientOrderId::from("O-123456789");
1113        let expected_topic = format!("snapshots.order.{client_order_id}").into();
1114        let result = switchboard.get_snapshot_order_topic(client_order_id);
1115        assert_eq!(result, expected_topic);
1116        assert!(
1117            switchboard
1118                .snapshot_order_topics
1119                .contains_key(&client_order_id)
1120        );
1121    }
1122
1123    #[rstest]
1124    fn test_get_snapshot_position_topic(mut switchboard: MessagingSwitchboard) {
1125        let position_id = PositionId::from("P-123456789");
1126        let expected_topic = format!("snapshots.position.{position_id}").into();
1127        let result = switchboard.get_snapshot_position_topic(position_id);
1128        assert_eq!(result, expected_topic);
1129        assert!(
1130            switchboard
1131                .snapshot_position_topics
1132                .contains_key(&position_id)
1133        );
1134    }
1135
1136    #[rstest]
1137    #[case(
1138        "CLIENT.A",
1139        "orders",
1140        "events.system.SocketStateChanged.CLIENT%2EA.orders"
1141    )]
1142    #[case(
1143        "CLIENT*?",
1144        "public.market",
1145        "events.system.SocketStateChanged.CLIENT%2A%3F.public%2Emarket"
1146    )]
1147    #[case(
1148        "CLIENT%2E",
1149        "market",
1150        "events.system.SocketStateChanged.CLIENT%252E.market"
1151    )]
1152    fn test_socket_state_topic_encodes_literal_components(
1153        #[case] client_id: &str,
1154        #[case] endpoint: &str,
1155        #[case] expected: &str,
1156    ) {
1157        let topic =
1158            MessagingSwitchboard::socket_state_changed_topic(ClientId::from(client_id), endpoint);
1159        assert_eq!(topic.as_ref(), expected);
1160    }
1161
1162    #[rstest]
1163    #[case(Some("CLIENT"), None, "CLIENT.A", "market", false)]
1164    #[case(None, Some("market"), "CLIENT", "public.market", false)]
1165    #[case(Some("CLIENT*"), None, "CLIENT1", "market", false)]
1166    #[case(Some("CLIENT?"), None, "CLIENT1", "market", false)]
1167    #[case(
1168        Some("CLIENT.A"),
1169        Some("public.market"),
1170        "CLIENT.A",
1171        "public.market",
1172        true
1173    )]
1174    #[case(None, Some("public.market"), "CLIENT.A", "public.market", true)]
1175    fn test_socket_state_pattern_matches_literal_fields(
1176        #[case] client_filter: Option<&str>,
1177        #[case] endpoint_filter: Option<&str>,
1178        #[case] client_id: &str,
1179        #[case] endpoint: &str,
1180        #[case] expected: bool,
1181    ) {
1182        let topic =
1183            MessagingSwitchboard::socket_state_changed_topic(ClientId::from(client_id), endpoint);
1184        let pattern = MessagingSwitchboard::socket_state_changed_pattern(
1185            client_filter.map(ClientId::from),
1186            endpoint_filter,
1187        );
1188        assert_eq!(is_matching_backtracking(topic, pattern), expected);
1189    }
1190
1191    #[rstest]
1192    fn test_queue_state_changed_topic_identity() {
1193        assert_eq!(
1194            MessagingSwitchboard::queue_state_changed_topic(SystemChannel::ExecCommands).as_ref(),
1195            "events.system.QueueStateChanged.ExecCommands"
1196        );
1197    }
1198
1199    #[rstest]
1200    fn test_socket_state_changed_topic_identity() {
1201        assert_eq!(
1202            MessagingSwitchboard::socket_state_changed_topic(ClientId::from("BINANCE"), "market")
1203                .as_ref(),
1204            "events.system.SocketStateChanged.BINANCE.market"
1205        );
1206    }
1207
1208    #[rstest]
1209    fn test_instruments_pattern_matches_instrument_topic(
1210        mut switchboard: MessagingSwitchboard,
1211        instrument_id: InstrumentId,
1212    ) {
1213        let venue = instrument_id.venue;
1214        let pattern = switchboard.instruments_pattern(venue);
1215        let topic = switchboard.get_instrument_topic(instrument_id);
1216
1217        assert_eq!(pattern.as_ref(), "data.instrument.XCME.*");
1218        assert!(is_matching_backtracking(topic, pattern));
1219    }
1220
1221    #[rstest]
1222    fn test_instruments_pattern_does_not_match_other_venue(mut switchboard: MessagingSwitchboard) {
1223        let pattern = switchboard.instruments_pattern(Venue::from("BINANCE"));
1224        let topic = switchboard.get_instrument_topic(InstrumentId::from("ESZ24.XCME"));
1225
1226        assert!(!is_matching_backtracking(topic, pattern));
1227    }
1228
1229    #[rstest]
1230    fn test_composite_book_deltas_pattern_uses_wildcard(mut switchboard: MessagingSwitchboard) {
1231        let composite_id = InstrumentId::from("ES.FUT.XCME");
1232        let underlying_id = InstrumentId::from("ESZ24.XCME");
1233
1234        let composite_pattern = switchboard.get_book_deltas_pattern(composite_id);
1235        let underlying_topic = switchboard.get_book_deltas_topic(underlying_id);
1236
1237        assert_eq!(composite_pattern.as_ref(), "data.book.deltas.XCME.ES*");
1238        assert_eq!(underlying_topic.as_ref(), "data.book.deltas.XCME.ESZ24");
1239        assert!(is_matching_backtracking(
1240            underlying_topic,
1241            composite_pattern
1242        ));
1243    }
1244
1245    #[rstest]
1246    fn test_book_deltas_pattern_for_non_composite_is_literal(
1247        mut switchboard: MessagingSwitchboard,
1248        instrument_id: InstrumentId,
1249    ) {
1250        let pattern = switchboard.get_book_deltas_pattern(instrument_id);
1251        assert_eq!(pattern.as_ref(), "data.book.deltas.XCME.ESZ24");
1252    }
1253
1254    type PatternFn = fn(&mut MessagingSwitchboard, InstrumentId) -> MStr<Pattern>;
1255
1256    #[rstest]
1257    #[case::book_depth(
1258        MessagingSwitchboard::get_book_depth_pattern as PatternFn,
1259        "data.book.depth.XCME.ESZ24",
1260    )]
1261    fn test_pattern_for_non_composite_is_literal(
1262        mut switchboard: MessagingSwitchboard,
1263        instrument_id: InstrumentId,
1264        #[case] pattern_fn: PatternFn,
1265        #[case] expected: &str,
1266    ) {
1267        let pattern = pattern_fn(&mut switchboard, instrument_id);
1268        assert_eq!(pattern.as_ref(), expected);
1269    }
1270
1271    #[rstest]
1272    fn test_book_snapshots_pattern_for_non_composite_is_literal(
1273        mut switchboard: MessagingSwitchboard,
1274        instrument_id: InstrumentId,
1275    ) {
1276        let interval_ms = NonZeroUsize::new(1000).unwrap();
1277        let pattern = switchboard.get_book_snapshots_pattern(instrument_id, interval_ms);
1278        assert_eq!(pattern.as_ref(), "data.book.snapshots.XCME.ESZ24.1000");
1279    }
1280
1281    #[rstest]
1282    #[case::book_deltas(MessagingSwitchboard::get_book_deltas_pattern as PatternFn)]
1283    #[case::book_depth(MessagingSwitchboard::get_book_depth_pattern as PatternFn)]
1284    fn test_pattern_function_is_idempotent(
1285        mut switchboard: MessagingSwitchboard,
1286        instrument_id: InstrumentId,
1287        #[case] pattern_fn: PatternFn,
1288    ) {
1289        let first = pattern_fn(&mut switchboard, instrument_id);
1290        let second = pattern_fn(&mut switchboard, instrument_id);
1291        assert_eq!(first, second);
1292    }
1293
1294    #[rstest]
1295    fn test_book_snapshots_pattern_is_idempotent(
1296        mut switchboard: MessagingSwitchboard,
1297        instrument_id: InstrumentId,
1298    ) {
1299        let interval_ms = NonZeroUsize::new(1000).unwrap();
1300        let first = switchboard.get_book_snapshots_pattern(instrument_id, interval_ms);
1301        let second = switchboard.get_book_snapshots_pattern(instrument_id, interval_ms);
1302        assert_eq!(first, second);
1303    }
1304
1305    #[rstest]
1306    fn test_composite_book_depth_pattern_uses_wildcard(mut switchboard: MessagingSwitchboard) {
1307        let composite_id = InstrumentId::from("ES.FUT.XCME");
1308        let underlying_id = InstrumentId::from("ESZ24.XCME");
1309
1310        let composite_pattern = switchboard.get_book_depth_pattern(composite_id);
1311        let underlying_topic = switchboard.get_book_depth_topic(underlying_id);
1312
1313        assert_eq!(composite_pattern.as_ref(), "data.book.depth.XCME.ES*");
1314        assert!(is_matching_backtracking(
1315            underlying_topic,
1316            composite_pattern
1317        ));
1318    }
1319
1320    #[rstest]
1321    fn test_composite_book_snapshots_pattern_uses_wildcard(mut switchboard: MessagingSwitchboard) {
1322        let composite_id = InstrumentId::from("ES.FUT.XCME");
1323        let underlying_id = InstrumentId::from("ESZ24.XCME");
1324        let interval_ms = NonZeroUsize::new(1000).unwrap();
1325
1326        let composite_pattern = switchboard.get_book_snapshots_pattern(composite_id, interval_ms);
1327        let underlying_topic = switchboard.get_book_snapshots_topic(underlying_id, interval_ms);
1328
1329        assert_eq!(
1330            composite_pattern.as_ref(),
1331            "data.book.snapshots.XCME.ES*.1000"
1332        );
1333        assert_eq!(
1334            underlying_topic.as_ref(),
1335            "data.book.snapshots.XCME.ESZ24.1000"
1336        );
1337        assert!(is_matching_backtracking(
1338            underlying_topic,
1339            composite_pattern
1340        ));
1341    }
1342}