nautilus-common 0.65.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
// -------------------------------------------------------------------------------------------------
//  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.
// -------------------------------------------------------------------------------------------------

//! Tokio-based channel senders for live trading runtime.
//!
//! Stores channel senders for the current runtime thread.
//!
//! Data and execution event setters accept either a runtime-bound [`EventSender`] or a plain
//! Tokio sender. Plain senders carry no callback context. Getters and clones preserve the
//! installed mode and owner; moving a runtime-bound sender to another thread makes its sends
//! independent ingress.

use std::cell::RefCell;

use crate::{
    live::sender::{DispatchSender, EventSender},
    messages::{DataEvent, ExecutionEvent, SystemCommand, SystemEvent},
};

/// Gets the thread-local data event sender.
///
/// # Panics
///
/// Panics if the sender is uninitialized.
#[must_use]
pub fn get_data_event_sender() -> EventSender<DataEvent> {
    DATA_EVENT_SENDER.with(|sender| {
        sender
            .borrow()
            .as_ref()
            .expect("Data event sender should be initialized by runner")
            .clone()
    })
}

/// Attempts to get the thread-local data event sender without panicking.
///
/// Returns `None` if the sender is not initialized (e.g., in Python/v1 bridge environments
/// before a runner or adapter bridge has registered a sender).
#[must_use]
pub fn try_get_data_event_sender() -> Option<EventSender<DataEvent>> {
    DATA_EVENT_SENDER.with(|sender| sender.borrow().as_ref().cloned())
}

/// Sets the thread-local data event sender.
///
/// Can only be called once per thread.
///
/// # Panics
///
/// Panics if a sender has already been set.
pub fn set_data_event_sender(sender: impl Into<EventSender<DataEvent>>) {
    let sender = sender.into();
    DATA_EVENT_SENDER.with(|s| {
        let mut slot = s.borrow_mut();
        assert!(slot.is_none(), "Data event sender can only be set once");
        *slot = Some(sender);
    });
}

/// Replaces the data event sender for the current thread.
pub fn replace_data_event_sender(sender: impl Into<EventSender<DataEvent>>) {
    let sender = sender.into();
    DATA_EVENT_SENDER.with(|s| {
        *s.borrow_mut() = Some(sender);
    });
}

/// Gets the thread-local system event sender.
///
/// # Panics
///
/// Panics if the sender is uninitialized.
#[must_use]
pub fn get_system_event_sender() -> EventSender<SystemEvent> {
    SYSTEM_EVENT_SENDER.with(|sender| {
        sender
            .borrow()
            .as_ref()
            .expect("System event sender should be initialized by runner")
            .clone()
    })
}

/// Attempts to get the thread-local system event sender without panicking.
///
/// Returns `None` if the sender is not initialized (e.g., in test environments).
#[must_use]
pub fn try_get_system_event_sender() -> Option<EventSender<SystemEvent>> {
    SYSTEM_EVENT_SENDER.with(|sender| sender.borrow().as_ref().cloned())
}

/// Sets the thread-local system event sender.
///
/// Can only be called once per thread.
///
/// # Panics
///
/// Panics if a sender has already been set.
pub fn set_system_event_sender(sender: impl Into<EventSender<SystemEvent>>) {
    let sender = sender.into();
    SYSTEM_EVENT_SENDER.with(|s| {
        let mut slot = s.borrow_mut();
        assert!(slot.is_none(), "System event sender can only be set once");
        *slot = Some(sender);
    });
}

/// Replaces the system event sender for the current thread.
pub fn replace_system_event_sender(sender: impl Into<EventSender<SystemEvent>>) {
    let sender = sender.into();
    SYSTEM_EVENT_SENDER.with(|s| {
        *s.borrow_mut() = Some(sender);
    });
}

/// Gets the thread-local system command sender.
///
/// # Panics
///
/// Panics if the sender is uninitialized.
#[must_use]
pub fn get_system_command_sender() -> DispatchSender<SystemCommand> {
    SYSTEM_COMMAND_SENDER.with(|sender| {
        sender
            .borrow()
            .as_ref()
            .expect("System command sender should be initialized by runner")
            .clone()
    })
}

/// Attempts to get the thread-local system command sender without panicking.
///
/// Returns `None` if the sender is not initialized.
#[must_use]
pub fn try_get_system_command_sender() -> Option<DispatchSender<SystemCommand>> {
    SYSTEM_COMMAND_SENDER.with(|sender| sender.borrow().as_ref().cloned())
}

/// Sets the thread-local system command sender.
///
/// Can only be called once per thread.
///
/// # Panics
///
/// Panics if a sender has already been set.
pub fn set_system_command_sender(sender: impl Into<DispatchSender<SystemCommand>>) {
    let sender = sender.into();
    SYSTEM_COMMAND_SENDER.with(|s| {
        let mut slot = s.borrow_mut();
        assert!(slot.is_none(), "System command sender can only be set once");
        *slot = Some(sender);
    });
}

/// Replaces the system command sender for the current thread.
pub fn replace_system_command_sender(sender: impl Into<DispatchSender<SystemCommand>>) {
    let sender = sender.into();
    SYSTEM_COMMAND_SENDER.with(|s| {
        *s.borrow_mut() = Some(sender);
    });
}

/// Gets the thread-local execution event sender.
///
/// # Panics
///
/// Panics if the sender is uninitialized.
#[must_use]
pub fn get_exec_event_sender() -> EventSender<ExecutionEvent> {
    EXEC_EVENT_SENDER.with(|sender| {
        sender
            .borrow()
            .as_ref()
            .expect("Execution event sender should be initialized by runner")
            .clone()
    })
}

/// Attempts to get the thread-local execution event sender without panicking.
///
/// Returns `None` if the sender is not initialized (e.g., in test environments).
#[must_use]
pub fn try_get_exec_event_sender() -> Option<EventSender<ExecutionEvent>> {
    EXEC_EVENT_SENDER.with(|sender| sender.borrow().as_ref().cloned())
}

/// Sets the thread-local execution event sender.
///
/// Can only be called once per thread.
///
/// # Panics
///
/// Panics if a sender has already been set.
pub fn set_exec_event_sender(sender: impl Into<EventSender<ExecutionEvent>>) {
    let sender = sender.into();
    EXEC_EVENT_SENDER.with(|s| {
        let mut slot = s.borrow_mut();
        assert!(
            slot.is_none(),
            "Execution event sender can only be set once"
        );
        *slot = Some(sender);
    });
}

/// Replaces the execution event sender for the current thread.
pub fn replace_exec_event_sender(sender: impl Into<EventSender<ExecutionEvent>>) {
    let sender = sender.into();
    EXEC_EVENT_SENDER.with(|s| {
        *s.borrow_mut() = Some(sender);
    });
}

thread_local! {
    static DATA_EVENT_SENDER: RefCell<Option<EventSender<DataEvent>>> = const { RefCell::new(None) };
    static EXEC_EVENT_SENDER: RefCell<Option<EventSender<ExecutionEvent>>> = const { RefCell::new(None) };
    static SYSTEM_EVENT_SENDER: RefCell<Option<EventSender<SystemEvent>>> = const { RefCell::new(None) };
    static SYSTEM_COMMAND_SENDER: RefCell<Option<DispatchSender<SystemCommand>>> = const { RefCell::new(None) };
}

#[cfg(test)]
mod tests {
    use std::sync::{Arc, Barrier};

    use rstest::rstest;

    use super::*;

    #[rstest]
    fn test_replace_data_event_sender_overwrites_previous() {
        assert_sender_replaced(replace_data_event_sender, get_data_event_sender);
    }

    #[rstest]
    fn test_replace_exec_event_sender_overwrites_previous() {
        assert_sender_replaced(replace_exec_event_sender, get_exec_event_sender);
    }

    #[rstest]
    fn test_replace_system_event_sender_overwrites_previous() {
        assert_sender_replaced(replace_system_event_sender, get_system_event_sender);
    }

    #[rstest]
    fn test_replace_system_command_sender_overwrites_previous() {
        assert_sender_replaced(replace_system_command_sender, get_system_command_sender);
    }

    #[rstest]
    fn test_event_senders_are_thread_local() {
        assert_sender_thread_local(replace_data_event_sender, get_data_event_sender);
        assert_sender_thread_local(replace_exec_event_sender, get_exec_event_sender);
        assert_sender_thread_local(replace_system_event_sender, get_system_event_sender);
        assert_sender_thread_local(replace_system_command_sender, get_system_command_sender);
    }

    #[rstest]
    fn test_set_data_event_sender_panics_on_double_set() {
        let result = std::thread::spawn(|| {
            let (tx1, _rx1) = tokio::sync::mpsc::unbounded_channel();
            let (tx2, _rx2) = tokio::sync::mpsc::unbounded_channel();
            set_data_event_sender(tx1);
            set_data_event_sender(tx2);
        })
        .join();
        assert!(result.is_err());
    }

    #[rstest]
    fn test_set_exec_event_sender_panics_on_double_set() {
        let result = std::thread::spawn(|| {
            let (tx1, _rx1) = tokio::sync::mpsc::unbounded_channel();
            let (tx2, _rx2) = tokio::sync::mpsc::unbounded_channel();
            set_exec_event_sender(tx1);
            set_exec_event_sender(tx2);
        })
        .join();
        assert!(result.is_err());
    }

    #[rstest]
    fn test_set_system_event_sender_panics_on_double_set() {
        let result = std::thread::spawn(|| {
            let (tx1, _rx1) = tokio::sync::mpsc::unbounded_channel();
            let (tx2, _rx2) = tokio::sync::mpsc::unbounded_channel();
            set_system_event_sender(tx1);
            set_system_event_sender(tx2);
        })
        .join();
        assert!(result.is_err());
    }

    #[rstest]
    fn test_set_system_command_sender_panics_on_double_set() {
        let result = std::thread::spawn(|| {
            let (tx1, _rx1) = tokio::sync::mpsc::unbounded_channel();
            let (tx2, _rx2) = tokio::sync::mpsc::unbounded_channel();
            set_system_command_sender(tx1);
            set_system_command_sender(tx2);
        })
        .join();
        assert!(result.is_err());
    }

    #[rstest]
    fn test_try_get_exec_event_sender_returns_none_when_unset() {
        let result = std::thread::spawn(try_get_exec_event_sender)
            .join()
            .unwrap();
        assert!(result.is_none());
    }

    #[rstest]
    fn test_try_get_system_event_sender_returns_none_when_unset() {
        let result = std::thread::spawn(try_get_system_event_sender)
            .join()
            .unwrap();
        assert!(result.is_none());
    }

    #[rstest]
    fn test_try_get_system_command_sender_returns_none_when_unset() {
        let result = std::thread::spawn(try_get_system_command_sender)
            .join()
            .unwrap();
        assert!(result.is_none());
    }

    fn assert_sender_replaced<T: Send + 'static, S: SenderChannel<T> + Send + 'static>(
        replace: fn(tokio::sync::mpsc::UnboundedSender<T>),
        get: fn() -> S,
    ) {
        std::thread::spawn(move || {
            let (tx1, _rx1) = tokio::sync::mpsc::unbounded_channel();
            let (tx2, _rx2) = tokio::sync::mpsc::unbounded_channel();

            replace(tx1.clone());
            replace(tx2.clone());
            let sender = get();

            assert!(!sender.targets(&tx1));
            assert!(sender.targets(&tx2));
        })
        .join()
        .expect("sender replacement test thread should join");
    }

    fn assert_sender_thread_local<T: Send + 'static, S: SenderChannel<T> + Send + 'static>(
        replace: fn(tokio::sync::mpsc::UnboundedSender<T>),
        get: fn() -> S,
    ) {
        let barrier = Arc::new(Barrier::new(2));
        let (tx1, _rx1) = tokio::sync::mpsc::unbounded_channel();
        let (tx2, _rx2) = tokio::sync::mpsc::unbounded_channel();
        let expected1 = tx1.clone();
        let expected2 = tx2.clone();

        let barrier1 = Arc::clone(&barrier);

        let thread1 = std::thread::spawn(move || {
            replace(tx1);
            barrier1.wait();
            assert!(get().targets(&expected1));
        });

        let thread2 = std::thread::spawn(move || {
            replace(tx2);
            barrier.wait();
            assert!(get().targets(&expected2));
        });

        thread1
            .join()
            .expect("first sender isolation test thread should join");
        thread2
            .join()
            .expect("second sender isolation test thread should join");
    }

    trait SenderChannel<T> {
        fn targets(&self, sender: &tokio::sync::mpsc::UnboundedSender<T>) -> bool;
    }

    impl<T> SenderChannel<T> for tokio::sync::mpsc::UnboundedSender<T> {
        fn targets(&self, sender: &Self) -> bool {
            self.same_channel(sender)
        }
    }

    impl<T> SenderChannel<T> for EventSender<T> {
        fn targets(&self, sender: &tokio::sync::mpsc::UnboundedSender<T>) -> bool {
            self.same_channel(&sender.clone().into())
        }
    }
}