Skip to content

Commit

Permalink
chore: Copy the in-mem logging functions to the FFI crate
Browse files Browse the repository at this point in the history
  • Loading branch information
rholshausen committed Sep 4, 2024
1 parent 1877010 commit 8a5150e
Showing 1 changed file with 41 additions and 2 deletions.
43 changes: 41 additions & 2 deletions rust/pact_ffi/src/log/inmem_buffer.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
//! In-memory buffer for logging output.
use std::collections::HashMap;
use std::io;
use std::io::Write;
use tracing_subscriber::fmt::MakeWriter;
use std::sync::Mutex;

use pact_matching::logging::write_to_log_buffer;
use bytes::{BufMut, Bytes, BytesMut};
use lazy_static::lazy_static;
use tokio::task_local;
use tracing_subscriber::fmt::MakeWriter;

/// In-memory buffer for logging output. Sends output to global static `LOG_BUFFER` in the pact_matching
/// crate. If there is a task local ID found, will accumulate against that ID, otherwise will
Expand All @@ -31,3 +35,38 @@ impl <'a> MakeWriter<'a> for InMemBuffer {
*self
}
}

lazy_static! {
/// Memory buffer for the buffer logger. This is needed here because there is no
/// way to get the logger sync from the Dispatch struct. The buffer will be emptied
/// when the contents is fetched via an FFI call.
///
/// Accumulates the log entries against a task local ID. If the ID is not set, accumulates against
/// the "global" ID.
/// cbindgen:ignore
static ref LOG_BUFFER: Mutex<HashMap<String, BytesMut>> = Mutex::new(HashMap::new());
}

task_local! {
/// Log ID to accumulate logs against
#[allow(missing_docs)]
pub static LOG_ID: String;
}

/// Fetches the contents from the id scoped in-memory buffer and empties the buffer.
pub fn fetch_buffer_contents(id: &str) -> Bytes {
let mut inner = LOG_BUFFER.lock().unwrap();
let buffer = inner.entry(id.to_string())
.or_insert_with(|| BytesMut::with_capacity(256));
buffer.split().freeze()
}

/// Writes the provided bytes to the task local ID scoped in-memory buffer. If there is no
/// task local ID set, will write to the "global" buffer.
pub fn write_to_log_buffer(buf: &[u8]) {
let id = LOG_ID.try_with(|id| id.clone()).unwrap_or_else(|_| "global".into());
let mut inner = LOG_BUFFER.lock().unwrap();
let buffer = inner.entry(id)
.or_insert_with(|| BytesMut::with_capacity(256));
buffer.put(buf);
}

0 comments on commit 8a5150e

Please sign in to comment.