Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(flushguard): provide interface to close trace manually #10

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 28 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use std::{
atomic::{AtomicU64, Ordering},
mpsc::Sender,
Arc, Mutex,
},
}, fs::File,
};

use std::io::{BufWriter, Write};
Expand Down Expand Up @@ -207,6 +207,17 @@ impl FlushGuard {
self.handle.set(Some(handle));
}
}

/// Signals the trace writing thread to flush to disk, then close subscriber.
/// Unlike flush, subsequent trace will no longer recorded.
pub fn close(&self) {
if let Some(handle) = self.handle.take() {
let _ignored = self.sender.send(Message::Close);
if handle.join().is_err() {
eprintln!("tracing_chrome: Trace writing thread panicked.");
}
}
}
}

impl Drop for FlushGuard {
Expand Down Expand Up @@ -236,6 +247,7 @@ enum Message {
NewThread(u64, String),
Flush,
Drop,
Close,
}

pub enum EventOrSpan<'a, 'b, S>
Expand Down Expand Up @@ -270,11 +282,24 @@ where
write.write_all(b"[\n").unwrap();

let mut has_started = false;
let mut has_completed = false;
let mut flush_trace = |writer: &mut BufWriter<File>| {
if !has_completed {
has_completed = true;
writer.write_all(b"\n]").unwrap();
writer.flush().unwrap();
}
};

for msg in rx {
if let Message::Flush = &msg {
write.flush().unwrap();
continue;
} else if let Message::Drop = &msg {
flush_trace(&mut write);
break;
} else if let Message::Close = &msg {
flush_trace(&mut write);
break;
}

Expand All @@ -291,7 +316,7 @@ where
("e", Some(ts), Some(callsite), Some(root_id))
}
Message::NewThread(_tid, _name) => ("M", None, None, None),
Message::Flush | Message::Drop => panic!("Was supposed to break by now."),
Message::Flush | Message::Drop | Message::Close => panic!("Was supposed to break by now."),
};
entry.insert("ph", ph.to_string().into());
entry.insert("pid", 1.into());
Expand Down Expand Up @@ -342,8 +367,7 @@ where
has_started = true;
}

write.write_all(b"\n]").unwrap();
write.flush().unwrap();
flush_trace(&mut write);
});

let guard = FlushGuard {
Expand Down