Skip to content

Commit

Permalink
keylogfile update: canonicalize + create parent dirs
Browse files Browse the repository at this point in the history
  • Loading branch information
GlenDC committed Nov 14, 2024
1 parent 0b3feb5 commit 7ad8fdf
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions rama-tls/src/keylog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use std::{
collections::{hash_map::Entry, HashMap},
fs::OpenOptions,
io::Write,
path::PathBuf,
sync::OnceLock,
};

Expand All @@ -21,6 +22,8 @@ use std::{
/// Paths are case-sensitive by default for rama, as utf-8 compatible.
/// Normalize yourself prior to passing a path to this function if you're concerned.
pub fn new_key_log_file_handle(path: String) -> Result<KeyLogFileHandle, OpaqueError> {
let path = std::fs::canonicalize(path).context("canonicalize keylog path")?;

let mapping = GLOBAL_KEY_LOG_FILE_MAPPING.get_or_init(Default::default);
if let Some(handle) = mapping.read().get(&path).cloned() {
return Ok(handle);
Expand All @@ -36,12 +39,16 @@ pub fn new_key_log_file_handle(path: String) -> Result<KeyLogFileHandle, OpaqueE
}
}

fn try_init_key_log_file_handle(path: String) -> Result<KeyLogFileHandle, OpaqueError> {
fn try_init_key_log_file_handle(path: PathBuf) -> Result<KeyLogFileHandle, OpaqueError> {
tracing::trace!(
file = ?path,
"KeyLogFileHandle: try to create a new handle",
);

if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).context("create parent dir(s) of key log file")?;
}

let mut file = OpenOptions::new()
.append(true)
.create(true)
Expand All @@ -59,7 +66,7 @@ fn try_init_key_log_file_handle(path: String) -> Result<KeyLogFileHandle, Opaque
while let Ok(line) = rx.recv() {
if let Err(err) = file.write_all(line.as_bytes()) {
tracing::error!(
file = path_name,
file = ?path_name,
error = %err,
"KeyLogFileHandle[rx]: failed to write file",
);
Expand All @@ -70,7 +77,7 @@ fn try_init_key_log_file_handle(path: String) -> Result<KeyLogFileHandle, Opaque
Ok(KeyLogFileHandle { path, sender: tx })
}

static GLOBAL_KEY_LOG_FILE_MAPPING: OnceLock<RwLock<HashMap<String, KeyLogFileHandle>>> =
static GLOBAL_KEY_LOG_FILE_MAPPING: OnceLock<RwLock<HashMap<PathBuf, KeyLogFileHandle>>> =
OnceLock::new();

#[derive(Debug, Clone)]
Expand All @@ -79,7 +86,7 @@ static GLOBAL_KEY_LOG_FILE_MAPPING: OnceLock<RwLock<HashMap<String, KeyLogFileHa
/// See [`new_key_log_file_handle`] for more info,
/// as that is the one creating it.
pub struct KeyLogFileHandle {
path: String,
path: PathBuf,
sender: flume::Sender<String>,
}

Expand All @@ -88,7 +95,7 @@ impl KeyLogFileHandle {
pub fn write_log_line(&self, line: String) {
if let Err(err) = self.sender.send(line) {
tracing::error!(
file = %self.path,
file = ?self.path,
error = %err,
"KeyLogFileHandle[tx]: failed to send log line for writing",
);
Expand Down

0 comments on commit 7ad8fdf

Please sign in to comment.