//! The log's file, its rotation, its echo and what it never holds (#142). use std::fs; use std::io::{self, Write}; use std::path::Path; use std::sync::{Arc, Mutex}; use log::{Level, Log, Metadata, Record}; use super::*; fn write(journal: &Journal, text: &str) { journal.log( &Record::builder() .level(Level::Info) .target("arena_tracker_core::follow") .args(format_args!("{text}")) .build(), ); } /// Waits until the writer has written all that was queued. Unlike `Log::flush`, which gives up /// after `FLUSH_WAIT` (a slow machine may still be rotating), it waits as long as it takes. fn drain(journal: &Journal) { let (ack, done) = mpsc::channel(); journal.tx.send(Msg::Flush(ack)).unwrap(); done.recv().unwrap(); } fn read(dir: &Path, name: &str) -> String { fs::read_to_string(dir.join(name)).unwrap_or_default() } fn names(dir: &Path) -> Vec { let mut names: Vec<_> = fs::read_dir(dir) .unwrap() .map(|e| e.unwrap().file_name().into_string().unwrap()) .collect(); names.sort(); names } #[test] fn long_tokens_are_masked_and_the_rest_kept() { let puuid = "x".repeat(78); assert_eq!( mask_long_tokens(&format!("a {puuid} é#EUW, EUW1_7 {puuid}")), "a xxxxxxxx… é#EUW, EUW1_7 xxxxxxxx…" ); assert_eq!(short("abcdefghij"), "abcdefgh"); assert_eq!(short("abc"), "abc"); } #[test] fn past_one_megabyte_the_file_becomes_the_old_one_and_never_more_than_two_exist() { let dir = tempfile::tempdir().unwrap(); let journal = Journal::open(dir.path(), None, || {}).unwrap(); let line = format!("{}end", "word ".repeat(200)); // About 3.5 MB: the file rotates three times. for i in 0..3500 { write(&journal, &format!("{i} {line}")); } drain(&journal); assert_eq!( names(dir.path()), ["arena-tracker.1.log", "arena-tracker.log"] ); for name in ["arena-tracker.log", "arena-tracker.1.log"] { let size = fs::metadata(dir.path().join(name)).unwrap().len(); assert!((1..=1_000_000).contains(&size), "{name}: {size}"); } assert!(read(dir.path(), "arena-tracker.log").contains("3499 word")); // The old file holds the lines just before the current one's first. let first: u32 = (read(dir.path(), "arena-tracker.log") .split_whitespace() .nth(2)) .and_then(|n| n.parse().ok()) .unwrap(); let old = read(dir.path(), "arena-tracker.1.log"); assert!( old.lines() .last() .unwrap() .contains(&format!(" {} word", first - 1)) ); } #[test] fn an_existing_file_is_appended_to_and_rotates_from_its_size() { let dir = tempfile::tempdir().unwrap(); fs::write(dir.path().join("arena-tracker.log"), "x ".repeat(400_000)).unwrap(); let journal = Journal::open(dir.path(), None, || {}).unwrap(); write(&journal, "first"); drain(&journal); assert_eq!(names(dir.path()), ["arena-tracker.log"]); assert!(read(dir.path(), "arena-tracker.log").ends_with("first\n")); write(&journal, &"long ".repeat(50_000)); drain(&journal); assert_eq!( names(dir.path()), ["arena-tracker.1.log", "arena-tracker.log"] ); } #[derive(Clone, Default)] struct Echo(Arc>>); impl Write for Echo { fn write(&mut self, buf: &[u8]) -> io::Result { self.0.lock().unwrap().extend_from_slice(buf); Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } #[test] fn an_echo_sink_gets_the_same_lines_as_the_file() { let dir = tempfile::tempdir().unwrap(); let echo = Echo::default(); let journal = Journal::open(dir.path(), Some(Box::new(echo.clone())), || {}).unwrap(); journal.launch("1.2.3", "stable"); write(&journal, "hello"); drain(&journal); let echoed = String::from_utf8(echo.0.lock().unwrap().clone()).unwrap(); assert_eq!(echoed, read(dir.path(), "arena-tracker.log")); assert_eq!(echoed.lines().count(), 2); } #[test] fn a_key_or_a_full_puuid_in_a_line_is_masked() { let dir = tempfile::tempdir().unwrap(); let journal = Journal::open(dir.path(), None, || {}).unwrap(); let key = "RGAPI-12345678-abcd-ef01-2345-6789abcdef01"; let puuid = "a1b2c3d4".repeat(9) + "-_"; write( &journal, &format!("key {key}, puuid {puuid}, id Joueur#EUW, EUW1_7"), ); drain(&journal); let text = read(dir.path(), "arena-tracker.log"); assert!(!text.contains(key) && !text.contains(&puuid), "{text}"); assert!( text.contains("RGAPI-12…, puuid a1b2c3d4…, id Joueur#EUW, EUW1_7"), "{text}" ); } #[test] fn a_folder_that_cannot_be_created_is_an_error_not_a_panic() { let dir = tempfile::tempdir().unwrap(); let file = dir.path().join("file"); fs::write(&file, "").unwrap(); assert!(Journal::open(&file.join("logs"), None, || {}).is_err()); } #[test] fn a_failed_rotation_keeps_writing_to_the_current_file() { let dir = tempfile::tempdir().unwrap(); // A non-empty folder where the old file goes: the rename fails. let old = dir.path().join("arena-tracker.1.log"); fs::create_dir(&old).unwrap(); fs::write(old.join("held"), "").unwrap(); let journal = Journal::open(dir.path(), None, || {}).unwrap(); let line = format!("{}end", "word ".repeat(200)); for i in 0..1500 { write(&journal, &format!("{i} {line}")); } write(&journal, "the last line"); drain(&journal); let text = read(dir.path(), "arena-tracker.log"); assert!(text.contains(" 0 word") && text.contains(" 1499 word")); assert!(text.ends_with("the last line\n")); } #[test] fn only_the_app_s_lines_and_other_libraries_errors_are_taken() { let dir = tempfile::tempdir().unwrap(); let journal = Journal::open(dir.path(), None, || {}).unwrap(); let enabled = |level, target| journal.enabled(&Metadata::builder().level(level).target(target).build()); assert!(enabled(Level::Info, "arena_tracker")); assert!(enabled(Level::Warn, "arena_tracker_core::riot")); assert!(!enabled(Level::Debug, "arena_tracker")); assert!(!enabled(Level::Trace, "arena_tracker")); // A library's info or warning may come per frame; its errors are kept. assert!(!enabled(Level::Info, "gpui::window")); assert!(!enabled(Level::Warn, "gpui::window")); assert!(enabled(Level::Error, "gpui::window")); // The HTTP client's lines may hold the URL or the key. assert!(!enabled(Level::Info, "ureq::unversioned::transport")); assert!(!enabled(Level::Error, "ureq")); }