nautilus-common 0.58.0

Common functionality and machinery for the Nautilus trading engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Built-in message bus endpoint, topic, and pattern names.
//!
//! The `DataEngine`, `ExecEngine`, and `RiskEngine` command endpoints use a queued entry point
//! plus a direct dispatch endpoint:
//!
//! - `*.queue_execute` is the normal entry point for runtime command producers. It routes through
//!   the current runner queue or channel before the engine sees the command.
//! - `*.execute` is the lower-level dispatch point used by runner drains and internal paths that
//!   intentionally bypass the queue.
//!
//! Prefer queued endpoints for runtime command producers unless the caller owns the ordering and
//! re-entrancy implications of direct dispatch. The risk and execution queued endpoints can fall
//! back to direct dispatch when no trading command sender is installed.

use std::{num::NonZeroUsize, sync::OnceLock};

use ahash::AHashMap;
use nautilus_model::{
    data::{BarType, DataType},
    identifiers::{ClientOrderId, InstrumentId, OptionSeriesId, PositionId, StrategyId, Venue},
};

use super::mstr::{Endpoint, MStr, Pattern, Topic};
use crate::msgbus::get_message_bus;

pub const CLOSE_TOPIC: &str = "CLOSE";
pub const TIME_EVENT_TOPIC: &str = "clock.time_event";

static DATA_QUEUE_COMMAND_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
static DATA_EXECUTE_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
static DATA_PROCESS_ANY_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
static DATA_PROCESS_DATA_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
static DATA_RESPONSE_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
static DATA_RESPONSE_TOPIC: OnceLock<MStr<Topic>> = OnceLock::new();
static TIME_EVENT_TOPIC_MSTR: OnceLock<MStr<Topic>> = OnceLock::new();
static EXEC_QUEUE_COMMAND_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
static EXEC_EXECUTE_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
static EXEC_PROCESS_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
static EXEC_RECONCILE_REPORT_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
static RISK_EXECUTE_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
static RISK_QUEUE_EXECUTE_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
static RISK_PROCESS_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
static ORDER_EMULATOR_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
static PORTFOLIO_ACCOUNT_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
static PORTFOLIO_ORDER_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();
static SHUTDOWN_SYSTEM_TOPIC: OnceLock<MStr<Topic>> = OnceLock::new();
static RECONCILIATION_RAW_ORDER_REPORT_TOPIC: OnceLock<MStr<Topic>> = OnceLock::new();
static RECONCILIATION_RAW_FILL_REPORT_TOPIC: OnceLock<MStr<Topic>> = OnceLock::new();
static RECONCILIATION_RAW_POSITION_REPORT_TOPIC: OnceLock<MStr<Topic>> = OnceLock::new();

#[cfg(feature = "defi")]
static DATA_PROCESS_DEFI_DATA_ENDPOINT: OnceLock<MStr<Endpoint>> = OnceLock::new();

macro_rules! define_switchboard {
    ($(
        $field:ident: $key_ty:ty,
        $method:ident($($arg_name:ident: $arg_ty:ty),*) -> $key_expr:expr,
        $val_fmt:expr,
        $($val_args:expr),*
    );* $(;)?) => {
        /// Represents a switchboard of built-in messaging endpoint names.
        #[derive(Clone, Debug)]
        pub struct MessagingSwitchboard {
            $(
                $field: AHashMap<$key_ty, MStr<Topic>>,
            )*
            pipeline_topics: AHashMap<MStr<Topic>, MStr<Topic>>,
            instruments_patterns: AHashMap<Venue, MStr<Pattern>>,
            book_deltas_patterns: AHashMap<InstrumentId, MStr<Pattern>>,
            book_depth10_patterns: AHashMap<InstrumentId, MStr<Pattern>>,
            book_snapshots_patterns: AHashMap<(InstrumentId, NonZeroUsize), MStr<Pattern>>,
            signal_topics: AHashMap<String, MStr<Topic>>,
            signal_patterns: AHashMap<String, MStr<Pattern>>,
            #[cfg(feature = "defi")]
            pub(crate) defi: crate::defi::switchboard::DefiSwitchboard,
        }

        impl Default for MessagingSwitchboard {
            /// Creates a new default [`MessagingSwitchboard`] instance.
            fn default() -> Self {
                Self {
                    $(
                        $field: AHashMap::new(),
                    )*
                    pipeline_topics: AHashMap::new(),
                    instruments_patterns: AHashMap::new(),
                    book_deltas_patterns: AHashMap::new(),
                    book_depth10_patterns: AHashMap::new(),
                    book_snapshots_patterns: AHashMap::new(),
                    signal_topics: AHashMap::new(),
                    signal_patterns: AHashMap::new(),
                    #[cfg(feature = "defi")]
                    defi: crate::defi::switchboard::DefiSwitchboard::default(),
                }
            }
        }

        impl MessagingSwitchboard {
            // Static endpoints

            /// Queued entry point for `DataEngine` commands.
            #[inline]
            #[must_use]
            pub fn data_engine_queue_execute() -> MStr<Endpoint> {
                *DATA_QUEUE_COMMAND_ENDPOINT.get_or_init(|| "DataEngine.queue_execute".into())
            }

            /// Direct dispatch endpoint for `DataEngine` commands.
            #[inline]
            #[must_use]
            pub fn data_engine_execute() -> MStr<Endpoint> {
                *DATA_EXECUTE_ENDPOINT.get_or_init(|| "DataEngine.execute".into())
            }

            #[inline]
            #[must_use]
            pub fn data_engine_process() -> MStr<Endpoint> {
                *DATA_PROCESS_ANY_ENDPOINT.get_or_init(|| "DataEngine.process".into())
            }

            #[inline]
            #[must_use]
            pub fn data_engine_process_data() -> MStr<Endpoint> {
                *DATA_PROCESS_DATA_ENDPOINT.get_or_init(|| "DataEngine.process_data".into())
            }

            #[cfg(feature = "defi")]
            #[inline]
            #[must_use]
            pub fn data_engine_process_defi_data() -> MStr<Endpoint> {
                *DATA_PROCESS_DEFI_DATA_ENDPOINT
                    .get_or_init(|| "DataEngine.process_defi_data".into())
            }

            #[inline]
            #[must_use]
            pub fn data_engine_response() -> MStr<Endpoint> {
                *DATA_RESPONSE_ENDPOINT.get_or_init(|| "DataEngine.response".into())
            }

            #[inline]
            #[must_use]
            pub fn data_response_topic() -> MStr<Topic> {
                *DATA_RESPONSE_TOPIC.get_or_init(|| "data.response".into())
            }

            /// Pub/sub topic used by the event-store tap for fired clock events.
            #[inline]
            #[must_use]
            pub fn time_event_topic() -> MStr<Topic> {
                *TIME_EVENT_TOPIC_MSTR.get_or_init(|| TIME_EVENT_TOPIC.into())
            }

            /// Direct dispatch endpoint for `ExecEngine` commands.
            #[inline]
            #[must_use]
            pub fn exec_engine_execute() -> MStr<Endpoint> {
                *EXEC_EXECUTE_ENDPOINT.get_or_init(|| "ExecEngine.execute".into())
            }

            /// Queued entry point for `ExecEngine` commands.
            #[inline]
            #[must_use]
            pub fn exec_engine_queue_execute() -> MStr<Endpoint> {
                *EXEC_QUEUE_COMMAND_ENDPOINT.get_or_init(|| "ExecEngine.queue_execute".into())
            }

            #[inline]
            #[must_use]
            pub fn exec_engine_process() -> MStr<Endpoint> {
                *EXEC_PROCESS_ENDPOINT.get_or_init(|| "ExecEngine.process".into())
            }

            #[inline]
            #[must_use]
            pub fn exec_engine_reconcile_execution_report() -> MStr<Endpoint> {
                *EXEC_RECONCILE_REPORT_ENDPOINT.get_or_init(|| "ExecEngine.reconcile_execution_report".into())
            }

            /// Direct dispatch endpoint for `RiskEngine` commands.
            #[inline]
            #[must_use]
            pub fn risk_engine_execute() -> MStr<Endpoint> {
                *RISK_EXECUTE_ENDPOINT.get_or_init(|| "RiskEngine.execute".into())
            }

            /// Queued entry point for `RiskEngine` commands.
            #[inline]
            #[must_use]
            pub fn risk_engine_queue_execute() -> MStr<Endpoint> {
                *RISK_QUEUE_EXECUTE_ENDPOINT.get_or_init(|| "RiskEngine.queue_execute".into())
            }

            #[inline]
            #[must_use]
            pub fn risk_engine_process() -> MStr<Endpoint> {
                *RISK_PROCESS_ENDPOINT.get_or_init(|| "RiskEngine.process".into())
            }

            #[inline]
            #[must_use]
            pub fn order_emulator_execute() -> MStr<Endpoint> {
                *ORDER_EMULATOR_ENDPOINT.get_or_init(|| "OrderEmulator.execute".into())
            }

            #[inline]
            #[must_use]
            pub fn portfolio_update_account() -> MStr<Endpoint> {
                *PORTFOLIO_ACCOUNT_ENDPOINT.get_or_init(|| "Portfolio.update_account".into())
            }

            #[inline]
            #[must_use]
            pub fn portfolio_update_order() -> MStr<Endpoint> {
                *PORTFOLIO_ORDER_ENDPOINT.get_or_init(|| "Portfolio.update_order".into())
            }

            /// Pub/sub topic carrying `ShutdownSystem` commands published by
            /// actors, engines, and strategies.
            ///
            /// Matches the Python topic. The kernel subscribes to validate the
            /// command and signal graceful shutdown; additional components may
            /// subscribe to react to the same signal.
            #[inline]
            #[must_use]
            pub fn shutdown_system_topic() -> MStr<Topic> {
                *SHUTDOWN_SYSTEM_TOPIC.get_or_init(|| "commands.system.shutdown".into())
            }

            /// Pub/sub topic carrying raw `OrderStatusReport`s that arrived from
            /// a venue client, published by the execution engine at the top of
            /// reconciliation before any state mutation.
            ///
            /// The event store bus tap captures publications on this topic so
            /// forensic replay can re-run reconciliation against the same raw
            /// inputs the live engine saw. Subscribers are not expected in
            /// production; the capture surface is the sole consumer today.
            #[inline]
            #[must_use]
            pub fn reconciliation_raw_order_status_report_topic() -> MStr<Topic> {
                *RECONCILIATION_RAW_ORDER_REPORT_TOPIC
                    .get_or_init(|| "reconciliation.raw.OrderStatusReport".into())
            }

            /// Pub/sub topic carrying raw `FillReport`s that arrived from a
            /// venue client, published by the execution engine at the top of
            /// reconciliation before any state mutation.
            ///
            /// See [`Self::reconciliation_raw_order_status_report_topic`] for the
            /// capture contract.
            #[inline]
            #[must_use]
            pub fn reconciliation_raw_fill_report_topic() -> MStr<Topic> {
                *RECONCILIATION_RAW_FILL_REPORT_TOPIC
                    .get_or_init(|| "reconciliation.raw.FillReport".into())
            }

            /// Pub/sub topic carrying raw `PositionStatusReport`s that arrived
            /// from a venue client, published by the execution engine at the
            /// top of reconciliation before any state mutation.
            ///
            /// See [`Self::reconciliation_raw_order_status_report_topic`] for the
            /// capture contract.
            #[inline]
            #[must_use]
            pub fn reconciliation_raw_position_status_report_topic() -> MStr<Topic> {
                *RECONCILIATION_RAW_POSITION_REPORT_TOPIC
                    .get_or_init(|| "reconciliation.raw.PositionStatusReport".into())
            }

            /// Returns a wildcard pattern for matching all instrument topics for a venue.
            #[must_use]
            pub fn instruments_pattern(&mut self, venue: Venue) -> MStr<Pattern> {
                *self.instruments_patterns
                    .entry(venue)
                    .or_insert_with(|| format!("data.instrument.{venue}.*").into())
            }

            /// Returns the exact signal publish topic for `name`
            /// (`data.Signal<TitleName>`).
            ///
            /// The title-cased encoding mirrors the v1 Python convention so
            /// subscribers keyed on either a specific name or the global
            /// `data.Signal*` wildcard receive published signals.
            #[must_use]
            pub fn signal_topic(&mut self, name: &str) -> MStr<Topic> {
                *self
                    .signal_topics
                    .entry(name.to_string())
                    .or_insert_with(|| {
                        format!(
                            "data.Signal{}",
                            nautilus_core::string::conversions::title_case(name)
                        )
                        .into()
                    })
            }

            /// Returns the subscription pattern for `name`
            /// (`data.Signal<TitleName>*`).
            ///
            /// An empty `name` yields the wildcard `data.Signal*` that matches
            /// every signal topic.
            #[must_use]
            pub fn signal_pattern(&mut self, name: &str) -> MStr<Pattern> {
                *self
                    .signal_patterns
                    .entry(name.to_string())
                    .or_insert_with(|| {
                        format!(
                            "data.Signal{}*",
                            nautilus_core::string::conversions::title_case(name)
                        )
                        .into()
                    })
            }

            // Dynamic topics
            $(
                #[must_use]
                pub fn $method(&mut self, $($arg_name: $arg_ty),*) -> MStr<Topic> {
                    let key = $key_expr;
                    *self.$field
                        .entry(key)
                        .or_insert_with(|| format!($val_fmt, $($val_args),*).into())
                }
            )*
        }
    };
}

define_switchboard! {
    custom_topics: DataType,
    get_custom_topic(data_type: &DataType) -> data_type.clone(),
    "data.{}", data_type.topic();

    instruments_topics: Venue,
    get_instruments_topic(venue: Venue) -> venue,
    "data.instrument.{}", venue;

    instrument_topics: InstrumentId,
    get_instrument_topic(instrument_id: InstrumentId) -> instrument_id,
    "data.instrument.{}.{}", instrument_id.venue, instrument_id.symbol;

    book_deltas_topics: InstrumentId,
    get_book_deltas_topic(instrument_id: InstrumentId) -> instrument_id,
    "data.book.deltas.{}.{}", instrument_id.venue, instrument_id.symbol;

    book_depth10_topics: InstrumentId,
    get_book_depth10_topic(instrument_id: InstrumentId) -> instrument_id,
    "data.book.depth10.{}.{}", instrument_id.venue, instrument_id.symbol;

    book_snapshots_topics: (InstrumentId, NonZeroUsize),
    get_book_snapshots_topic(instrument_id: InstrumentId, interval_ms: NonZeroUsize) -> (instrument_id, interval_ms),
    "data.book.snapshots.{}.{}.{}", instrument_id.venue, instrument_id.symbol, interval_ms;

    quote_topics: InstrumentId,
    get_quotes_topic(instrument_id: InstrumentId) -> instrument_id,
    "data.quotes.{}.{}", instrument_id.venue, instrument_id.symbol;

    trade_topics: InstrumentId,
    get_trades_topic(instrument_id: InstrumentId) -> instrument_id,
    "data.trades.{}.{}", instrument_id.venue, instrument_id.symbol;

    bar_topics: BarType,
    get_bars_topic(bar_type: BarType) -> bar_type,
    "data.bars.{}", bar_type;

    mark_price_topics: InstrumentId,
    get_mark_price_topic(instrument_id: InstrumentId) -> instrument_id,
    "data.mark_prices.{}.{}", instrument_id.venue, instrument_id.symbol;

    index_price_topics: InstrumentId,
    get_index_price_topic(instrument_id: InstrumentId) -> instrument_id,
    "data.index_prices.{}.{}", instrument_id.venue, instrument_id.symbol;

    funding_rate_topics: InstrumentId,
    get_funding_rate_topic(instrument_id: InstrumentId) -> instrument_id,
    "data.funding_rates.{}.{}", instrument_id.venue, instrument_id.symbol;

    funding_settlement_topics: InstrumentId,
    get_funding_settlement_topic(instrument_id: InstrumentId) -> instrument_id,
    "events.funding_settlements.{}.{}", instrument_id.venue, instrument_id.symbol;

    instrument_status_topics: InstrumentId,
    get_instrument_status_topic(instrument_id: InstrumentId) -> instrument_id,
    "data.status.{}.{}", instrument_id.venue, instrument_id.symbol;

    instrument_close_topics: InstrumentId,
    get_instrument_close_topic(instrument_id: InstrumentId) -> instrument_id,
    "data.close.{}.{}", instrument_id.venue, instrument_id.symbol;

    option_greeks_topics: InstrumentId,
    get_option_greeks_topic(instrument_id: InstrumentId) -> instrument_id,
    "data.option_greeks.{}.{}", instrument_id.venue, instrument_id.symbol;

    option_chain_topics: OptionSeriesId,
    get_option_chain_topic(series_id: OptionSeriesId) -> series_id,
    "data.option_chain.{}", series_id;

    order_fills_topics: InstrumentId,
    get_order_fills_topic(instrument_id: InstrumentId) -> instrument_id,
    "events.fills.{}", instrument_id;

    order_cancels_topics: InstrumentId,
    get_order_cancels_topic(instrument_id: InstrumentId) -> instrument_id,
    "events.cancels.{}", instrument_id;

    order_snapshots_topics: ClientOrderId,
    get_order_snapshots_topic(client_order_id: ClientOrderId) -> client_order_id,
    "order.snapshots.{}", client_order_id;

    positions_snapshots_topics: PositionId,
    get_positions_snapshots_topic(position_id: PositionId) -> position_id,
    "positions.snapshots.{}", position_id;

    event_orders_topics: StrategyId,
    get_event_orders_topic(strategy_id: StrategyId) -> strategy_id,
    "events.order.{}", strategy_id;

    event_positions_topics: StrategyId,
    get_event_positions_topic(strategy_id: StrategyId) -> strategy_id,
    "events.position.{}", strategy_id;
}

impl MessagingSwitchboard {
    #[inline]
    fn pipeline_topic(&mut self, live: MStr<Topic>) -> MStr<Topic> {
        *self.pipeline_topics.entry(live).or_insert_with(|| {
            let live = live.as_ref();
            let suffix = live
                .strip_prefix("data.")
                .expect("live data topic must start with data.");
            MStr::<Topic>::from(format!("data.pipeline.{suffix}"))
        })
    }

    #[must_use]
    pub fn get_pipeline_custom_topic(&mut self, data_type: &DataType) -> MStr<Topic> {
        let live = self.get_custom_topic(data_type);
        self.pipeline_topic(live)
    }

    #[must_use]
    pub fn get_pipeline_book_deltas_topic(&mut self, instrument_id: InstrumentId) -> MStr<Topic> {
        let live = self.get_book_deltas_topic(instrument_id);
        self.pipeline_topic(live)
    }

    #[must_use]
    pub fn get_pipeline_book_depth10_topic(&mut self, instrument_id: InstrumentId) -> MStr<Topic> {
        let live = self.get_book_depth10_topic(instrument_id);
        self.pipeline_topic(live)
    }

    #[must_use]
    pub fn get_pipeline_quotes_topic(&mut self, instrument_id: InstrumentId) -> MStr<Topic> {
        let live = self.get_quotes_topic(instrument_id);
        self.pipeline_topic(live)
    }

    #[must_use]
    pub fn get_pipeline_trades_topic(&mut self, instrument_id: InstrumentId) -> MStr<Topic> {
        let live = self.get_trades_topic(instrument_id);
        self.pipeline_topic(live)
    }

    #[must_use]
    pub fn get_pipeline_bars_topic(&mut self, bar_type: BarType) -> MStr<Topic> {
        let live = self.get_bars_topic(bar_type);
        self.pipeline_topic(live)
    }

    #[must_use]
    pub fn get_pipeline_mark_price_topic(&mut self, instrument_id: InstrumentId) -> MStr<Topic> {
        let live = self.get_mark_price_topic(instrument_id);
        self.pipeline_topic(live)
    }

    #[must_use]
    pub fn get_pipeline_index_price_topic(&mut self, instrument_id: InstrumentId) -> MStr<Topic> {
        let live = self.get_index_price_topic(instrument_id);
        self.pipeline_topic(live)
    }

    #[must_use]
    pub fn get_pipeline_funding_rate_topic(&mut self, instrument_id: InstrumentId) -> MStr<Topic> {
        let live = self.get_funding_rate_topic(instrument_id);
        self.pipeline_topic(live)
    }

    #[must_use]
    pub fn get_pipeline_instrument_status_topic(
        &mut self,
        instrument_id: InstrumentId,
    ) -> MStr<Topic> {
        let live = self.get_instrument_status_topic(instrument_id);
        self.pipeline_topic(live)
    }

    #[must_use]
    pub fn get_pipeline_option_greeks_topic(&mut self, instrument_id: InstrumentId) -> MStr<Topic> {
        let live = self.get_option_greeks_topic(instrument_id);
        self.pipeline_topic(live)
    }

    #[must_use]
    pub fn get_pipeline_instrument_close_topic(
        &mut self,
        instrument_id: InstrumentId,
    ) -> MStr<Topic> {
        let live = self.get_instrument_close_topic(instrument_id);
        self.pipeline_topic(live)
    }

    /// Returns the subscription pattern for order book deltas on `instrument_id`.
    #[must_use]
    pub fn get_book_deltas_pattern(&mut self, instrument_id: InstrumentId) -> MStr<Pattern> {
        *self
            .book_deltas_patterns
            .entry(instrument_id)
            .or_insert_with(|| {
                format!(
                    "data.book.deltas.{}.{}",
                    instrument_id.venue,
                    instrument_id.symbol.topic(),
                )
                .into()
            })
    }

    /// Returns the subscription pattern for order book depth10 snapshots on `instrument_id`.
    #[must_use]
    pub fn get_book_depth10_pattern(&mut self, instrument_id: InstrumentId) -> MStr<Pattern> {
        *self
            .book_depth10_patterns
            .entry(instrument_id)
            .or_insert_with(|| {
                format!(
                    "data.book.depth10.{}.{}",
                    instrument_id.venue,
                    instrument_id.symbol.topic(),
                )
                .into()
            })
    }

    /// Returns the subscription pattern for periodic order book snapshots on `instrument_id`.
    #[must_use]
    pub fn get_book_snapshots_pattern(
        &mut self,
        instrument_id: InstrumentId,
        interval_ms: NonZeroUsize,
    ) -> MStr<Pattern> {
        *self
            .book_snapshots_patterns
            .entry((instrument_id, interval_ms))
            .or_insert_with(|| {
                format!(
                    "data.book.snapshots.{}.{}.{}",
                    instrument_id.venue,
                    instrument_id.symbol.topic(),
                    interval_ms,
                )
                .into()
            })
    }
}

macro_rules! define_wrappers {
    ($($method:ident($($arg_name:ident: $arg_ty:ty),*) -> $ret:ty),* $(,)?) => {
        $(
            #[must_use]
            pub fn $method($($arg_name: $arg_ty),*) -> $ret {
                get_message_bus()
                    .borrow_mut()
                    .switchboard
                    .$method($($arg_name),*)
            }
        )*
    }
}

define_wrappers! {
    get_custom_topic(data_type: &DataType) -> MStr<Topic>,
    get_instruments_topic(venue: Venue) -> MStr<Topic>,
    get_instrument_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_book_deltas_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_book_depth10_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_book_snapshots_topic(instrument_id: InstrumentId, interval_ms: NonZeroUsize) -> MStr<Topic>,
    get_quotes_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_trades_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_bars_topic(bar_type: BarType) -> MStr<Topic>,
    get_mark_price_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_index_price_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_funding_rate_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_funding_settlement_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_instrument_status_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_instrument_close_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_option_greeks_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_option_chain_topic(series_id: OptionSeriesId) -> MStr<Topic>,
    get_pipeline_custom_topic(data_type: &DataType) -> MStr<Topic>,
    get_pipeline_book_deltas_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_pipeline_book_depth10_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_pipeline_quotes_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_pipeline_trades_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_pipeline_bars_topic(bar_type: BarType) -> MStr<Topic>,
    get_pipeline_mark_price_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_pipeline_index_price_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_pipeline_funding_rate_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_pipeline_instrument_status_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_pipeline_option_greeks_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_pipeline_instrument_close_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_order_fills_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_order_cancels_topic(instrument_id: InstrumentId) -> MStr<Topic>,
    get_order_snapshots_topic(client_order_id: ClientOrderId) -> MStr<Topic>,
    get_positions_snapshots_topic(position_id: PositionId) -> MStr<Topic>,
    get_event_orders_topic(strategy_id: StrategyId) -> MStr<Topic>,
    get_event_positions_topic(strategy_id: StrategyId) -> MStr<Topic>,
}

/// Returns a wildcard subscription pattern that matches all instrument topics
/// for the given `venue`.
///
/// For example, venue `BINANCE` produces pattern `data.instrument.BINANCE.*`,
/// which matches per-instrument topics like `data.instrument.BINANCE.BTCUSDT`.
#[must_use]
pub fn get_instruments_pattern(venue: Venue) -> MStr<Pattern> {
    get_message_bus()
        .borrow_mut()
        .switchboard
        .instruments_pattern(venue)
}

/// Returns the subscription pattern for order book deltas on `instrument_id`.
#[must_use]
pub fn get_book_deltas_pattern(instrument_id: InstrumentId) -> MStr<Pattern> {
    get_message_bus()
        .borrow_mut()
        .switchboard
        .get_book_deltas_pattern(instrument_id)
}

/// Returns the subscription pattern for order book depth10 snapshots on `instrument_id`.
#[must_use]
pub fn get_book_depth10_pattern(instrument_id: InstrumentId) -> MStr<Pattern> {
    get_message_bus()
        .borrow_mut()
        .switchboard
        .get_book_depth10_pattern(instrument_id)
}

/// Returns the subscription pattern for periodic order book snapshots on `instrument_id`.
#[must_use]
pub fn get_book_snapshots_pattern(
    instrument_id: InstrumentId,
    interval_ms: NonZeroUsize,
) -> MStr<Pattern> {
    get_message_bus()
        .borrow_mut()
        .switchboard
        .get_book_snapshots_pattern(instrument_id, interval_ms)
}

/// Returns the exact signal publish topic for `name` (`data.Signal<TitleName>`).
#[must_use]
pub fn get_signal_topic(name: &str) -> MStr<Topic> {
    get_message_bus()
        .borrow_mut()
        .switchboard
        .signal_topic(name)
}

/// Returns the signal subscription pattern for `name` (`data.Signal<TitleName>*`).
///
/// An empty `name` yields the wildcard `data.Signal*` matching every signal topic.
#[must_use]
pub fn get_signal_pattern(name: &str) -> MStr<Pattern> {
    get_message_bus()
        .borrow_mut()
        .switchboard
        .signal_pattern(name)
}

#[cfg(test)]
mod tests {
    use nautilus_model::{
        data::{BarType, DataType},
        identifiers::{InstrumentId, Venue},
    };
    use rstest::*;

    use super::*;
    use crate::msgbus::matching::is_matching_backtracking;

    #[fixture]
    fn switchboard() -> MessagingSwitchboard {
        MessagingSwitchboard::default()
    }

    #[fixture]
    fn instrument_id() -> InstrumentId {
        InstrumentId::from("ESZ24.XCME")
    }

    #[rstest]
    fn test_data_response_topic() {
        let expected_topic = "data.response".into();
        let result = MessagingSwitchboard::data_response_topic();
        assert_eq!(result, expected_topic);
    }

    #[rstest]
    fn test_time_event_topic() {
        let expected_topic = "clock.time_event".into();
        let result = MessagingSwitchboard::time_event_topic();
        assert_eq!(result, expected_topic);
    }

    #[rstest]
    fn test_reconciliation_raw_order_status_report_topic() {
        let expected_topic = "reconciliation.raw.OrderStatusReport".into();
        let result = MessagingSwitchboard::reconciliation_raw_order_status_report_topic();
        assert_eq!(result, expected_topic);
    }

    #[rstest]
    fn test_reconciliation_raw_fill_report_topic() {
        let expected_topic = "reconciliation.raw.FillReport".into();
        let result = MessagingSwitchboard::reconciliation_raw_fill_report_topic();
        assert_eq!(result, expected_topic);
    }

    #[rstest]
    fn test_reconciliation_raw_position_status_report_topic() {
        let expected_topic = "reconciliation.raw.PositionStatusReport".into();
        let result = MessagingSwitchboard::reconciliation_raw_position_status_report_topic();
        assert_eq!(result, expected_topic);
    }

    #[rstest]
    fn test_get_custom_topic(mut switchboard: MessagingSwitchboard) {
        let data_type = DataType::new("ExampleDataType", None, None);
        let expected_topic = "data.ExampleDataType".into();
        let result = switchboard.get_custom_topic(&data_type);
        assert_eq!(result, expected_topic);
        assert!(switchboard.custom_topics.contains_key(&data_type));
    }

    #[rstest]
    fn test_get_instrument_topic(
        mut switchboard: MessagingSwitchboard,
        instrument_id: InstrumentId,
    ) {
        let expected_topic = "data.instrument.XCME.ESZ24".into();
        let result = switchboard.get_instrument_topic(instrument_id);
        assert_eq!(result, expected_topic);
        assert!(switchboard.instrument_topics.contains_key(&instrument_id));
    }

    #[rstest]
    fn test_get_book_deltas_topic(
        mut switchboard: MessagingSwitchboard,
        instrument_id: InstrumentId,
    ) {
        let expected_topic = "data.book.deltas.XCME.ESZ24".into();
        let result = switchboard.get_book_deltas_topic(instrument_id);
        assert_eq!(result, expected_topic);
        assert!(switchboard.book_deltas_topics.contains_key(&instrument_id));
    }

    #[rstest]
    fn test_get_book_depth10_topic(
        mut switchboard: MessagingSwitchboard,
        instrument_id: InstrumentId,
    ) {
        let expected_topic = "data.book.depth10.XCME.ESZ24".into();
        let result = switchboard.get_book_depth10_topic(instrument_id);
        assert_eq!(result, expected_topic);
        assert!(switchboard.book_depth10_topics.contains_key(&instrument_id));
    }

    #[rstest]
    fn test_get_book_snapshots_topic(
        mut switchboard: MessagingSwitchboard,
        instrument_id: InstrumentId,
    ) {
        let expected_topic = "data.book.snapshots.XCME.ESZ24.1000".into();
        let interval_ms = NonZeroUsize::new(1000).unwrap();
        let result = switchboard.get_book_snapshots_topic(instrument_id, interval_ms);
        assert_eq!(result, expected_topic);

        assert!(
            switchboard
                .book_snapshots_topics
                .contains_key(&(instrument_id, interval_ms))
        );
    }

    #[rstest]
    fn test_get_quotes_topic(mut switchboard: MessagingSwitchboard, instrument_id: InstrumentId) {
        let expected_topic = "data.quotes.XCME.ESZ24".into();
        let result = switchboard.get_quotes_topic(instrument_id);
        assert_eq!(result, expected_topic);
        assert!(switchboard.quote_topics.contains_key(&instrument_id));
    }

    #[rstest]
    fn test_get_trades_topic(mut switchboard: MessagingSwitchboard, instrument_id: InstrumentId) {
        let expected_topic = "data.trades.XCME.ESZ24".into();
        let result = switchboard.get_trades_topic(instrument_id);
        assert_eq!(result, expected_topic);
        assert!(switchboard.trade_topics.contains_key(&instrument_id));
    }

    #[rstest]
    fn test_get_bars_topic(mut switchboard: MessagingSwitchboard) {
        let bar_type = BarType::from("ESZ24.XCME-1-MINUTE-LAST-INTERNAL");
        let expected_topic = format!("data.bars.{bar_type}").into();
        let result = switchboard.get_bars_topic(bar_type);
        assert_eq!(result, expected_topic);
        assert!(switchboard.bar_topics.contains_key(&bar_type));
    }

    #[rstest]
    fn test_get_pipeline_custom_topic(mut switchboard: MessagingSwitchboard) {
        let data_type = DataType::new("ExampleDataType", None, None);
        let expected_topic = "data.pipeline.ExampleDataType".into();
        let result = switchboard.get_pipeline_custom_topic(&data_type);
        assert_eq!(result, expected_topic);
        assert!(switchboard.custom_topics.contains_key(&data_type));
        assert_eq!(switchboard.pipeline_topics.len(), 1);
    }

    type PipelineInstrumentIdTopicFn = fn(&mut MessagingSwitchboard, InstrumentId) -> MStr<Topic>;

    #[rstest]
    #[case::book_deltas(
        MessagingSwitchboard::get_pipeline_book_deltas_topic as PipelineInstrumentIdTopicFn,
        "data.pipeline.book.deltas.XCME.ESZ24",
    )]
    #[case::book_depth10(
        MessagingSwitchboard::get_pipeline_book_depth10_topic as PipelineInstrumentIdTopicFn,
        "data.pipeline.book.depth10.XCME.ESZ24",
    )]
    #[case::quotes(
        MessagingSwitchboard::get_pipeline_quotes_topic as PipelineInstrumentIdTopicFn,
        "data.pipeline.quotes.XCME.ESZ24",
    )]
    #[case::trades(
        MessagingSwitchboard::get_pipeline_trades_topic as PipelineInstrumentIdTopicFn,
        "data.pipeline.trades.XCME.ESZ24",
    )]
    #[case::mark_prices(
        MessagingSwitchboard::get_pipeline_mark_price_topic as PipelineInstrumentIdTopicFn,
        "data.pipeline.mark_prices.XCME.ESZ24",
    )]
    #[case::index_prices(
        MessagingSwitchboard::get_pipeline_index_price_topic as PipelineInstrumentIdTopicFn,
        "data.pipeline.index_prices.XCME.ESZ24",
    )]
    #[case::funding_rates(
        MessagingSwitchboard::get_pipeline_funding_rate_topic as PipelineInstrumentIdTopicFn,
        "data.pipeline.funding_rates.XCME.ESZ24",
    )]
    #[case::status(
        MessagingSwitchboard::get_pipeline_instrument_status_topic as PipelineInstrumentIdTopicFn,
        "data.pipeline.status.XCME.ESZ24",
    )]
    #[case::close(
        MessagingSwitchboard::get_pipeline_instrument_close_topic as PipelineInstrumentIdTopicFn,
        "data.pipeline.close.XCME.ESZ24",
    )]
    fn test_get_pipeline_instrument_id_topic(
        mut switchboard: MessagingSwitchboard,
        instrument_id: InstrumentId,
        #[case] topic_fn: PipelineInstrumentIdTopicFn,
        #[case] expected: &str,
    ) {
        let result = topic_fn(&mut switchboard, instrument_id);
        assert_eq!(result.as_ref(), expected);
        assert_eq!(switchboard.pipeline_topics.len(), 1);
    }

    #[rstest]
    fn test_get_pipeline_bars_topic(mut switchboard: MessagingSwitchboard) {
        let bar_type = BarType::from("ESZ24.XCME-1-MINUTE-LAST-INTERNAL");
        let expected_topic = format!("data.pipeline.bars.{bar_type}").into();
        let result = switchboard.get_pipeline_bars_topic(bar_type);
        assert_eq!(result, expected_topic);
        assert!(switchboard.bar_topics.contains_key(&bar_type));
        assert_eq!(switchboard.pipeline_topics.len(), 1);
    }

    #[rstest]
    fn test_get_order_snapshots_topic(mut switchboard: MessagingSwitchboard) {
        let client_order_id = ClientOrderId::from("O-123456789");
        let expected_topic = format!("order.snapshots.{client_order_id}").into();
        let result = switchboard.get_order_snapshots_topic(client_order_id);
        assert_eq!(result, expected_topic);
        assert!(
            switchboard
                .order_snapshots_topics
                .contains_key(&client_order_id)
        );
    }

    #[rstest]
    fn test_instruments_pattern_matches_instrument_topic(
        mut switchboard: MessagingSwitchboard,
        instrument_id: InstrumentId,
    ) {
        let venue = instrument_id.venue;
        let pattern = switchboard.instruments_pattern(venue);
        let topic = switchboard.get_instrument_topic(instrument_id);

        assert_eq!(pattern.as_ref(), "data.instrument.XCME.*");
        assert!(is_matching_backtracking(topic, pattern));
    }

    #[rstest]
    fn test_instruments_pattern_does_not_match_other_venue(mut switchboard: MessagingSwitchboard) {
        let pattern = switchboard.instruments_pattern(Venue::from("BINANCE"));
        let topic = switchboard.get_instrument_topic(InstrumentId::from("ESZ24.XCME"));

        assert!(!is_matching_backtracking(topic, pattern));
    }

    #[rstest]
    fn test_composite_book_deltas_pattern_uses_wildcard(mut switchboard: MessagingSwitchboard) {
        let composite_id = InstrumentId::from("ES.FUT.XCME");
        let underlying_id = InstrumentId::from("ESZ24.XCME");

        let composite_pattern = switchboard.get_book_deltas_pattern(composite_id);
        let underlying_topic = switchboard.get_book_deltas_topic(underlying_id);

        assert_eq!(composite_pattern.as_ref(), "data.book.deltas.XCME.ES*");
        assert_eq!(underlying_topic.as_ref(), "data.book.deltas.XCME.ESZ24");
        assert!(is_matching_backtracking(
            underlying_topic,
            composite_pattern
        ));
    }

    #[rstest]
    fn test_book_deltas_pattern_for_non_composite_is_literal(
        mut switchboard: MessagingSwitchboard,
        instrument_id: InstrumentId,
    ) {
        let pattern = switchboard.get_book_deltas_pattern(instrument_id);
        assert_eq!(pattern.as_ref(), "data.book.deltas.XCME.ESZ24");
    }

    type PatternFn = fn(&mut MessagingSwitchboard, InstrumentId) -> MStr<Pattern>;

    #[rstest]
    #[case::book_depth10(
        MessagingSwitchboard::get_book_depth10_pattern as PatternFn,
        "data.book.depth10.XCME.ESZ24",
    )]
    fn test_pattern_for_non_composite_is_literal(
        mut switchboard: MessagingSwitchboard,
        instrument_id: InstrumentId,
        #[case] helper: PatternFn,
        #[case] expected: &str,
    ) {
        let pattern = helper(&mut switchboard, instrument_id);
        assert_eq!(pattern.as_ref(), expected);
    }

    #[rstest]
    fn test_book_snapshots_pattern_for_non_composite_is_literal(
        mut switchboard: MessagingSwitchboard,
        instrument_id: InstrumentId,
    ) {
        let interval_ms = NonZeroUsize::new(1000).unwrap();
        let pattern = switchboard.get_book_snapshots_pattern(instrument_id, interval_ms);
        assert_eq!(pattern.as_ref(), "data.book.snapshots.XCME.ESZ24.1000");
    }

    #[rstest]
    #[case::book_deltas(MessagingSwitchboard::get_book_deltas_pattern as PatternFn)]
    #[case::book_depth10(MessagingSwitchboard::get_book_depth10_pattern as PatternFn)]
    fn test_pattern_helper_is_idempotent(
        mut switchboard: MessagingSwitchboard,
        instrument_id: InstrumentId,
        #[case] helper: PatternFn,
    ) {
        let first = helper(&mut switchboard, instrument_id);
        let second = helper(&mut switchboard, instrument_id);
        assert_eq!(first, second);
    }

    #[rstest]
    fn test_book_snapshots_pattern_helper_is_idempotent(
        mut switchboard: MessagingSwitchboard,
        instrument_id: InstrumentId,
    ) {
        let interval_ms = NonZeroUsize::new(1000).unwrap();
        let first = switchboard.get_book_snapshots_pattern(instrument_id, interval_ms);
        let second = switchboard.get_book_snapshots_pattern(instrument_id, interval_ms);
        assert_eq!(first, second);
    }

    #[rstest]
    fn test_composite_book_depth10_pattern_uses_wildcard(mut switchboard: MessagingSwitchboard) {
        let composite_id = InstrumentId::from("ES.FUT.XCME");
        let underlying_id = InstrumentId::from("ESZ24.XCME");

        let composite_pattern = switchboard.get_book_depth10_pattern(composite_id);
        let underlying_topic = switchboard.get_book_depth10_topic(underlying_id);

        assert_eq!(composite_pattern.as_ref(), "data.book.depth10.XCME.ES*");
        assert!(is_matching_backtracking(
            underlying_topic,
            composite_pattern
        ));
    }

    #[rstest]
    fn test_composite_book_snapshots_pattern_uses_wildcard(mut switchboard: MessagingSwitchboard) {
        let composite_id = InstrumentId::from("ES.FUT.XCME");
        let underlying_id = InstrumentId::from("ESZ24.XCME");
        let interval_ms = NonZeroUsize::new(1000).unwrap();

        let composite_pattern = switchboard.get_book_snapshots_pattern(composite_id, interval_ms);
        let underlying_topic = switchboard.get_book_snapshots_topic(underlying_id, interval_ms);

        assert_eq!(
            composite_pattern.as_ref(),
            "data.book.snapshots.XCME.ES*.1000"
        );
        assert_eq!(
            underlying_topic.as_ref(),
            "data.book.snapshots.XCME.ESZ24.1000"
        );
        assert!(is_matching_backtracking(
            underlying_topic,
            composite_pattern
        ));
    }
}