Skip to main content

easyfix_dictionary/dictionary/
builder.rs

1use std::{
2    fs,
3    path::{Path, PathBuf},
4};
5
6use quick_xml::de::from_str;
7
8use super::{
9    Dictionary, Version,
10    error::{BuilderError, Error, ValidationError},
11};
12use crate::xml;
13
14/// Builder for creating and configuring FIX dictionaries.
15///
16/// This builder provides a fluent interface for configuring and creating
17/// a FIX protocol dictionary from XML specification files.
18pub struct DictionaryBuilder {
19    /// Path to the FIXT (transport) XML specification
20    fixt_xml_path: Option<PathBuf>,
21
22    /// Paths to FIX application-level XML specifications
23    fix_xml_paths: Vec<PathBuf>,
24
25    /// Allow custom FIX versions not in the standard list
26    allow_custom_version: bool,
27
28    /// Apply strict validation during parsing
29    strict_check: bool,
30
31    /// Whether to flatten component hierarchies
32    flatten_components: bool,
33}
34
35pub fn read_raw_dictionary(path: &Path) -> Result<xml::Dictionary, Error> {
36    let xml = fs::read_to_string(path)?;
37    Ok(from_str::<xml::Dictionary>(&xml)?)
38}
39
40pub fn read_raw_fixt_dictionary(path: &Path) -> Result<xml::Dictionary, Error> {
41    let raw_dictionary = read_raw_dictionary(path)?;
42    let version = raw_dictionary.version()?;
43
44    if !version.is_fixt() || version < Version::FIXT11 {
45        return Err(Error::Builder(BuilderError::IncompatibleVersion));
46    }
47    if raw_dictionary.header.members.is_empty() {
48        return Err(Error::Validation(ValidationError::EmptyContainer(
49            "Header".into(),
50        )));
51    }
52    if raw_dictionary.trailer.members.is_empty() {
53        return Err(Error::Validation(ValidationError::EmptyContainer(
54            "Trailer".into(),
55        )));
56    }
57    if let Some(msg) = raw_dictionary
58        .messages
59        .iter()
60        .find(|msg| !matches!(msg.msg_cat, xml::MsgCat::Admin))
61    {
62        return Err(Error::Validation(
63            ValidationError::UnexpectedMessageCategory(msg.msg_cat, msg.name.to_string()),
64        ));
65    }
66
67    Ok(raw_dictionary)
68}
69
70pub fn read_raw_fix_dictionary(path: &Path) -> Result<xml::Dictionary, Error> {
71    let raw_dictionary = read_raw_dictionary(path)?;
72    let version = raw_dictionary.version()?;
73
74    if !version.is_fix() {
75        return Err(Error::Builder(BuilderError::IncompatibleVersion));
76    } else if version >= Version::FIX50 {
77        if !raw_dictionary.header.members.is_empty() {
78            return Err(Error::Validation(ValidationError::EmptyContainer(
79                "Header".into(),
80            )));
81        }
82        if !raw_dictionary.trailer.members.is_empty() {
83            return Err(Error::Validation(ValidationError::EmptyContainer(
84                "Trailer".into(),
85            )));
86        }
87        if let Some(msg) = raw_dictionary
88            .messages
89            .iter()
90            .find(|msg| !matches!(msg.msg_cat, xml::MsgCat::App))
91        {
92            return Err(Error::Validation(
93                ValidationError::UnexpectedMessageCategory(msg.msg_cat, msg.name.to_string()),
94            ));
95        }
96    } else {
97        if raw_dictionary.header.members.is_empty() {
98            return Err(Error::Validation(ValidationError::EmptyContainer(
99                "Header".into(),
100            )));
101        }
102        if raw_dictionary.trailer.members.is_empty() {
103            return Err(Error::Validation(ValidationError::EmptyContainer(
104                "Trailer".into(),
105            )));
106        }
107    }
108
109    Ok(raw_dictionary)
110}
111
112impl Default for DictionaryBuilder {
113    fn default() -> Self {
114        Self::new()
115    }
116}
117
118impl DictionaryBuilder {
119    /// Creates a new, empty DictionaryBuilder with default settings
120    ///
121    /// Use the builder's methods to configure and then call `build()` to create
122    /// the dictionary.
123    pub fn new() -> DictionaryBuilder {
124        DictionaryBuilder {
125            fixt_xml_path: None,
126            fix_xml_paths: Vec::new(),
127            allow_custom_version: false,
128            strict_check: false,
129            flatten_components: false,
130        }
131    }
132
133    /// Sets whether to allow custom FIX versions not in the standard list
134    ///
135    /// By default, only standard FIX versions are accepted.
136    pub fn allow_custom_version(mut self, allow_custom_version: bool) -> Self {
137        self.allow_custom_version = allow_custom_version;
138        self
139    }
140
141    /// Sets whether to apply strict validation during dictionary parsing
142    ///
143    /// When enabled, more rigorous checks are applied to the dictionary structure.
144    pub fn with_strict_check(mut self, strict_check: bool) -> Self {
145        self.strict_check = strict_check;
146        self
147    }
148
149    /// Adds a FIX application-level XML specification file to the builder
150    ///
151    /// For FIX versions prior to 5.0, this is the only XML file needed.
152    /// For FIX 5.0+, this should be used along with `with_fixt_xml()`.
153    pub fn with_fix_xml(mut self, path: impl Into<PathBuf>) -> Self {
154        self.fix_xml_paths.push(path.into());
155        self
156    }
157
158    /// Adds multiple FIX application-level XML specification files to the builder
159    ///
160    /// This is useful when working with multiple FIX versions or custom extensions.
161    pub fn with_fix_xmls(mut self, paths: impl IntoIterator<Item = PathBuf>) -> Self {
162        self.fix_xml_paths.extend(paths);
163        self
164    }
165
166    /// Sets the FIXT transport layer XML specification file
167    ///
168    /// This is required for FIX 5.0+ versions, which separate transport (FIXT)
169    /// from application (FIX) layer specifications.
170    pub fn with_fixt_xml(mut self, path: impl Into<PathBuf>) -> Self {
171        self.fixt_xml_path = Some(path.into());
172        self
173    }
174
175    /// Sets whether to flatten component hierarchies
176    ///
177    /// When enabled, nested components are flattened into their parent containers.
178    /// This simplifies the structure by removing intermediate component layers,
179    /// resulting in direct field references in messages and groups.
180    ///
181    /// For example, if Message A contains Component B which contains Field C,
182    /// flattening would make Message A directly contain Field C. The resulting
183    /// dictionary has no components left, so code generation never has to
184    /// resolve one.
185    pub fn flatten_components(mut self, flatten_components: bool) -> Self {
186        self.flatten_components = flatten_components;
187        self
188    }
189
190    /// Builds the Dictionary from the configured sources
191    ///
192    /// This method parses the XML files and constructs a complete FIX dictionary.
193    /// It will return an error if the dictionary configuration is invalid or if
194    /// parsing fails.
195    pub fn build(self) -> Result<Dictionary, Error> {
196        match (self.fixt_xml_path, self.fix_xml_paths.as_slice()) {
197            (None, []) => Err(Error::Builder(BuilderError::Unspecified)),
198            (None, [fix_xml_path]) => {
199                // Legacy FIX version
200                let dict = read_raw_fix_dictionary(fix_xml_path)?;
201                let dictionary = Dictionary::from_raw_dictionary(
202                    dict,
203                    self.flatten_components,
204                    self.strict_check,
205                )?;
206                if self.flatten_components {
207                    Ok(dictionary.flatten()?)
208                } else {
209                    Ok(dictionary)
210                }
211            }
212            (None, [_, ..]) => Err(Error::Builder(BuilderError::IncompatibleVersion)),
213            (Some(fixt_xml_path), fix_xml_paths) => {
214                let fixt = read_raw_fixt_dictionary(&fixt_xml_path)?;
215                let mut fixt_dict = Dictionary::from_raw_dictionary(
216                    fixt,
217                    self.flatten_components,
218                    self.strict_check,
219                )?;
220
221                for fix_xml_path in fix_xml_paths {
222                    let fix = read_raw_fix_dictionary(fix_xml_path)?;
223                    if fix.major < 5 {
224                        return Err(Error::Builder(BuilderError::IncompatibleVersion));
225                    }
226                    let subdict = Dictionary::from_raw_dictionary(
227                        fix,
228                        self.flatten_components,
229                        self.strict_check,
230                    )?;
231                    fixt_dict.subdictionaries.insert(subdict.version, subdict);
232                }
233
234                if self.flatten_components {
235                    Ok(fixt_dict.flatten()?)
236                } else {
237                    Ok(fixt_dict)
238                }
239            }
240        }
241    }
242}