Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions crates/hotfix/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@
//! for more detail.
use chrono::{NaiveTime, Weekday};
use chrono_tz::Tz;
use hotfix_message::dict::Dictionary;
use serde::Deserialize;
use std::fs;
use std::path::Path;
use std::sync::Arc;

/// The configuration for multiple sessions.
#[derive(Clone, Debug, Deserialize)]
Expand Down Expand Up @@ -80,6 +82,19 @@ pub struct SessionConfig {
/// The path to the data dictionary to use.
pub data_dictionary_path: Option<String>,

/// The data dictionary to use, passed as a value.
///
/// This allows a dictionary to be built or extended in memory (for example a
/// standard dictionary plus a counterparty's custom fields) rather than read from
/// a file. When set, it takes precedence over `data_dictionary_path`. It cannot be
/// set from a configuration file.
///
/// Sessions configured with the same `Arc` (and the same validation settings) share
/// one message parser, so running many sessions with one dictionary costs the
/// dictionary's memory once rather than once per session.
#[serde(skip)]
pub data_dictionary: Option<Arc<Dictionary>>,

/// The host to connect to.
///
/// This can be any representation of a host that can be interpreted
Expand Down
1 change: 1 addition & 0 deletions crates/hotfix/src/initiator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,7 @@ mod tests {
sender_comp_id: "TEST-SENDER".to_string(),
target_comp_id: "TEST-TARGET".to_string(),
data_dictionary_path: None,
data_dictionary: None,
connection_host: host.to_string(),
connection_port: port,
tls_config: None,
Expand Down
1 change: 1 addition & 0 deletions crates/hotfix/src/message/verification.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,7 @@ mod tests {
sender_comp_id: "SENDER".to_string(),
target_comp_id: "TARGET".to_string(),
data_dictionary_path: None,
data_dictionary: None,
connection_host: "localhost".to_string(),
connection_port: 9999,
tls_config: None,
Expand Down
101 changes: 98 additions & 3 deletions crates/hotfix/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use hotfix_message::dict::Dictionary;
use hotfix_message::message::{Config as MessageConfig, Message};
use hotfix_message::{MessageBuilder, Part};
use std::pin::Pin;
use std::sync::{Arc, Mutex, Weak};
use tokio::select;
use tokio::sync::mpsc;
use tokio::time::{Duration, Instant, Sleep, sleep, sleep_until};
Expand Down Expand Up @@ -58,6 +59,51 @@ use hotfix_message::session_fields::{MSG_SEQ_NUM, MSG_TYPE, SessionRejectReason,

const SCHEDULE_CHECK_INTERVAL: u64 = 1;

/// A message builder shared by every live session built from the same dictionary value.
type SharedBuilder = (Weak<Dictionary>, bool, Weak<MessageBuilder>);
static SHARED_MESSAGE_BUILDERS: Mutex<Vec<SharedBuilder>> = Mutex::new(Vec::new());

/// Returns the message builder for a dictionary passed as a value.
///
/// Sessions given the same `Arc<Dictionary>` and the same user-defined field validation
/// share one builder, which holds its own copy of the dictionary. Entries are held weakly,
/// so a builder is dropped with the last session using it.
fn shared_message_builder(
dictionary: &Arc<Dictionary>,
validate_user_defined_fields: bool,
message_config: MessageConfig,
) -> Result<Arc<MessageBuilder>, SessionCreationError> {
let mut shared = SHARED_MESSAGE_BUILDERS
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
shared.retain(|(dict, _, builder)| dict.strong_count() > 0 && builder.strong_count() > 0);

let existing = shared.iter().find_map(|(dict, validate, builder)| {
let same_dictionary = dict
.upgrade()
.is_some_and(|dict| Arc::ptr_eq(&dict, dictionary));
if same_dictionary && *validate == validate_user_defined_fields {
builder.upgrade()
} else {
None
}
});
if let Some(builder) = existing {
return Ok(builder);
}

let builder = Arc::new(MessageBuilder::new(
dictionary.as_ref().clone(),
message_config,
)?);
shared.push((
Arc::downgrade(dictionary),
validate_user_defined_fields,
Arc::downgrade(&builder),
));
Ok(builder)
}

struct Session<A, S> {
ctx: SessionCtx<A, S>,
schedule: SessionSchedule,
Expand All @@ -78,10 +124,19 @@ where
) -> Result<Session<App, Store>, SessionCreationError> {
let schedule_check_timer = sleep(Duration::from_secs(SCHEDULE_CHECK_INTERVAL));

let dictionary = Self::get_data_dictionary(&config)?;
let message_config = MessageConfig::default()
.validate_user_defined_fields(config.validation.validate_user_defined_fields);
let message_builder = MessageBuilder::new(dictionary, message_config)?;
let message_builder = match &config.data_dictionary {
Some(dictionary) => shared_message_builder(
dictionary,
config.validation.validate_user_defined_fields,
message_config,
)?,
None => Arc::new(MessageBuilder::new(
Self::get_data_dictionary(&config)?,
message_config,
)?),
};
let schedule = config.schedule.as_ref().try_into()?;
let ctx = SessionCtx {
config,
Expand Down Expand Up @@ -921,6 +976,7 @@ mod tests {
sender_comp_id: "SENDER".to_string(),
target_comp_id: "TARGET".to_string(),
data_dictionary_path: None,
data_dictionary: None,
connection_host: "localhost".to_string(),
connection_port: 9876,
tls_config: None,
Expand All @@ -942,7 +998,7 @@ mod tests {
let config = create_test_config();
let message_config = MessageConfig::default();
let dictionary = Dictionary::fix44();
let message_builder = MessageBuilder::new(dictionary, message_config).unwrap();
let message_builder = Arc::new(MessageBuilder::new(dictionary, message_config).unwrap());
let ctx = SessionCtx {
config,
store,
Expand Down Expand Up @@ -1177,4 +1233,43 @@ mod tests {
"Reconnect flag should be preserved"
);
}

#[test]
fn test_sessions_with_the_same_dictionary_value_share_a_message_builder() {
let dictionary = Arc::new(Dictionary::fix44());
let config = MessageConfig::default();

let first = shared_message_builder(&dictionary, true, config).unwrap();
let second = shared_message_builder(&dictionary, true, config).unwrap();
assert!(Arc::ptr_eq(&first, &second));

// a different validation setting gets its own builder
let unvalidated = shared_message_builder(
&dictionary,
false,
config.validate_user_defined_fields(false),
)
.unwrap();
assert!(!Arc::ptr_eq(&first, &unvalidated));

// an equal dictionary in a different Arc gets its own builder
let other_dictionary = Arc::new(Dictionary::fix44());
let other = shared_message_builder(&other_dictionary, true, config).unwrap();
assert!(!Arc::ptr_eq(&first, &other));
}

#[test]
fn test_shared_message_builder_is_dropped_with_its_last_session() {
let dictionary = Arc::new(Dictionary::fix44());
let config = MessageConfig::default();

let builder = shared_message_builder(&dictionary, true, config).unwrap();
let weak = Arc::downgrade(&builder);
drop(builder);
assert!(weak.upgrade().is_none());

// a later session builds a fresh one
let rebuilt = shared_message_builder(&dictionary, true, config).unwrap();
assert_eq!(Arc::strong_count(&rebuilt), 1);
}
}
2 changes: 1 addition & 1 deletion crates/hotfix/src/session/ctx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ pub(crate) struct SessionCtx<A, S> {
pub config: SessionConfig,
pub store: S,
pub application: A,
pub message_builder: MessageBuilder,
pub message_builder: std::sync::Arc<MessageBuilder>,
pub message_config: MessageConfig,
}

Expand Down
4 changes: 3 additions & 1 deletion crates/hotfix/src/session/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use chrono::{DateTime, Utc};
use hotfix_message::MessageBuilder;
use hotfix_message::dict::Dictionary;
use hotfix_message::message::Config as MessageConfig;
use std::sync::Arc;
use tokio::sync::mpsc;

#[derive(Clone)]
Expand Down Expand Up @@ -75,13 +76,14 @@ pub(crate) fn create_writer() -> (WriterRef, mpsc::Receiver<WriterMessage>) {
pub(crate) fn create_test_ctx(store: FakeMessageStore) -> SessionCtx<(), FakeMessageStore> {
let message_config = MessageConfig::default();
let dictionary = Dictionary::fix44();
let message_builder = MessageBuilder::new(dictionary, message_config).unwrap();
let message_builder = Arc::new(MessageBuilder::new(dictionary, message_config).unwrap());
SessionCtx {
config: SessionConfig {
begin_string: "FIX.4.4".to_string(),
sender_comp_id: "SENDER".to_string(),
target_comp_id: "TARGET".to_string(),
data_dictionary_path: None,
data_dictionary: None,
connection_host: "localhost".to_string(),
connection_port: 9876,
tls_config: None,
Expand Down
1 change: 1 addition & 0 deletions crates/hotfix/tests/connection_test_cases/connect_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ fn create_session_config(host: &str, port: u16, tls_config: Option<TlsConfig>) -
sender_comp_id: "TEST_SENDER".to_string(),
target_comp_id: "TEST_TARGET".to_string(),
data_dictionary_path: None,
data_dictionary: None,
connection_host: host.to_string(),
connection_port: port,
tls_config,
Expand Down
1 change: 1 addition & 0 deletions crates/hotfix/tests/session_test_cases/common/setup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ pub fn create_session_config() -> SessionConfig {
sender_comp_id: OUR_COMP_ID.to_string(),
target_comp_id: COUNTERPARTY_COMP_ID.to_string(),
data_dictionary_path: None,
data_dictionary: None,
connection_host: "".to_string(),
connection_port: 0,
tls_config: None,
Expand Down
1 change: 1 addition & 0 deletions examples/load-testing/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ fn get_config() -> SessionConfig {
sender_comp_id: "dummy-initiator".to_string(),
target_comp_id: "dummy-acceptor".to_string(),
data_dictionary_path: None,
data_dictionary: None,
connection_host: "127.0.0.1".to_string(),
connection_port: 9880,
tls_config: None,
Expand Down