easyfix-dictionary 0.20.0

Easy FIX (Financial Information Exchange) toolset - messages dictionary.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! Core dictionary implementation and data structures.
//!
//! This module provides the main implementation of the FIX dictionary, including:
//! - The `Dictionary` struct for accessing fields, components, and messages
//! - The `DictionaryBuilder` for configuring and creating dictionaries
//! - Type definitions for FIX protocol elements (Message, Component, Group, etc.)
//! - FIX protocol types (`MsgType`, `MsgCat`, etc.)
//! - Error handling for dictionary operations

mod builder;
mod error;
mod resolver;
mod types;

#[cfg(test)]
mod tests;

use std::{collections::HashMap, fs, rc::Rc};

pub use easyfix_core::version::{SessionProtocol, Version};
use easyfix_core::{
    basic_types::{FixStr, FixString},
    fix_str,
};
use quick_xml::de::from_str;

use self::resolver::{Elements, Resolver, check_required_fields};
pub use self::{
    builder::DictionaryBuilder,
    error::{BuilderError, Error, ValidationError},
    types::{Component, Field, Group, Member, MemberDefinition, Message, Variant},
};
use crate::xml;
pub use crate::xml::{BasicType, MsgCat, MsgType};

impl xml::Dictionary {
    /// Build a [`Version`] from this raw XML dictionary's header
    /// attributes.
    ///
    /// Returns [`BuilderError::UnknownVersion`] (carrying the formatted
    /// `BeginString`) when the version is not recognized.
    pub(crate) fn version(&self) -> Result<Version, Error> {
        Version::new(
            self.session_protocol,
            self.major,
            self.minor,
            self.servicepack,
        )
        .map_err(|_| {
            let begin_string = if self.servicepack == 0 {
                format!("{}.{}.{}", self.session_protocol, self.major, self.minor)
            } else {
                format!(
                    "{}.{}.{}SP{}",
                    self.session_protocol, self.major, self.minor, self.servicepack
                )
            };
            Error::Builder(BuilderError::UnknownVersion(begin_string))
        })
    }
}

/// The main dictionary representing a FIX protocol specification.
///
/// A `Dictionary` provides access to all elements of a FIX protocol
/// specification, including fields, components, messages, and version information.
/// For modern FIX versions (FIXT/FIX5+), it may also contain subdictionaries
/// for different message categories.
#[derive(Debug)]
pub struct Dictionary {
    /// The version of this dictionary
    version: Version,

    /// Fields indexed by name
    fields_by_name: HashMap<FixString, Rc<Field>>,

    /// Fields indexed by ID (tag number)
    fields_by_id: HashMap<u16, Rc<Field>>,

    /// Groups indexed by name
    groups: HashMap<FixString, Rc<Group>>,

    /// Components indexed by name
    components: HashMap<FixString, Rc<Component>>,

    /// Messages in definition order (from XML)
    messages: Vec<Rc<Message>>,

    /// Messages indexed by name
    messages_by_name: HashMap<FixString, Rc<Message>>,

    /// Messages indexed by message type
    messages_by_id: HashMap<MsgType, Rc<Message>>,

    /// Standard header component definition
    header: Component,

    /// Standard trailer component definition
    trailer: Component,

    /// Application-level subdictionaries (for FIXT-based versions)
    subdictionaries: HashMap<Version, Dictionary>,
}

impl Dictionary {
    pub(crate) fn from_raw_dictionary(
        raw_dictionary: xml::Dictionary,
        _flatten: bool,
        strict_check: bool,
    ) -> Result<Dictionary, Error> {
        let version = raw_dictionary.version()?;
        let mut resolver = Resolver::new(raw_dictionary.fields, raw_dictionary.components)?;

        let header = Component {
            name: fix_str!("Header").to_owned(),
            doc: None,
            members: resolver.create_members(raw_dictionary.header.members, None)?,
        };
        let trailer = Component {
            name: fix_str!("Trailer").to_owned(),
            doc: None,
            members: resolver.create_members(raw_dictionary.trailer.members, None)?,
        };
        if strict_check {
            check_required_fields(&header, &trailer, version)?;
        }

        let mut messages = Vec::with_capacity(raw_dictionary.messages.len());
        let mut messages_by_name = HashMap::with_capacity(raw_dictionary.messages.len());
        let mut messages_by_id = HashMap::with_capacity(raw_dictionary.messages.len());
        for raw_msg in raw_dictionary.messages {
            let msg = Rc::new(resolver.create_message(raw_msg)?);
            if let Some(msg) = messages_by_name.insert(msg.name.clone(), msg.clone()) {
                return Err(Error::Validation(ValidationError::DuplicatedMessageName(
                    msg.name.to_string(),
                )));
            }
            if let Some(msg) = messages_by_id.insert(msg.msg_type, msg.clone()) {
                return Err(Error::Validation(ValidationError::DuplicatedMessageType(
                    msg.msg_type,
                )));
            }
            messages.push(msg);
        }

        if strict_check {
            resolver.check_unused_elements()?;
        } else {
            resolver.register_unused_elements()?;
        }

        let Elements {
            fields: fields_by_name,
            components,
            groups,
        } = resolver.into_elements();

        let fields_by_id = fields_by_name
            .values()
            .map(|field| (field.number(), field.clone()))
            .collect();

        Ok(Dictionary {
            version,
            fields_by_name,
            fields_by_id,
            groups,
            components,
            messages,
            messages_by_name,
            messages_by_id,
            header,
            trailer,
            subdictionaries: HashMap::new(),
        })
    }

    /// Creates a new Dictionary by parsing a single XML specification file
    ///
    /// This is a convenience method for simple cases. For more complex scenarios,
    /// use the `DictionaryBuilder` instead.
    pub fn new(path: &str) -> Result<Dictionary, Error> {
        let xml = fs::read_to_string(path)?;
        let raw_dictionary: xml::Dictionary = from_str(&xml)?;

        Dictionary::from_raw_dictionary(raw_dictionary, false, false)
    }

    fn flatten_component(
        component_name: &FixStr,
        output: &mut Vec<Member>,
        components_map: &HashMap<FixString, Rc<Component>>,
    ) -> Result<(), Error> {
        // Get the component
        let component = components_map.get(component_name).ok_or_else(|| {
            Error::Validation(ValidationError::UnknownComponent(
                component_name.to_string(),
            ))
        })?;

        // Inline each member of the component with its own required flag.
        // The component's usage-site required flag is not used - components
        // are just grouping containers that disappear after flattening.
        for member in &component.members {
            match member.definition() {
                MemberDefinition::Component(nested_comp) => {
                    Self::flatten_component(&nested_comp.name, output, components_map)?;
                }

                MemberDefinition::Field(field) => {
                    output.push(Member {
                        required: member.required(),
                        definition: MemberDefinition::Field(field.clone()),
                    });
                }

                MemberDefinition::RawData { length, data } => {
                    output.push(Member {
                        required: member.required(),
                        definition: MemberDefinition::RawData {
                            length: length.clone(),
                            data: data.clone(),
                        },
                    });
                }

                MemberDefinition::Group(group) => {
                    let flattened_group = Self::flatten_group(group, components_map)?;

                    output.push(Member {
                        required: member.required(),
                        definition: MemberDefinition::Group(flattened_group),
                    });
                }
            }
        }

        Ok(())
    }

    // Helper function to flatten a list of members
    fn flatten_members(
        members: &[Member],
        components_map: &HashMap<FixString, Rc<Component>>,
    ) -> Result<Vec<Member>, Error> {
        let mut flattened_members = Vec::new();

        for member in members {
            match member.definition() {
                MemberDefinition::Component(component) => {
                    Self::flatten_component(
                        &component.name,
                        &mut flattened_members,
                        components_map,
                    )?;
                }

                MemberDefinition::Field(field) => {
                    flattened_members.push(Member {
                        required: member.required(),
                        definition: MemberDefinition::Field(field.clone()),
                    });
                }

                MemberDefinition::RawData { length, data } => {
                    flattened_members.push(Member {
                        required: member.required(),
                        definition: MemberDefinition::RawData {
                            length: length.clone(),
                            data: data.clone(),
                        },
                    });
                }

                MemberDefinition::Group(group) => {
                    let flattened_group = Self::flatten_group(group, components_map)?;

                    // Add the flattened group to the output
                    flattened_members.push(Member {
                        required: member.required(),
                        definition: MemberDefinition::Group(flattened_group),
                    });
                }
            }
        }

        Ok(flattened_members)
    }

    // Helper function to flatten a group
    fn flatten_group(
        group: &Rc<Group>,
        components_map: &HashMap<FixString, Rc<Component>>,
    ) -> Result<Rc<Group>, Error> {
        let flattened_members = Self::flatten_members(group.members(), components_map)?;

        // Create a new group with the flattened members
        let flattened_group = Rc::new(Group {
            name: group.name.clone(),
            num_in_group: group.num_in_group.clone(),
            doc: group.doc.clone(),
            members: flattened_members,
        });

        Ok(flattened_group)
    }

    /// Returns a copy of this dictionary with every component inlined into
    /// the message, group, header or trailer that used it.
    ///
    /// The result has an empty [`components`](Self::components) map and no
    /// [`MemberDefinition::Component`] anywhere, so a consumer walking members
    /// never has to resolve one. Everything else survives: message definition
    /// order, group names, and the subdictionaries, which are flattened too.
    ///
    /// Each inlined field keeps the `required` flag from **its own definition
    /// inside the component**, not the one on the component's usage site - a
    /// field marked `required='Y'` within a component stays required even
    /// where that component was included with `required='N'`.
    ///
    /// Returns [`ValidationError::UnknownComponent`] if a member references a
    /// component this dictionary does not define.
    pub fn flatten(&self) -> Result<Dictionary, Error> {
        // Create copies of messages with flattened components, preserving definition order
        let mut new_messages = Vec::with_capacity(self.messages.len());
        let mut new_messages_by_name = HashMap::with_capacity(self.messages_by_name.len());
        let mut new_messages_by_id = HashMap::with_capacity(self.messages_by_id.len());

        for msg in &self.messages {
            let flattened_members = Self::flatten_members(msg.members(), &self.components)?;
            let flattened_msg = Rc::new(Message {
                name: msg.name.clone(),
                msg_type: msg.msg_type,
                msg_cat: msg.msg_cat,
                doc: msg.doc.clone(),
                members: flattened_members,
            });

            new_messages.push(flattened_msg.clone());
            new_messages_by_name.insert(msg.name.clone(), flattened_msg.clone());
            new_messages_by_id.insert(msg.msg_type, flattened_msg);
        }

        // Flatten the header and trailer
        let flattened_header_members =
            Self::flatten_members(&self.header.members, &self.components)?;
        let flattened_trailer_members =
            Self::flatten_members(&self.trailer.members, &self.components)?;

        let mut new_groups = HashMap::with_capacity(self.groups.len());
        for (name, group) in &self.groups {
            new_groups.insert(name.clone(), Self::flatten_group(group, &self.components)?);
        }

        let header = Component {
            name: self.header.name.clone(),
            doc: self.header.doc.clone(),
            members: flattened_header_members,
        };
        let trailer = Component {
            name: self.trailer.name.clone(),
            doc: self.trailer.doc.clone(),
            members: flattened_trailer_members,
        };

        let mut subdictionaries = HashMap::with_capacity(self.subdictionaries.len());
        for (version, subdictionary) in &self.subdictionaries {
            subdictionaries.insert(*version, subdictionary.flatten()?);
        }

        Ok(Dictionary {
            version: self.version,
            fields_by_name: self.fields_by_name.clone(),
            fields_by_id: self.fields_by_id.clone(),
            groups: new_groups,
            components: HashMap::new(),
            messages: new_messages,
            messages_by_name: new_messages_by_name,
            messages_by_id: new_messages_by_id,
            header,
            trailer,
            subdictionaries,
        })
    }

    /// Returns the version of this dictionary
    pub fn version(&self) -> Version {
        self.version
    }

    /// Returns the BeginString representation of this dictionary's version.
    pub fn begin_string(&self) -> String {
        self.version.to_string()
    }

    /// Looks up a field by name
    pub fn field_by_name(&self, name: &FixStr) -> Option<&Field> {
        self.fields_by_name.get(name).map(|v| &**v)
    }

    /// Looks up a field by tag number
    pub fn field_by_id(&self, id: u16) -> Option<&Field> {
        self.fields_by_id.get(&id).map(|v| &**v)
    }

    /// Returns an iterator over all fields in this dictionary
    pub fn fields(&self) -> impl Iterator<Item = &Field> {
        self.fields_by_id.values().map(|v| &**v)
    }

    /// Looks up a component by name
    pub fn component(&self, name: &FixStr) -> Option<&Component> {
        self.components.get(name).map(|v| &**v)
    }

    /// Returns an iterator over all components in this dictionary
    pub fn components(&self) -> impl Iterator<Item = &Component> {
        self.components.values().map(|v| &**v)
    }

    /// Looks up a group by name
    pub fn group(&self, name: &FixStr) -> Option<&Group> {
        self.groups.get(name).map(|v| &**v)
    }

    /// Returns an iterator over all groups in this dictionary
    pub fn groups(&self) -> impl Iterator<Item = &Group> {
        self.groups.values().map(|v| &**v)
    }

    /// Looks up a message by name
    pub fn message_by_name(&self, name: &FixStr) -> Option<&Message> {
        self.messages_by_name.get(name).map(|v| &**v)
    }

    /// Looks up a message by message type
    pub fn message_by_type(&self, msg_type: &[u8]) -> Option<&Message> {
        self.messages_by_id.get(msg_type).map(|v| &**v)
    }

    /// Returns an iterator over all messages in this dictionary, in definition order
    pub fn messages(&self) -> impl Iterator<Item = &Message> {
        self.messages.iter().map(|v| &**v)
    }

    /// Returns a reference to the standard header component
    ///
    /// The header component contains fields that appear at the beginning of every message.
    pub fn header(&self) -> &Component {
        &self.header
    }

    /// Returns a reference to the standard trailer component
    ///
    /// The trailer component contains fields that appear at the end of every message.
    pub fn trailer(&self) -> &Component {
        &self.trailer
    }

    /// Returns a subdictionary for the specified version, if available
    ///
    /// For FIXT-based FIX versions, this allows access to application-level dictionaries.
    pub fn subdictionary(&self, version: Version) -> Option<&Dictionary> {
        self.subdictionaries.get(&version)
    }

    /// Returns an iterator over all subdictionaries
    ///
    /// For FIXT-based FIX versions, this provides access to application-level dictionaries.
    pub fn subdictionaries(&self) -> impl Iterator<Item = &Dictionary> {
        self.subdictionaries.values()
    }
}