diff --git a/crates/hotfix/src/config.rs b/crates/hotfix/src/config.rs index b13a854..36297a4 100644 --- a/crates/hotfix/src/config.rs +++ b/crates/hotfix/src/config.rs @@ -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)] @@ -80,6 +82,19 @@ pub struct SessionConfig { /// The path to the data dictionary to use. pub data_dictionary_path: Option, + /// 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>, + /// The host to connect to. /// /// This can be any representation of a host that can be interpreted diff --git a/crates/hotfix/src/initiator.rs b/crates/hotfix/src/initiator.rs index 782df5d..0d7e105 100644 --- a/crates/hotfix/src/initiator.rs +++ b/crates/hotfix/src/initiator.rs @@ -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, diff --git a/crates/hotfix/src/message/verification.rs b/crates/hotfix/src/message/verification.rs index aaa1b76..3bc2b0a 100644 --- a/crates/hotfix/src/message/verification.rs +++ b/crates/hotfix/src/message/verification.rs @@ -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, diff --git a/crates/hotfix/src/session.rs b/crates/hotfix/src/session.rs index 440b87c..cd9847d 100644 --- a/crates/hotfix/src/session.rs +++ b/crates/hotfix/src/session.rs @@ -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}; @@ -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, bool, Weak); +static SHARED_MESSAGE_BUILDERS: Mutex> = Mutex::new(Vec::new()); + +/// Returns the message builder for a dictionary passed as a value. +/// +/// Sessions given the same `Arc` 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, + validate_user_defined_fields: bool, + message_config: MessageConfig, +) -> Result, 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 { ctx: SessionCtx, schedule: SessionSchedule, @@ -78,10 +124,19 @@ where ) -> Result, 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, @@ -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, @@ -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, @@ -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); + } } diff --git a/crates/hotfix/src/session/ctx.rs b/crates/hotfix/src/session/ctx.rs index 75c2fa5..76a10ec 100644 --- a/crates/hotfix/src/session/ctx.rs +++ b/crates/hotfix/src/session/ctx.rs @@ -44,7 +44,7 @@ pub(crate) struct SessionCtx { pub config: SessionConfig, pub store: S, pub application: A, - pub message_builder: MessageBuilder, + pub message_builder: std::sync::Arc, pub message_config: MessageConfig, } diff --git a/crates/hotfix/src/session/test_utils.rs b/crates/hotfix/src/session/test_utils.rs index 6db4649..3b348e2 100644 --- a/crates/hotfix/src/session/test_utils.rs +++ b/crates/hotfix/src/session/test_utils.rs @@ -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)] @@ -75,13 +76,14 @@ pub(crate) fn create_writer() -> (WriterRef, mpsc::Receiver) { 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, diff --git a/crates/hotfix/tests/connection_test_cases/connect_tests.rs b/crates/hotfix/tests/connection_test_cases/connect_tests.rs index ff1d683..a54df9a 100644 --- a/crates/hotfix/tests/connection_test_cases/connect_tests.rs +++ b/crates/hotfix/tests/connection_test_cases/connect_tests.rs @@ -17,6 +17,7 @@ fn create_session_config(host: &str, port: u16, tls_config: Option) - 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, diff --git a/crates/hotfix/tests/session_test_cases/common/setup.rs b/crates/hotfix/tests/session_test_cases/common/setup.rs index 7ff6c03..b49861f 100644 --- a/crates/hotfix/tests/session_test_cases/common/setup.rs +++ b/crates/hotfix/tests/session_test_cases/common/setup.rs @@ -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, diff --git a/examples/load-testing/src/main.rs b/examples/load-testing/src/main.rs index b4d2568..cea0710 100644 --- a/examples/load-testing/src/main.rs +++ b/examples/load-testing/src/main.rs @@ -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,