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
// -------------------------------------------------------------------------------------------------
//  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.
// -------------------------------------------------------------------------------------------------

use std::{
    borrow::Cow,
    collections::VecDeque,
    fs::{File, create_dir_all},
    io::{self, BufWriter, Stderr, Stdout, Write},
    path::PathBuf,
};

use chrono::{NaiveDate, Utc};
use log::LevelFilter;
use nautilus_core::consts::NAUTILUS_PREFIX;
use serde::{Deserialize, Serialize};

use crate::logging::logger::LogLine;

pub trait LogWriter {
    /// Writes a log line.
    fn write(&mut self, line: &str);
    /// Flushes buffered logs.
    fn flush(&mut self);
    /// Checks if a line needs to be written to the writer or not.
    fn enabled(&self, line: &LogLine) -> bool;
}

#[derive(Debug)]
pub struct StdoutWriter {
    pub is_colored: bool,
    io: StdoutSink,
    level: LevelFilter,
}

#[derive(Debug)]
enum StdoutSink {
    Direct(Stdout),
    Buffered(BufWriter<Stdout>),
}

impl StdoutWriter {
    /// Creates a new [`StdoutWriter`] instance.
    #[must_use]
    pub fn new(level: LevelFilter, is_colored: bool, buffered: bool) -> Self {
        let io = if buffered {
            StdoutSink::Buffered(BufWriter::new(io::stdout()))
        } else {
            StdoutSink::Direct(io::stdout())
        };

        Self {
            is_colored,
            io,
            level,
        }
    }
}

impl LogWriter for StdoutWriter {
    fn write(&mut self, line: &str) {
        let result = match &mut self.io {
            StdoutSink::Direct(io) => io.write_all(line.as_bytes()),
            StdoutSink::Buffered(io) => io.write_all(line.as_bytes()),
        };

        match result {
            Ok(()) => {}
            Err(e) => eprintln!("Error writing to stdout: {e:?}"),
        }
    }

    fn flush(&mut self) {
        let result = match &mut self.io {
            StdoutSink::Direct(io) => io.flush(),
            StdoutSink::Buffered(io) => io.flush(),
        };

        match result {
            Ok(()) => {}
            Err(e) => eprintln!("Error flushing stdout: {e:?}"),
        }
    }

    fn enabled(&self, line: &LogLine) -> bool {
        // Prevent error logs also writing to stdout (they go to stderr)
        line.level > LevelFilter::Error && line.level <= self.level
    }
}

#[derive(Debug)]
pub struct StderrWriter {
    pub is_colored: bool,
    io: Stderr,
}

impl StderrWriter {
    /// Creates a new [`StderrWriter`] instance.
    #[must_use]
    pub fn new(is_colored: bool) -> Self {
        Self {
            io: io::stderr(),
            is_colored,
        }
    }
}

impl LogWriter for StderrWriter {
    fn write(&mut self, line: &str) {
        match self.io.write_all(line.as_bytes()) {
            Ok(()) => {}
            Err(e) => eprintln!("Error writing to stderr: {e:?}"),
        }
    }

    fn flush(&mut self) {
        match self.io.flush() {
            Ok(()) => {}
            Err(e) => eprintln!("Error flushing stderr: {e:?}"),
        }
    }

    fn enabled(&self, line: &LogLine) -> bool {
        line.level == LevelFilter::Error
    }
}

/// File rotation config.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct FileRotateConfig {
    /// Maximum file size in bytes before rotating.
    pub max_file_size: u64,
    /// Maximum number of backup files to keep.
    pub max_backup_count: u32,
    /// Current file size tracking.
    #[serde(skip)]
    cur_file_size: u64,
    /// Current file creation date.
    #[serde(skip, default = "today_date")]
    cur_file_creation_date: NaiveDate,
    /// Queue of backup file paths (oldest first).
    #[serde(skip)]
    backup_files: VecDeque<PathBuf>,
}

fn today_date() -> NaiveDate {
    Utc::now().date_naive()
}

impl PartialEq for FileRotateConfig {
    fn eq(&self, other: &Self) -> bool {
        self.max_file_size == other.max_file_size && self.max_backup_count == other.max_backup_count
    }
}

impl Eq for FileRotateConfig {}

impl Default for FileRotateConfig {
    fn default() -> Self {
        Self {
            max_file_size: 100 * 1024 * 1024, // 100MB default
            max_backup_count: 5,
            cur_file_size: 0,
            cur_file_creation_date: Utc::now().date_naive(),
            backup_files: VecDeque::new(),
        }
    }
}

impl From<(u64, u32)> for FileRotateConfig {
    fn from(value: (u64, u32)) -> Self {
        let (max_file_size, max_backup_count) = value;
        Self {
            max_file_size,
            max_backup_count,
            cur_file_size: 0,
            cur_file_creation_date: Utc::now().date_naive(),
            backup_files: VecDeque::new(),
        }
    }
}

#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.common", from_py_object)
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.common")
)]
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct FileWriterConfig {
    pub directory: Option<String>,
    pub file_name: Option<String>,
    pub file_format: Option<String>,
    pub file_rotate: Option<FileRotateConfig>,
}

impl FileWriterConfig {
    /// Creates a new [`FileWriterConfig`] instance.
    #[must_use]
    pub fn new(
        directory: Option<String>,
        file_name: Option<String>,
        file_format: Option<String>,
        file_rotate: Option<(u64, u32)>,
    ) -> Self {
        let file_rotate = file_rotate.map(FileRotateConfig::from);
        Self {
            directory,
            file_name,
            file_format,
            file_rotate,
        }
    }
}

#[derive(Debug)]
pub struct FileWriter {
    pub json_format: bool,
    buf: BufWriter<File>,
    path: PathBuf,
    file_config: FileWriterConfig,
    trader_id: String,
    instance_id: String,
    level: LevelFilter,
    cur_file_date: NaiveDate,
    sync_on_flush: bool,
}

impl FileWriter {
    /// Creates a new [`FileWriter`] instance.
    pub fn new(
        trader_id: String,
        instance_id: String,
        file_config: FileWriterConfig,
        fileout_level: LevelFilter,
        clear_log_file: bool,
        sync_on_flush: bool,
    ) -> Option<Self> {
        // Set up log file
        let json_format = match file_config.file_format.as_ref().map(|s| s.to_lowercase()) {
            Some(ref format) if format == "json" => true,
            None => false,
            Some(ref unrecognized) => {
                eprintln!(
                    "{NAUTILUS_PREFIX} Unrecognized log file format: {unrecognized}. Using plain text format as default."
                );
                false
            }
        };

        let file_path =
            match Self::create_log_file_path(&file_config, &trader_id, &instance_id, json_format) {
                Ok(path) => path,
                Err(e) => {
                    eprintln!("{NAUTILUS_PREFIX} Error creating log directory: {e}");
                    return None;
                }
            };

        if clear_log_file
            && file_path.exists()
            && let Err(e) = File::create(&file_path)
        {
            eprintln!("{NAUTILUS_PREFIX} Error clearing log file: {e}");
        }

        match File::options()
            .create(true)
            .append(true)
            .open(file_path.clone())
        {
            Ok(file) => {
                // Seed cur_file_size from existing file length if rotation is enabled
                let mut file_config = file_config;
                if let Some(ref mut rotate_config) = file_config.file_rotate
                    && let Ok(metadata) = file.metadata()
                {
                    rotate_config.cur_file_size = metadata.len();
                }

                Some(Self {
                    json_format,
                    buf: BufWriter::new(file),
                    path: file_path,
                    file_config,
                    trader_id,
                    instance_id,
                    level: fileout_level,
                    cur_file_date: Utc::now().date_naive(),
                    sync_on_flush,
                })
            }
            Err(e) => {
                eprintln!("{NAUTILUS_PREFIX} Error creating log file: {e}");
                None
            }
        }
    }

    fn create_log_file_path(
        file_config: &FileWriterConfig,
        trader_id: &str,
        instance_id: &str,
        is_json_format: bool,
    ) -> Result<PathBuf, io::Error> {
        let utc_now = Utc::now();

        let basename = if let Some(file_name) = file_config.file_name.as_ref() {
            if file_config.file_rotate.is_some() {
                let utc_datetime = utc_now.format("%Y-%m-%d_%H%M%S:%3f");
                format!("{file_name}_{utc_datetime}")
            } else {
                file_name.clone()
            }
        } else {
            let utc_component = if file_config.file_rotate.is_some() {
                utc_now.format("%Y-%m-%d_%H%M%S:%3f")
            } else {
                utc_now.format("%Y-%m-%d")
            };

            format!("{trader_id}_{utc_component}_{instance_id}")
        };

        let suffix = if is_json_format { "jsonl" } else { "log" };
        let mut file_path = PathBuf::new();

        if let Some(directory) = file_config.directory.as_ref() {
            file_path.push(directory);
            create_dir_all(&file_path)?;
        }

        file_path.push(basename);
        file_path.set_extension(suffix);
        Ok(file_path)
    }

    #[must_use]
    fn should_rotate_file(&self, next_line_size: u64) -> bool {
        // Size-based rotation takes priority when configured
        if let Some(ref rotate_config) = self.file_config.file_rotate {
            rotate_config.cur_file_size + next_line_size > rotate_config.max_file_size
        // Otherwise, for default-named logs, rotate on UTC date change
        } else if self.file_config.file_name.is_none() {
            let today = Utc::now().date_naive();
            self.cur_file_date != today
        // No rotation for custom-named logs without size-based rotation
        } else {
            false
        }
    }

    fn rotate_file(&mut self) {
        self.flush_and_sync_logged();

        let new_path = match Self::create_log_file_path(
            &self.file_config,
            &self.trader_id,
            &self.instance_id,
            self.json_format,
        ) {
            Ok(path) => path,
            Err(e) => {
                eprintln!("{NAUTILUS_PREFIX} Error creating log directory for rotation: {e}");
                return;
            }
        };

        match File::options().create(true).append(true).open(&new_path) {
            Ok(new_file) => {
                // Rotate existing file
                if let Some(rotate_config) = &mut self.file_config.file_rotate {
                    // Add current file to backup queue
                    rotate_config.backup_files.push_back(self.path.clone());
                    rotate_config.cur_file_size = 0;
                    rotate_config.cur_file_creation_date = Utc::now().date_naive();
                    cleanup_backups(rotate_config);
                } else {
                    // Update creation date for date-based rotation
                    self.cur_file_date = Utc::now().date_naive();
                }

                self.buf = BufWriter::new(new_file);
                self.path.clone_from(&new_path);
                eprintln!(
                    "{NAUTILUS_PREFIX} Rotated log file, now logging to: {}",
                    new_path.display()
                );
            }
            Err(e) => eprintln!("{NAUTILUS_PREFIX} Error creating log file: {e}"),
        }
    }

    /// Flushes the userspace file buffer to the OS.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying file buffer cannot be flushed.
    pub fn flush_buffer(&mut self) -> io::Result<()> {
        self.buf.flush()
    }

    /// Requests that flushed file data is synchronized to durable storage.
    ///
    /// # Errors
    ///
    /// Returns an error if the operating system cannot sync the file to disk.
    pub fn sync_to_disk(&mut self) -> io::Result<()> {
        self.buf.get_ref().sync_all()
    }

    /// Flushes buffered file data and then syncs it to disk.
    ///
    /// # Errors
    ///
    /// Returns an error if either flushing the file buffer or syncing the file to disk fails.
    pub fn flush_and_sync(&mut self) -> io::Result<()> {
        let flush_result = self.flush_buffer();
        let sync_result = self.sync_to_disk();
        flush_result.and(sync_result)
    }

    /// Flushes and syncs while preserving the existing logging-on-error behavior.
    pub fn flush_and_sync_logged(&mut self) {
        let flush_result = self.flush_buffer();
        if let Err(e) = flush_result {
            eprintln!("{NAUTILUS_PREFIX} Error flushing file: {e:?}");
        }

        let sync_result = self.sync_to_disk();
        if let Err(e) = sync_result {
            eprintln!("{NAUTILUS_PREFIX} Error syncing file: {e:?}");
        }
    }
}

/// Clean up old backup files if we exceed the max backup count.
///
/// TODO: Minor consider using a more specific version to pop a single file
/// since normal execution will not create more than 1 excess file
fn cleanup_backups(rotate_config: &mut FileRotateConfig) {
    // Remove oldest backup files until we are at or below max_backup_count
    let excess = rotate_config
        .backup_files
        .len()
        .saturating_sub(rotate_config.max_backup_count as usize);
    for _ in 0..excess {
        if let Some(path) = rotate_config.backup_files.pop_front() {
            if path.exists()
                && let Err(e) = std::fs::remove_file(&path)
            {
                eprintln!(
                    "{NAUTILUS_PREFIX} Failed to remove old log file {}: {e}",
                    path.display()
                );
            }
        } else {
            break;
        }
    }
}

impl LogWriter for FileWriter {
    fn write(&mut self, line: &str) {
        let line = sanitize_file_line(line);
        let line_size = line.len() as u64;

        // Rotate file if needed (size-based or date-based depending on configuration)
        if self.should_rotate_file(line_size) {
            self.rotate_file();
        }

        match self.buf.write_all(line.as_bytes()) {
            Ok(()) => {
                // Update current file size
                if let Some(rotate_config) = &mut self.file_config.file_rotate {
                    rotate_config.cur_file_size += line_size;
                }
            }
            Err(e) => eprintln!("{NAUTILUS_PREFIX} Error writing to file: {e:?}"),
        }
    }

    fn flush(&mut self) {
        match self.flush_buffer() {
            Ok(()) => {}
            Err(e) => eprintln!("{NAUTILUS_PREFIX} Error flushing file: {e:?}"),
        }

        if self.sync_on_flush {
            match self.sync_to_disk() {
                Ok(()) => {}
                Err(e) => eprintln!("{NAUTILUS_PREFIX} Error syncing file: {e:?}"),
            }
        }
    }

    fn enabled(&self, line: &LogLine) -> bool {
        line.level <= self.level
    }
}

fn contains_ansi_escape(s: &str) -> bool {
    s.as_bytes().contains(&b'\x1b')
}

fn contains_nonprinting_except_newline(s: &str) -> bool {
    if s.is_ascii() {
        return s.bytes().any(|b| b != b'\n' && (b < b' ' || b == b'\x7f'));
    }

    s.chars()
        .any(|c| c != '\n' && (c.is_control() || c == '\u{7F}'))
}

fn strip_nonprinting_except_newline(s: &str) -> Cow<'_, str> {
    if !contains_nonprinting_except_newline(s) {
        return Cow::Borrowed(s);
    }

    Cow::Owned(strip_nonprinting_to_string(s))
}

fn strip_nonprinting_to_string(s: &str) -> String {
    s.chars()
        .filter(|&c| c == '\n' || (!c.is_control() && c != '\u{7F}'))
        .collect()
}

fn sanitize_file_line(s: &str) -> Cow<'_, str> {
    if !contains_ansi_escape(s) {
        return strip_nonprinting_except_newline(s);
    }

    Cow::Owned(strip_ansi_and_nonprinting_to_string(s))
}

fn strip_ansi_and_nonprinting_to_string(s: &str) -> String {
    let bytes = s.as_bytes();
    let mut out = String::with_capacity(s.len());
    let mut i = 0;

    while i < bytes.len() {
        if bytes[i] == b'\x1b' {
            if let Some(end) = ansi_escape_end(bytes, i) {
                i = end;
            } else {
                i += 1;
            }
            continue;
        }

        if bytes[i].is_ascii() {
            if bytes[i] == b'\n' || (bytes[i] >= b' ' && bytes[i] != b'\x7f') {
                out.push(bytes[i] as char);
            }
            i += 1;
            continue;
        }

        let ch = s[i..]
            .chars()
            .next()
            .expect("valid UTF-8 char boundary expected");

        if ch == '\n' || (!ch.is_control() && ch != '\u{7F}') {
            out.push(ch);
        }
        i += ch.len_utf8();
    }

    out
}

fn ansi_escape_end(bytes: &[u8], start: usize) -> Option<usize> {
    match bytes.get(start + 1).copied() {
        Some(b'[') => csi_escape_end(bytes, start + 2),
        Some(b']') => osc_escape_end(bytes, start + 2),
        _ => None,
    }
}

fn csi_escape_end(bytes: &[u8], mut i: usize) -> Option<usize> {
    while let Some(byte) = bytes.get(i).copied() {
        if byte.is_ascii_alphabetic() {
            return Some(i + 1);
        }

        if !matches!(byte, b'0'..=b'9' | b';' | b'?' | b'=') {
            return None;
        }
        i += 1;
    }

    None
}

fn osc_escape_end(bytes: &[u8], mut i: usize) -> Option<usize> {
    while let Some(byte) = bytes.get(i).copied() {
        if byte == b'\x07' {
            return Some(i + 1);
        }
        i += 1;
    }

    None
}

#[cfg(test)]
mod tests {
    use log::LevelFilter;
    use rstest::rstest;
    use smallvec::SmallVec;
    use tempfile::tempdir;

    use super::*;

    #[rstest]
    fn test_file_writer_with_rotation_creates_new_timestamped_file() {
        let temp_dir = tempdir().unwrap();

        let config = FileWriterConfig {
            directory: Some(temp_dir.path().to_str().unwrap().to_string()),
            file_name: Some("test".to_string()),
            file_format: None,
            file_rotate: Some(FileRotateConfig::from((2000, 5))),
        };

        let writer = FileWriter::new(
            "TRADER-001".to_string(),
            "instance-123".to_string(),
            config,
            LevelFilter::Info,
            false,
            true,
        )
        .unwrap();

        assert_eq!(
            writer
                .file_config
                .file_rotate
                .as_ref()
                .unwrap()
                .cur_file_size,
            0
        );
        assert!(writer.path.to_str().unwrap().contains("test_"));
    }

    #[rstest]
    #[case("Hello, World!", "Hello, World!")]
    #[case("Line1\nLine2", "Line1\nLine2")]
    #[case("Tab\there", "Tabhere")]
    #[case("Null\0char", "Nullchar")]
    #[case("DEL\u{7F}char", "DELchar")]
    #[case("Bell\u{07}sound", "Bellsound")]
    #[case("Mix\t\0\u{7F}ed", "Mixed")]
    fn test_strip_nonprinting_except_newline(#[case] input: &str, #[case] expected: &str) {
        let result = strip_nonprinting_except_newline(input);
        assert_eq!(result, expected);
    }

    #[rstest]
    #[case("Plain text", "Plain text")]
    #[case("\x1B[31mRed\x1B[0m", "Red")]
    #[case("\x1B[1;32mBold Green\x1B[0m", "Bold Green")]
    #[case("Before\x1B[0mAfter", "BeforeAfter")]
    #[case("\x1B]0;Title\x07Content", "Content")]
    #[case("Text\t\x1B[31mRed\x1B[0m", "TextRed")]
    #[case("Broken\x1B[31", "Broken[31")]
    #[case("Broken\x1B]Title", "Broken]Title")]
    fn test_sanitize_file_line(#[case] input: &str, #[case] expected: &str) {
        let result = sanitize_file_line(input);
        assert_eq!(result, expected);
    }

    #[rstest]
    fn test_sanitize_file_line_borrows_clean_input() {
        let result = sanitize_file_line("Plain text\n");

        assert!(matches!(result, Cow::Borrowed(_)));
    }

    #[rstest]
    fn test_file_writer_unwritable_directory_returns_none() {
        let config = FileWriterConfig {
            directory: Some("/nonexistent/path/that/should/not/exist".to_string()),
            file_name: Some("test".to_string()),
            file_format: None,
            file_rotate: None,
        };

        let writer = FileWriter::new(
            "TRADER-001".to_string(),
            "instance-123".to_string(),
            config,
            LevelFilter::Info,
            false,
            true,
        );

        assert!(writer.is_none());
    }

    #[rstest]
    fn test_file_writer_directory_is_file_returns_none() {
        let temp_dir = tempdir().unwrap();
        let file_path = temp_dir.path().join("not_a_directory");
        std::fs::write(&file_path, "I am a file").unwrap();

        let config = FileWriterConfig {
            directory: Some(file_path.to_str().unwrap().to_string()),
            file_name: Some("test".to_string()),
            file_format: None,
            file_rotate: None,
        };

        let writer = FileWriter::new(
            "TRADER-001".to_string(),
            "instance-123".to_string(),
            config,
            LevelFilter::Info,
            false,
            true,
        );

        assert!(writer.is_none());
    }

    #[rstest]
    fn test_file_writer_unrecognized_format_defaults_to_text() {
        let temp_dir = tempdir().unwrap();

        let config = FileWriterConfig {
            directory: Some(temp_dir.path().to_str().unwrap().to_string()),
            file_name: Some("test".to_string()),
            file_format: Some("invalid_format".to_string()),
            file_rotate: None,
        };

        let writer = FileWriter::new(
            "TRADER-001".to_string(),
            "instance-123".to_string(),
            config,
            LevelFilter::Info,
            false,
            true,
        )
        .unwrap();

        assert!(!writer.json_format);
        assert_eq!(writer.path.extension().unwrap(), "log");
    }

    #[rstest]
    fn test_file_writer_json_format() {
        let temp_dir = tempdir().unwrap();

        let config = FileWriterConfig {
            directory: Some(temp_dir.path().to_str().unwrap().to_string()),
            file_name: Some("test".to_string()),
            file_format: Some("json".to_string()),
            file_rotate: None,
        };

        let writer = FileWriter::new(
            "TRADER-001".to_string(),
            "instance-123".to_string(),
            config,
            LevelFilter::Info,
            false,
            true,
        )
        .unwrap();

        assert!(writer.json_format);
        assert_eq!(writer.path.extension().unwrap(), "jsonl");
    }

    #[rstest]
    fn test_file_writer_clear_log_file_truncates_existing_file() {
        let temp_dir = tempdir().unwrap();

        let config = FileWriterConfig {
            directory: Some(temp_dir.path().to_str().unwrap().to_string()),
            file_name: Some("test".to_string()),
            file_format: None,
            file_rotate: None,
        };

        let existing_path = temp_dir.path().join("test.log");
        std::fs::write(&existing_path, "stale contents").unwrap();
        assert_eq!(
            std::fs::metadata(&existing_path).unwrap().len(),
            "stale contents".len() as u64
        );

        let writer = FileWriter::new(
            "TRADER-001".to_string(),
            "instance-123".to_string(),
            config,
            LevelFilter::Info,
            true,
            true,
        )
        .unwrap();

        assert_eq!(writer.path, existing_path);
        assert_eq!(std::fs::metadata(&existing_path).unwrap().len(), 0);
    }

    #[rstest]
    fn test_file_writer_clear_log_file_false_preserves_existing_file() {
        let temp_dir = tempdir().unwrap();

        let config = FileWriterConfig {
            directory: Some(temp_dir.path().to_str().unwrap().to_string()),
            file_name: Some("test".to_string()),
            file_format: None,
            file_rotate: None,
        };

        let existing_path = temp_dir.path().join("test.log");
        let existing_contents = "preserved contents";
        std::fs::write(&existing_path, existing_contents).unwrap();

        let writer = FileWriter::new(
            "TRADER-001".to_string(),
            "instance-123".to_string(),
            config,
            LevelFilter::Info,
            false,
            true,
        )
        .unwrap();

        assert_eq!(writer.path, existing_path);
        assert_eq!(
            std::fs::read_to_string(&existing_path).unwrap(),
            existing_contents
        );
    }

    #[rstest]
    fn test_file_writer_sync_on_flush_can_be_disabled() {
        let temp_dir = tempdir().unwrap();

        let config = FileWriterConfig {
            directory: Some(temp_dir.path().to_str().unwrap().to_string()),
            file_name: Some("test".to_string()),
            file_format: None,
            file_rotate: None,
        };

        let mut writer = FileWriter::new(
            "TRADER-001".to_string(),
            "instance-123".to_string(),
            config,
            LevelFilter::Info,
            false,
            false,
        )
        .unwrap();

        assert!(!writer.sync_on_flush);
        writer.write("hello\n");
        writer.flush();
        writer.flush_and_sync().unwrap();
    }

    #[rstest]
    fn test_stdout_writer_filters_error_level() {
        let writer = StdoutWriter::new(LevelFilter::Info, true, false);

        // Error level should NOT be enabled for stdout (goes to stderr)
        let error_line = LogLine {
            timestamp: 0.into(),
            level: log::Level::Error,
            color: crate::enums::LogColor::Normal,
            component: ustr::Ustr::from("Test"),
            message: "error".to_string(),
            fields: SmallVec::new(),
        };
        assert!(!writer.enabled(&error_line));

        // Info level should be enabled
        let info_line = LogLine {
            timestamp: 0.into(),
            level: log::Level::Info,
            color: crate::enums::LogColor::Normal,
            component: ustr::Ustr::from("Test"),
            message: "info".to_string(),
            fields: SmallVec::new(),
        };
        assert!(writer.enabled(&info_line));

        // Debug should NOT be enabled when stdout level is Info
        let debug_line = LogLine {
            timestamp: 0.into(),
            level: log::Level::Debug,
            color: crate::enums::LogColor::Normal,
            component: ustr::Ustr::from("Test"),
            message: "debug".to_string(),
            fields: SmallVec::new(),
        };
        assert!(!writer.enabled(&debug_line));
    }

    #[rstest]
    fn test_stderr_writer_only_enables_error_level() {
        let writer = StderrWriter::new(true);

        let error_line = LogLine {
            timestamp: 0.into(),
            level: log::Level::Error,
            color: crate::enums::LogColor::Normal,
            component: ustr::Ustr::from("Test"),
            message: "error".to_string(),
            fields: SmallVec::new(),
        };
        assert!(writer.enabled(&error_line));

        let warn_line = LogLine {
            timestamp: 0.into(),
            level: log::Level::Warn,
            color: crate::enums::LogColor::Normal,
            component: ustr::Ustr::from("Test"),
            message: "warn".to_string(),
            fields: SmallVec::new(),
        };
        assert!(!writer.enabled(&warn_line));
    }
}