Skip to main content

tale_ndjson/
config.rs

1//! A module to corral configuration to the side and into a single
2//! source of truth. Provides conveniences for answering config
3//! questions without having to pass batons around.
4
5use std::path::PathBuf;
6
7/// Read-only view of the parsed CLI options. The binary crate (`main.rs`)
8/// owns the clap-derived `Args` struct and implements this trait for it.
9/// Keeping the lib's config construction behind a trait keeps `clap` (and any
10/// future CLI parser) out of the library's public surface.
11pub trait CliOptions {
12    fn follow(&self) -> bool;
13    fn sticky(&self) -> bool;
14    fn bytes(&self) -> Option<i64>;
15    fn offset(&self) -> Option<i64>;
16    fn verbose(&self) -> bool;
17    fn quiet(&self) -> bool;
18    fn timestamps(&self) -> bool;
19    fn window(&self) -> u64;
20    fn chunked(&self) -> bool;
21    fn no_chunked(&self) -> bool;
22    fn max_memory(&self) -> Option<usize>;
23    fn args(&self) -> &[String];
24    #[cfg(debug_assertions)]
25    fn profile_json(&self) -> bool;
26}
27
28/// A sensible holder for our configuration.
29#[derive(Debug, Clone, Default)]
30pub struct ConfigOpts {
31    pub tailing: bool,
32    pub sticky: bool,
33    pub offset: i64,
34    pub offset_unit: OffsetUnit,
35    pub show_time: bool,
36    pub batch_window_ms: u64,
37    pub mode: InputMode,
38    pub force_chunked: bool,
39    pub disable_chunked: bool,
40    pub no_file_names: bool,
41    pub all_file_names: bool,
42    pub max_memory: Option<usize>,
43    #[cfg(debug_assertions)]
44    pub profile_json: bool,
45}
46
47#[derive(Debug, Clone, Default, Copy)]
48pub enum OffsetUnit {
49    #[default]
50    Lines,
51    Bytes,
52}
53
54/// Operation modes for tale
55#[derive(Debug, Clone, Default)]
56pub enum InputMode {
57    /// Read from stdin
58    #[default]
59    Stdin,
60    /// Read from a single file
61    SingleFile { path: PathBuf },
62    /// Watch multiple files
63    MultiFile { paths: Vec<PathBuf> },
64}
65
66// Production implementation: Simple OnceLock for fast access
67#[cfg(not(test))]
68mod runtime {
69    use std::sync::OnceLock;
70
71    use super::ConfigOpts;
72
73    /// Hold our configuration - production uses simple OnceLock
74    pub static CONFIG: OnceLock<ConfigOpts> = OnceLock::new();
75
76    /// Get reference to configuration
77    pub fn config() -> &'static ConfigOpts {
78        CONFIG
79            .get()
80            .expect("programmer error: tried to access configuration before it was set")
81    }
82
83    /// Set configuration - one-time initialization only
84    pub fn set(input: ConfigOpts) -> Result<(), Box<ConfigOpts>> {
85        match CONFIG.set(input) {
86            Ok(_) => Ok(()),
87            Err(e) => Err(Box::new(e)),
88        }
89    }
90}
91
92// Test implementation: Thread-local storage for isolation
93#[cfg(test)]
94mod runtime {
95    use std::cell::RefCell;
96
97    use super::ConfigOpts;
98
99    // Test implementation uses thread-local storage for isolation
100    thread_local! {
101        pub static TEST_CONFIG: RefCell<Option<ConfigOpts>> = const { RefCell::new(None) };
102    }
103
104    /// Get configuration - returns owned value from thread-local storage
105    pub fn config() -> ConfigOpts {
106        TEST_CONFIG.with(|cfg| cfg.borrow().as_ref().cloned().unwrap_or_else(ConfigOpts::default))
107    }
108
109    /// Set configuration - can be called multiple times per thread
110    pub fn set(input: ConfigOpts) -> Result<(), Box<ConfigOpts>> {
111        TEST_CONFIG.with(|cfg| {
112            *cfg.borrow_mut() = Some(input);
113        });
114        Ok(())
115    }
116
117    /// Test-only helper to modify config in place
118    pub fn update<F>(f: F)
119    where
120        F: FnOnce(&mut ConfigOpts),
121    {
122        TEST_CONFIG.with(|cfg| {
123            let mut borrowed = cfg.borrow_mut();
124            if borrowed.is_none() {
125                *borrowed = Some(ConfigOpts::default());
126            }
127            if let Some(ref mut config) = borrowed.as_mut() {
128                f(config);
129            }
130        });
131    }
132
133    /// Test-only helper for temporary config changes
134    pub fn with_config<F, R>(new_config: ConfigOpts, f: F) -> R
135    where
136        F: FnOnce() -> R,
137    {
138        // Save old config
139        let old_config = TEST_CONFIG.with(|cfg| cfg.borrow().clone());
140
141        // Set new config
142        TEST_CONFIG.with(|cfg| {
143            *cfg.borrow_mut() = Some(new_config);
144        });
145
146        // Run the test
147        let result = f();
148
149        // Restore old config
150        TEST_CONFIG.with(|cfg| {
151            *cfg.borrow_mut() = old_config;
152        });
153
154        result
155    }
156}
157
158// Re-export the runtime implementation as the public API
159use miette::Result;
160pub use runtime::{config, set};
161#[cfg(test)]
162pub use runtime::{update, with_config};
163
164use crate::defaults::{SystemDefaults, get_system_config};
165use crate::errors::TaleError;
166
167// Public convenience accessors. `config()` returns `&'static ConfigOpts` in
168// production (via OnceLock) and an owned `ConfigOpts` in tests (via
169// thread-local). Field access works on both.
170pub fn tailing() -> bool {
171    config().tailing
172}
173
174pub fn sticky() -> bool {
175    config().sticky
176}
177
178pub fn offset() -> i64 {
179    config().offset
180}
181
182pub fn offset_unit() -> OffsetUnit {
183    config().offset_unit
184}
185
186pub fn show_time() -> bool {
187    config().show_time
188}
189
190pub fn batch_window_ms() -> u64 {
191    config().batch_window_ms
192}
193
194pub fn force_chunked() -> bool {
195    config().force_chunked
196}
197
198pub fn disable_chunked() -> bool {
199    config().disable_chunked
200}
201
202pub fn mode() -> InputMode {
203    config().mode.clone()
204}
205
206/// Unescape shell-escaped glob patterns (e.g., \* -> *, \? -> ?, \[ -> [)
207fn unescape_glob_pattern(pattern: &str) -> String {
208    let mut result = String::new();
209    let mut chars = pattern.chars().peekable();
210
211    while let Some(ch) = chars.next() {
212        if ch == '\\' {
213            // Check if next character is a glob metacharacter
214            if let Some(&next_ch) = chars.peek() {
215                if matches!(next_ch, '*' | '?' | '[' | ']' | '{' | '}') {
216                    // Skip the backslash and add the escaped character
217                    chars.next();
218                    result.push(next_ch);
219                } else {
220                    // Not escaping a glob metacharacter, keep the backslash
221                    result.push(ch);
222                }
223            } else {
224                // Backslash at end of string
225                result.push(ch);
226            }
227        } else {
228            result.push(ch);
229        }
230    }
231
232    result
233}
234
235/// Check if a string contains glob patterns, including shell-escaped ones
236fn is_glob(maybe: &str) -> bool {
237    // Check for unescaped glob patterns, for users who turn on noglob.
238    if maybe.contains('?') || maybe.contains('*') || maybe.contains('[') || maybe.contains('{') {
239        return true;
240    }
241
242    // Check for shell-escaped glob patterns
243    maybe.contains("\\*") || maybe.contains("\\?") || maybe.contains("\\[") || maybe.contains("\\{")
244}
245
246/// Amongst our list of files to tail we might have a glob pattern
247/// to expand. If so, we find matches. Otherwise, we add that path
248/// to our list directly.
249fn expand_globs(args: &[String]) -> Result<Vec<PathBuf>, TaleError> {
250    let mut all_paths = Vec::new();
251
252    for candidate in args {
253        if is_glob(candidate.as_str()) {
254            // Unescape shell-escaped glob patterns before expansion
255            let unescaped_pattern = unescape_glob_pattern(candidate);
256            let pattern = glob::glob(&unescaped_pattern)?;
257            for fpath in pattern.flatten() {
258                if fpath.is_file() {
259                    all_paths.push(fpath);
260                }
261            }
262        } else {
263            let fpath = PathBuf::from(candidate);
264            if fpath.exists() && fpath.is_file() {
265                all_paths.push(fpath);
266            }
267        }
268    }
269    all_paths.sort();
270    Ok(all_paths)
271}
272
273fn handle_possible_paths(args: &[String]) -> Result<Vec<PathBuf>, TaleError> {
274    match expand_globs(args) {
275        Ok(paths) => {
276            if paths.is_empty() {
277                // No files matched the glob pattern(s)
278                let patterns: Vec<String> = args.iter().map(|s| format!("'{}'", s)).collect();
279                Err(TaleError::from(Box::new(crate::errors::FileError::NotFound {
280                    path: PathBuf::from(patterns.join(", ")),
281                    similar_files: vec![
282                        "Check if the glob pattern is correct".to_string(),
283                        "Verify the files exist in the specified directory".to_string(),
284                        "Try using an absolute path".to_string(),
285                    ],
286                })))
287            } else {
288                Ok(paths)
289            }
290        }
291        Err(e) => {
292            // Glob expansion failed - could be invalid pattern or I/O error
293            Err(e)
294        }
295    }
296}
297
298impl ConfigOpts {
299    pub fn new(args: &impl CliOptions) -> Result<Self> {
300        // Get production defaults
301        let system_config = get_system_config();
302        let positional = args.args();
303        let (mode, maybe_offset) = match positional.len() {
304            0 => (InputMode::Stdin, None),
305            1 => {
306                let only = &positional[0];
307                if (only.starts_with('-') || only.starts_with('+'))
308                    && only.len() > 1
309                    && let Ok(offset) = only.parse::<i64>()
310                {
311                    // It's a numeric offset like "-4" or "+4"
312                    (InputMode::Stdin, Some(offset))
313                } else if is_glob(only) {
314                    // It's a glob pattern, handle as multi-file
315                    let paths = handle_possible_paths(std::slice::from_ref(only))?;
316                    (InputMode::MultiFile { paths }, None)
317                } else {
318                    // It's a single filename (may or may not exist) - always
319                    // treat as SingleFile
320                    (
321                        InputMode::SingleFile {
322                            path: PathBuf::from(only),
323                        },
324                        None,
325                    )
326                }
327            }
328            2 => {
329                let (first, second) = (&positional[0], &positional[1]);
330
331                // Check if first arg is an offset
332                if let Ok(offset) = first.parse::<i64>() {
333                    // offset + single file
334                    (
335                        InputMode::SingleFile {
336                            path: PathBuf::from(second),
337                        },
338                        Some(offset),
339                    )
340                } else {
341                    // Two file paths or globs: we're multifile for sure.
342                    let paths = handle_possible_paths(positional)?;
343                    (InputMode::MultiFile { paths }, None)
344                }
345            }
346            _ => {
347                // More than two paths and/or globs.
348                // We still want to know if the first arg is an offset.
349                let paths = handle_possible_paths(positional)?;
350                (InputMode::MultiFile { paths }, None)
351            }
352        };
353
354        let (offset, offset_unit) = if let Some(bytes) = args.bytes() {
355            (bytes, OffsetUnit::Bytes)
356        } else if let Some(lines) = args.offset() {
357            (lines, OffsetUnit::Lines)
358        } else if let Some(offset) = maybe_offset {
359            (offset, OffsetUnit::Lines)
360        } else {
361            (0, OffsetUnit::Lines)
362        };
363
364        // Apply production defaults
365        let max_memory = args.max_memory().unwrap_or_else(|| {
366            // Use production default memory budget
367            let system_percentage = system_config.memory_percentage;
368            if let Some(memory_stats) = memory_stats::memory_stats() {
369                let system_memory = memory_stats.physical_mem;
370                let calculated = (system_memory as f64 * system_percentage / 100.0) as usize;
371                calculated.clamp(SystemDefaults::MIN_MEMORY_BUDGET, SystemDefaults::MAX_MEMORY_BUDGET)
372            } else {
373                // Fallback to reasonable default
374                system_config.max_memory_mb * 1024 * 1024
375            }
376        });
377
378        // Determine chunking behavior based on production defaults if not
379        // specified
380        let force_chunked = if args.chunked() {
381            true
382        } else if args.no_chunked() {
383            false
384        } else {
385            // Use production default based on preset
386            system_config.force_chunked
387        };
388
389        Ok(Self {
390            tailing: args.follow() || args.sticky(),
391            sticky: args.sticky(),
392            offset,
393            offset_unit,
394            show_time: args.timestamps(),
395            batch_window_ms: args.window(),
396            mode,
397            force_chunked,
398            disable_chunked: args.no_chunked(),
399            no_file_names: args.quiet(),
400            all_file_names: args.verbose(),
401            max_memory: Some(max_memory),
402            #[cfg(debug_assertions)]
403            profile_json: args.profile_json(),
404        })
405    }
406}
407
408#[cfg(test)]
409mod tests {
410    use super::*;
411
412    /// Minimal CliOptions impl for tests. Builds a struct with all fields
413    /// at their defaults; tests override the ones they care about.
414    #[derive(Default)]
415    struct TestArgs {
416        follow: bool,
417        sticky: bool,
418        bytes: Option<i64>,
419        offset: Option<i64>,
420        verbose: bool,
421        quiet: bool,
422        timestamps: bool,
423        window: u64,
424        chunked: bool,
425        no_chunked: bool,
426        max_memory: Option<usize>,
427        positional: Vec<String>,
428    }
429
430    impl CliOptions for TestArgs {
431        fn follow(&self) -> bool {
432            self.follow
433        }
434        fn sticky(&self) -> bool {
435            self.sticky
436        }
437        fn bytes(&self) -> Option<i64> {
438            self.bytes
439        }
440        fn offset(&self) -> Option<i64> {
441            self.offset
442        }
443        fn verbose(&self) -> bool {
444            self.verbose
445        }
446        fn quiet(&self) -> bool {
447            self.quiet
448        }
449        fn timestamps(&self) -> bool {
450            self.timestamps
451        }
452        fn window(&self) -> u64 {
453            self.window
454        }
455        fn chunked(&self) -> bool {
456            self.chunked
457        }
458        fn no_chunked(&self) -> bool {
459            self.no_chunked
460        }
461        fn max_memory(&self) -> Option<usize> {
462            self.max_memory
463        }
464        fn args(&self) -> &[String] {
465            &self.positional
466        }
467        #[cfg(debug_assertions)]
468        fn profile_json(&self) -> bool {
469            false
470        }
471    }
472
473    #[test]
474    fn complicated_args() {
475        // bytes=Some(-5) wins over the positional "-4" offset; mode stays
476        // stdin.
477        let args = TestArgs {
478            timestamps: true,
479            follow: true,
480            bytes: Some(-5),
481            window: 250,
482            positional: vec!["-4".to_string()],
483            max_memory: Some(10_000_000_000),
484            ..Default::default()
485        };
486        let config = ConfigOpts::new(&args).expect("Config should be valid for test");
487        assert_eq!(config.offset, -5);
488        assert!(matches!(config.mode, InputMode::Stdin));
489    }
490
491    #[test]
492    fn glob_expansions() {
493        let fixture_glob = "./fixtures/*.log".to_string();
494        let results = expand_globs(&[fixture_glob]).expect("this list of paths should expand successfully");
495        assert_eq!(results.len(), 8); // changes if we add fixtures to that directory
496        assert_eq!(
497            results.as_slice(),
498            vec![
499                PathBuf::from("fixtures/ascii_colors.log"),
500                PathBuf::from("fixtures/garbage_prefix.log"),
501                PathBuf::from("fixtures/java_stacktrace.log"),
502                PathBuf::from("fixtures/just_loglines.log"),
503                PathBuf::from("fixtures/log4j.log"),
504                PathBuf::from("fixtures/mixed_json_types.log"),
505                PathBuf::from("fixtures/mixed_text_json.log"),
506                PathBuf::from("fixtures/windows_line_endings.log")
507            ]
508        );
509    }
510
511    #[test]
512    fn can_unescape_glob_pattern() {
513        // Test basic unescaping
514        assert_eq!(unescape_glob_pattern("\\*.log"), "*.log");
515        assert_eq!(unescape_glob_pattern("test\\?.txt"), "test?.txt");
516        assert_eq!(unescape_glob_pattern("\\[abc\\]"), "[abc]");
517
518        // Test mixed patterns
519        assert_eq!(unescape_glob_pattern("\\*.log\\?"), "*.log?");
520        assert_eq!(unescape_glob_pattern("test\\*file\\?.log"), "test*file?.log");
521
522        // Test non-glob backslashes (should be preserved)
523        assert_eq!(unescape_glob_pattern("file\\name.txt"), "file\\name.txt");
524        assert_eq!(unescape_glob_pattern("path\\to\\file"), "path\\to\\file");
525
526        // Test already unescaped patterns (should be unchanged)
527        assert_eq!(unescape_glob_pattern("*.log"), "*.log");
528        assert_eq!(unescape_glob_pattern("test?.txt"), "test?.txt");
529
530        // Test empty and edge cases
531        assert_eq!(unescape_glob_pattern(""), "");
532        assert_eq!(unescape_glob_pattern("\\"), "\\");
533        assert_eq!(unescape_glob_pattern("file\\"), "file\\");
534    }
535
536    #[test]
537    fn is_glob_with_escaped_patterns_works() {
538        // Test escaped glob patterns
539        assert!(is_glob("\\*.log"));
540        assert!(is_glob("test\\?.txt"));
541        assert!(is_glob("\\[abc]"));
542
543        // Test unescaped glob patterns (existing functionality)
544        assert!(is_glob("*.log"));
545        assert!(is_glob("test?.txt"));
546        assert!(is_glob("[abc]"));
547
548        // Test non-glob patterns
549        assert!(!is_glob("file.log"));
550        assert!(!is_glob("test.txt"));
551        assert!(!is_glob("path/to/file"));
552
553        // Test backslashes that don't escape glob chars
554        assert!(!is_glob("file\\name.txt"));
555        assert!(!is_glob("path\\to\\file"));
556    }
557
558    #[test]
559    fn can_expand_escaped_globs() {
560        // This test requires the fixtures directory to exist
561        // Test that escaped glob patterns work the same as unescaped ones
562        let escaped_fixture_glob = ".\\*/fixtures/\\*.log".to_string();
563        let normal_fixture_glob = "./fixtures/*.log".to_string();
564
565        // Both should expand to the same files (if fixtures exist)
566        if let (Ok(escaped_results), Ok(normal_results)) = (
567            expand_globs(&[escaped_fixture_glob]),
568            expand_globs(&[normal_fixture_glob]),
569        ) {
570            assert_eq!(escaped_results, normal_results);
571        }
572    }
573
574    #[test]
575    fn can_modify_config() {
576        let initial_config = ConfigOpts {
577            tailing: false,
578            sticky: false,
579            offset: 10,
580            offset_unit: OffsetUnit::Lines,
581            show_time: false,
582            batch_window_ms: 250,
583            mode: InputMode::Stdin,
584            force_chunked: false,
585            disable_chunked: false,
586            ..Default::default()
587        };
588
589        // Use with_config to isolate this test
590        with_config(initial_config.clone(), || {
591            // Test the update function
592            update(|cfg| {
593                cfg.tailing = true;
594                cfg.offset = 20;
595                cfg.show_time = true;
596            });
597
598            // Verify the changes
599            assert!(tailing());
600            assert_eq!(offset(), 20);
601            assert!(show_time());
602        });
603    }
604
605    #[test]
606    fn can_test_with_config() {
607        let original_config = ConfigOpts::default();
608        set(original_config.clone()).expect("should set config");
609
610        let original_offset = offset();
611        let original_tailing = tailing();
612
613        // Test with temporary config
614        let result = with_config(
615            ConfigOpts {
616                tailing: true,
617                sticky: false,
618                offset: 42,
619                offset_unit: OffsetUnit::Bytes,
620                show_time: true,
621                batch_window_ms: 500,
622                mode: InputMode::Stdin,
623                force_chunked: true,
624                disable_chunked: false,
625                ..Default::default()
626            },
627            || {
628                // Inside this closure, config should be changed
629                assert_eq!(offset(), 42);
630                assert!(tailing());
631                assert_eq!(batch_window_ms(), 500);
632                assert!(force_chunked());
633
634                // Return a value to verify the closure ran
635                "test_successful"
636            },
637        );
638
639        // After the closure, config should be restored
640        assert_eq!(offset(), original_offset);
641        assert_eq!(tailing(), original_tailing);
642        assert_eq!(result, "test_successful");
643    }
644
645    #[test]
646    fn concurrent_access_to_test_config() {
647        use std::thread;
648        use std::time::Duration;
649
650        // Set different configs in different threads to verify isolation
651        let handles: Vec<_> = (0..3)
652            .map(|i| {
653                thread::spawn(move || {
654                    let config = ConfigOpts {
655                        offset: i * 10,
656                        tailing: i % 2 == 0,
657                        show_time: i % 2 == 1,
658                        ..ConfigOpts::default()
659                    };
660
661                    set(config).expect("should set config");
662
663                    // Sleep a bit to let other threads potentially interfere
664                    thread::sleep(Duration::from_millis(10));
665
666                    // Verify our config is still correct
667                    assert_eq!(offset(), i * 10);
668                    assert_eq!(tailing(), i % 2 == 0);
669                    assert_eq!(show_time(), i % 2 == 1);
670
671                    i
672                })
673            })
674            .collect();
675
676        // Collect results
677        let results: Vec<_> = handles
678            .into_iter()
679            .map(|h| h.join().expect("test results should always be ok"))
680            .collect();
681        assert_eq!(results, vec![0, 1, 2]);
682    }
683
684    #[test]
685    fn config_accessors_work() {
686        let test_config = ConfigOpts {
687            tailing: true,
688            sticky: true,
689            offset: -100,
690            offset_unit: OffsetUnit::Bytes,
691            show_time: true,
692            batch_window_ms: 1000,
693            mode: InputMode::SingleFile {
694                path: PathBuf::from("test.log"),
695            },
696            force_chunked: true,
697            disable_chunked: false,
698            ..Default::default()
699        };
700
701        // Use with_config to isolate this test
702        with_config(test_config, || {
703            // Test all accessor functions
704            assert!(tailing());
705            assert!(sticky());
706            assert_eq!(offset(), -100);
707            assert!(matches!(offset_unit(), OffsetUnit::Bytes));
708            assert!(show_time());
709            assert_eq!(batch_window_ms(), 1000);
710            assert!(matches!(mode(), InputMode::SingleFile { .. }));
711            assert!(force_chunked());
712            assert!(!disable_chunked());
713        });
714    }
715}