OnixS C++ FIX Engine  4.13.0
API Documentation
Session.h
Go to the documentation of this file.
1 /*
2 * Copyright Onix Solutions Limited [OnixS]. All rights reserved.
3 *
4 * This software owned by Onix Solutions Limited [OnixS] and is protected by copyright law
5 * and international copyright treaties.
6 *
7 * Access to and use of the software is governed by the terms of the applicable OnixS Software
8 * Services Agreement (the Agreement) and Customer end user license agreements granting
9 * a non-assignable, non-transferable and non-exclusive license to use the software
10 * for it's own data processing purposes under the terms defined in the Agreement.
11 *
12 * Except as otherwise granted within the terms of the Agreement, copying or reproduction of any part
13 * of this source code or associated reference material to any other location for further reproduction
14 * or redistribution, and any amendments to this copyright notice, are expressly prohibited.
15 *
16 * Any reproduction or redistribution for sale or hiring of the Software not in accordance with
17 * the terms of the Agreement is a violation of copyright law.
18 */
19 
20 #pragma once
21 
22 #include <string>
23 #include <set>
24 #include <vector>
25 #include <utility>
26 #include <iosfwd>
27 #include <limits>
28 
32 
33 
35 
44 
46 
48 
51 
52 
53 namespace OnixS {
54 namespace FIX {
55 ONIXS_FIXENGINE_API_DECL(class, Message);
56 ONIXS_FIXENGINE_API_DECL(class, Dictionary);
57 ONIXS_FIXENGINE_API_DECL(class, Engine);
58 ONIXS_FIXENGINE_API_DECL(class, ISessionListener);
59 ONIXS_FIXENGINE_API_DECL(class, ISessionStorage);
60 
61 /// The session message mode.
62 struct MessageMode {
63  enum Enum {
64  /// The default mode. The `Message` class is used in inbound callbacks.
65  Message = 1,
66 
67  /// The `FlatMessage` class is used in inbound callbacks.
69  };
70 };
71 
72 namespace Core {
73 namespace Messaging {
74 class Message;
75 }
76 }
77 
78 template<typename MsgType>
80 {
82  typedef std::vector<FlatMessage*> MsgBatchType;
83  typedef std::vector<OnixS::FIX::Core::Messaging::Extras::FlatMessage*> CoreMsgBatchType;
84 };
85 
86 template<>
88 {
90  typedef std::vector<Message*> MsgBatchType;
91  typedef std::vector<OnixS::FIX::Core::Messaging::Message*> CoreMsgBatchType;
92 };
93 
94 /**
95 * The FIX Session - a bi-directional stream of ordered messages between two parties within a continuous sequence number series.
96 */
98 {
99 public:
100  /**
101  * Creates the FIX Session.
102  *
103  * @param senderCompId The assigned value used to identify the firm sending message (SenderCompID (tag=49) field value in outgoing messages).
104  * @param targetCompId The assigned value used to identify the receiving firm (TargetCompID (tag=56) field value in outgoing messages).
105  * @param dictionary The FIX dictionary to be used by the session.
106  * @param listener An instance of the ISessionListener interface, which will receive and handle miscellaneous Session events.
107  * @param storageType The session storage type.
108  * @param storage The pluggable session storage.
109  */
110  Session(
111  const std::string & senderCompId,
112  const std::string & targetCompId,
113  const Dictionary & dictionary,
114  ISessionListener * listener,
117 
118  /**
119  * Creates the FIX Session.
120  *
121  * @param reactor An instance of an externally managed reactor.
122  * @param senderCompId The assigned value used to identify the firm sending message (SenderCompID (tag=49) field value in outgoing messages).
123  * @param targetCompId The assigned value used to identify the receiving firm (TargetCompID (tag=56) field value in outgoing messages).
124  * @param dictionary The FIX dictionary to be used by the session.
125  * @param listener An instance of the ISessionListener interface, which will receive and handle miscellaneous Session events.
126  * @param storageType The session storage type.
127  * @param storage The pluggable session storage.
128  */
129  Session(
130  ISessionReactor * reactor,
131  const std::string & senderCompId,
132  const std::string & targetCompId,
133  const Dictionary & dictionary,
134  ISessionListener * listener,
137 
138  /**
139  * Creates the FIX Session.
140  *
141  * @param senderCompId The assigned value used to identify the firm sending message (SenderCompID (tag=49) field value in outgoing messages).
142  * @param targetCompId The assigned value used to identify the receiving firm (TargetCompID (tag=56) field value in outgoing messages).
143  * @param dictionary The FIX dictionary to be used by the session.
144  * @param keepSequenceNumbersAfterLogout The option to keep sequence numbers after the exchange of Logout (MsgType=5) messages.
145  * @param listener An instance of the ISessionListener interface which will receive and handle miscellaneous Session events.
146  * @param storageType The session storage type.
147  * @param storage The pluggable session storage.
148  */
149  Session(
150  const std::string & senderCompId,
151  const std::string & targetCompId,
152  const Dictionary & dictionary,
153  bool keepSequenceNumbersAfterLogout,
154  OnixS::FIX::ISessionListener * listener,
157 
158 
159  /**
160  * Creates the FIX Session.
161  *
162  * @param reactor An instance of an externally managed reactor.
163  * @param senderCompId The assigned value used to identify the firm sending message (SenderCompID (tag=49) field value in outgoing messages).
164  * @param targetCompId The assigned value used to identify the receiving firm (TargetCompID (tag=56) field value in outgoing messages).
165  * @param dictionary The FIX dictionary to be used by the session.
166  * @param keepSequenceNumbersAfterLogout The option to keep sequence numbers after the exchange of Logout (MsgType=5) messages.
167  * @param listener An instance of the ISessionListener interface which will receive and handle miscellaneous Session events.
168  * @param storageType The session storage type.
169  * @param storage The pluggable session storage.
170  */
171  Session(
172  ISessionReactor * reactor,
173  const std::string & senderCompId,
174  const std::string & targetCompId,
175  const Dictionary & dictionary,
176  bool keepSequenceNumbersAfterLogout,
177  OnixS::FIX::ISessionListener * listener,
180 
181  /**
182  * Creates the FIX Session.
183  *
184  * @param senderCompId The assigned value used to identify the firm sending message (SenderCompID (tag=49) field value in outgoing messages).
185  * @param targetCompId The assigned value used to identify the receiving firm (TargetCompID (tag=56) field value in outgoing messages).
186  * @param dictionary The FIX dictionary to be used by the session.
187  * @param keepSequenceNumbersAfterLogout The option to keep sequence numbers after the exchange of Logout (MsgType=5) messages.
188  * @param listener An instance of the ISessionListener interface which will receive and handle miscellaneous Session events.
189  * @param customSessionKey The custom key that can be used to distinguish sessions with the same values of the SenderCompID, TargetCompID and the FIX Protocol version.
190  * @param storageType The session storage type.
191  * @param storage The pluggable session storage.
192  */
193  Session(
194  const std::string & senderCompId,
195  const std::string & targetCompId,
196  const Dictionary & dictionary,
197  bool keepSequenceNumbersAfterLogout,
198  OnixS::FIX::ISessionListener * listener,
199  const std::string & customSessionKey,
202 
203  /**
204  * Creates the FIX Session.
205  *
206  * @param reactor An instance of an externally managed reactor.
207  * @param senderCompId The assigned value used to identify the firm sending message (SenderCompID (tag=49) field value in outgoing messages).
208  * @param targetCompId The assigned value used to identify the receiving firm (TargetCompID (tag=56) field value in outgoing messages).
209  * @param dictionary The FIX dictionary to be used by the session.
210  * @param keepSequenceNumbersAfterLogout The option to keep sequence numbers after the exchange of Logout (MsgType=5) messages.
211  * @param listener An instance of the ISessionListener interface which will receive and handle miscellaneous Session events.
212  * @param customSessionKey The custom key that can be used to distinguish sessions with the same values of the SenderCompID, TargetCompID and the FIX Protocol version.
213  * @param storageType The session storage type.
214  * @param storage The pluggable Session storage.
215  */
216  Session(
217  ISessionReactor * reactor,
218  const std::string & senderCompId,
219  const std::string & targetCompId,
220  const Dictionary & dictionary,
221  bool keepSequenceNumbersAfterLogout,
222  OnixS::FIX::ISessionListener * listener,
223  const std::string & customSessionKey,
226 
227  /**
228  * The destructor.
229  */
230  ~Session();
231 
232  /**
233  * Removes all messages from the outbound queue.
234  *
235  * @param removeFragmentedPacket The flag specifies whether to remove the last packet which is partially sent.
236  *
237  * @note This call is thread-safe.
238  */
239  Session & clearOutboundQueue(bool removeFragmentedPacket = false);
240 
241  /**
242  * Returns the Session's state.
243  *
244  * @note This call is thread-safe.
245  */
246  SessionState::Enum state() const;
247 
248  /**
249  * Returns the current encryption method.
250  *
251  * @note This call is thread-safe.
252  */
253  EncryptionMethod::Enum encryptionMethod() const;
254 
255  /**
256  * Sets the encryption method.
257  *
258  * @note This call is thread-safe.
259  */
260  Session & encryptionMethod(EncryptionMethod::Enum newEncryptionMethod);
261 
262  /**
263  * Returns the port to listen on for incoming FIX Connections in the Acceptor mode.
264  *
265  * @note This call is thread-safe.
266  */
267  int listenPort() const;
268 
269  /**
270  * Sets the port to listen on for incoming FIX Connections in the Acceptor mode.
271  *
272  * @note This call is thread-safe.
273  */
274  Session & listenPort(int listenPort);
275 
276  /**
277  * Returns the local network interface from which you intend to send and receive data.
278  *
279  * @note This call is thread-safe.
280  */
281  std::string localNetworkInterface() const;
282 
283  /**
284  * Sets the local network interface from which you intend to send and receive data.
285  *
286  * @note This call is thread-safe.
287  */
288  Session & localNetworkInterface(const std::string & localNetworkInterface);
289 
290  /**
291  * Returns the local port from which you intend to send and receive data.
292  *
293  * @note This call is thread-safe.
294  */
295  unsigned short localPort() const;
296  /**
297  * The local port range type.
298  */
299  typedef std::pair<unsigned short, unsigned short> LocalPortRange;
300 
301  /**
302  * Returns the local port range, the first available port from this range will be used to send and receive data.
303  *
304  * @note This call is thread-safe.
305  */
306  LocalPortRange localPortRange() const;
307 
308  /**
309  * Sets the local port range, the first available port from this range will be used to send and receive data.
310  *
311  * @note This call is thread-safe.
312  */
313  Session & localPortRange(LocalPortRange portRange);
314 
315  /**
316  * Returns the option to improve the latency at the expense of the message throughput (TCP_NODELAY socket option).
317  * When it is not set, the corresponding Engine setting's value is used ('true' by default).
318  */
319  bool tcpNoDelayOption() const;
320 
321  /**
322  * Sets the value of the option to improve the latency at the expense of the message throughput (TCP_NODELAY socket option).
323  */
324  Session & tcpNoDelayOption(bool improveLatency = true);
325 
326  /**
327  * Returns the option that controls whether to send the logout message before
328  * dropping the telecommunication link, in case of an exception.
329  * When it is not set, the corresponding Engine setting's value is used ('false' by default).
330  */
331  bool sendLogoutOnException() const;
332 
333  /**
334  * Sets the value of the option that controls whether to send the logout message before
335  * dropping the telecommunication link, in case of an exception.
336  */
337  Session & sendLogoutOnException(bool sendLogoutOnException);
338 
339  /**
340  * Returns the option to validate the presence of unknown FIX messages.
341  * When it is not set, the corresponding Engine setting's value is used ('false' by default).
342  */
343  bool validateUnknownMessages() const;
344 
345  /**
346  * Sets the option to validate the presence of unknown FIX messages.
347  */
348  Session & validateUnknownMessages(bool);
349 
350  /**
351  * Returns the option to validate the presence of unknown fields.
352  * When it is not set, the corresponding Engine setting's value is used ('false' by default).
353  */
354  bool validateUnknownFields() const;
355 
356  /**
357  * Sets the option to validate the presence of unknown fields.
358  */
359  Session & validateUnknownFields(bool);
360 
361  /**
362  * Returns the option to validate the presence of required fields in inbound and outbound messages.
363  * When it is not set, the corresponding Engine setting's value is used ('false' by default).
364  */
365  bool validateRequiredFields() const;
366 
367  /**
368  * Sets the option to validate the presence of required fields in inbound and outbound messages.
369  */
370  Session & validateRequiredFields(bool);
371 
372  /**
373  * Returns the option to validate the field values of FIX messages in accordance with the FIX protocol or its FIX Dictionary.
374  * When it is not set, the corresponding Engine setting's value is used ('false' by default).
375  */
376  bool validateFieldValues() const;
377 
378  /**
379  * Sets the option to validate the field values of FIX messages in accordance with the FIX protocol or its FIX Dictionary.
380  */
381  Session & validateFieldValues(bool);
382 
383  /**
384  * Returns the option to validate the empty field values of FIX messages in accordance with the FIX protocol or its FIX Dictionary.
385  * When it is not set, the corresponding Engine setting's value is used ('false' by default).
386  */
387  bool validateEmptyFieldValues() const;
388 
389  /**
390  * Sets the option to validate the empty field values of FIX messages in accordance with the FIX protocol or its FIX Dictionary.
391  */
392  Session & validateEmptyFieldValues(bool);
393 
394  /**
395  * Returns the option that controls the repeating group entry count validation.
396  * When it is not set, the corresponding Engine setting's value is used ('true' by default).
397  */
398  bool validateRepeatingGroupEntryCount() const;
399 
400  /**
401  * Sets the value of the option that controls the repeating group entry count validation.
402  */
403  Session & validateRepeatingGroupEntryCount(bool);
404 
405  /**
406  * Returns the option that controls the repeating group leading tag validation.
407  * When it is not set, the corresponding Engine setting's value is used ('false' by default).
408  */
409  bool validateRepeatingGroupLeadingTag() const;
410 
411  /**
412  * Sets the value of the option that controls the repeating group leading tag validation.
413  */
414  Session & validateRepeatingGroupLeadingTag(bool);
415 
416  /**
417  * Returns the option that controls the duplicated field validation.
418  * When it is not set, the corresponding Engine setting's value is used ('false' by default).
419  */
420  bool validateDuplicatedField() const;
421 
422  /**
423  * Sets value of the option that controls the duplicated field validation.
424  */
425  Session & validateDuplicatedField(bool);
426 
427  /**
428  * Returns the option that controls the validation of the checksum of the incoming message.
429  * When it is not set, the corresponding Engine setting's value is used ('false' by default).
430  */
431  bool validateChecksum() const;
432 
433  /**
434  * Sets the validation of the checksum of the incoming message.
435  */
436  Session & validateChecksum(bool);
437 
438  /**
439  * Returns the number of messages that should be written to the outgoing TCP buffer together.
440  * When it is not set, the corresponding Engine setting's value is used (0 by default).
441  */
442  unsigned messageGrouping() const;
443 
444  /**
445  * Sets the number of messages that should be written to the outgoing TCP buffer together.
446  */
447  Session & messageGrouping(unsigned numberOfMessagesToGroup);
448 
449  /**
450  * Returns the connection mode.
451  */
452  ThreadingModel::Enum threadingModel() const;
453 
454  /**
455  * Sets the connection mode.
456  */
457  Session & threadingModel(ThreadingModel::Enum value);
458 
459  /**
460  * Returns whether the Session uses the spin lock.
461  */
462  bool useSpinLock() const;
463 
464  /**
465  * Sets the Session to use the spin lock.
466  */
467  Session & useSpinLock(bool value);
468 
469  /**
470  * Returns the reasonable transmission time as % from the heartbeatIntervalSec value.
471  * When it is not set, the corresponding Engine setting's value is used (20% by default).
472  */
473  int reasonableTransmissionTime() const;
474 
475  /**
476  * Sets the reasonable transmission time as % from the heartbeatIntervalSec value.
477  *
478  * When either end of the connection has not received any data for (heartbeatIntervalSec() * (100 + reasonableTransmissionTime())/100) seconds,
479  * it will transmit a Test Request message.
480  *
481  * If there is still no a Heartbeat message received after (heartbeatIntervalSec * (100 + reasonableTransmissionTime())/100) seconds
482  * then the connection should be considered lost and a corrective action be initiated.
483  */
484  Session & reasonableTransmissionTime(int value);
485 
486  /**
487  * Sets the number of attempts to restore the FIX connection.
488  */
489  Session & reconnectAttempts(int value);
490 
491  /**
492  * Returns the number of attempts to restore the FIX connection.
493  * When it is not set, the corresponding Engine setting's value is used (3 by default).
494  */
495  int reconnectAttempts() const;
496 
497  /**
498  * Sets the time interval between the attempts to restore the FIX connection (in seconds).
499  */
500  Session & reconnectInterval(int value);
501 
502  /**
503  * Returns the time interval between the attempts to restore the FIX connection (in seconds).
504  * When it is not set, the corresponding Engine setting's value is used (180 by default).
505  */
506  int reconnectInterval() const;
507 
508  /**
509  * Sets the non-blocking receive spinning timeout (in microseconds) before the receiving thread enters into the blocking wait mode.
510  *
511  * @note Should not be greater than 1 sec (minimal heartbeatIntervalSec()).
512  */
513  Session & receiveSpinningTimeoutUsec(int usec);
514 
515  /**
516  * Returns the current receive spinning timeout value (in microseconds).
517  * By default, the value is zero and the receive spinning is not used.
518  */
519  int receiveSpinningTimeout() const;
520 
521  /**
522  * Sets the send spinning timeout (in microseconds) of the Session::send(..) method to wait for the socket sending buffer availability
523  * in the spin loop mode before placing the message to the outgoing queue (to be sent later by the sending thread).
524  *
525  * @note Should not be greater than 1 sec (minimal heartbeatIntervalSec()).
526  */
527  Session & sendSpinningTimeoutUsec(int usec);
528 
529  /**
530  * Returns the current send spinning timeout value (in microseconds).
531  * By default, the value is zero and send spinning is not used.
532  */
533  int sendSpinningTimeout() const;
534 
535  /**
536  * Sets the NextExpectedMsgSeqNum field (tag 789) support in Logon messages.
537  */
538  Session & supportNextExpectedMsgSeqNum(bool support);
539 
540  /**
541  * Returns 'true' if the NextExpectedMsgSeqNum field (tag 789) is supported in Logon messages, otherwise - 'false'.
542  * By default, the option value is false.
543  */
544  bool supportNextExpectedMsgSeqNum() const;
545 
546  /**
547  * Returns the SSL certificate file.
548  *
549  * @note This call is thread-safe.
550  */
551  std::string sslCertificateFile() const;
552 
553  /**
554  * Sets the SSL certificate file.
555  *
556  * @note Only the (Privacy Enhanced Mail) Base 64 Encoded (.pem) SSL certificates are supported.
557  *
558  * @note This call is thread-safe.
559  */
560  Session & sslCertificateFile(const std::string & file);
561 
562  /**
563  * Returns the SSL private key file.
564  *
565  * @note This call is thread-safe.
566  */
567  std::string sslPrivateKeyFile() const;
568 
569  /**
570  * Sets the SSL private key file.
571  *
572  * @note Only the (Privacy Enhanced Mail) Base 64 Encoded (.pem) SSL certificates are supported.
573  *
574  * @note This call is thread-safe.
575  */
576  Session & sslPrivateKeyFile(const std::string & file);
577 
578  /**
579  * Returns the SSL private key file password.
580  *
581  * @note This call is thread-safe.
582  */
583  Cryptography::SecureString sslPrivateKeyPassword() const;
584 
585  /**
586  * Sets the SSL private key file password.
587  *
588  * @note This call is thread-safe.
589  */
590  Session & sslPrivateKeyPassword(const Cryptography::SecureString & password);
591 
592  /**
593  * Set the option to request peer certificates and perform the certificate verification.
594  *
595  * @note This call is thread-safe.
596  */
597  Session & sslVerifyPeer(bool verify);
598 
599  /**
600  * Returns the option to request peer certificates and perform the certificate verification.
601  * When it is not set, the corresponding Engine setting's value is used ('false' by default).
602  *
603  * @note This call is thread-safe.
604  */
605  bool sslVerifyPeer() const;
606 
607  /**
608  * Sets the client-side SNI-extension field.
609  * When is not empty, then this field provides SNI-name.
610  * When field value is "*" (wildcard), then SNI-name will be taken from the connection URL.
611  *
612  * @note Connection URL cannot be an IP address when the value "*" is used.
613  */
614  Session & sslClientSni(const std::string & hostName);
615 
616  /**
617  * Returns the client-side SNI-extension field.
618  */
619  const std::string & sslClientSni() const;
620 
621  /**
622  * Sets the path to the trusted certification authority certificate file in (Privacy Enhanced Mail) Base64 encoded (.pem) format.
623  *
624  * @note This call is thread-safe.
625  */
626  Session & sslCaFile(const std::string & value);
627 
628  /**
629  * Returns the path to the trusted certification authority certificate file in the (Privacy Enhanced Mail) Base64 encoded (.pem) format.
630  *
631  * @note This call is thread-safe.
632  */
633  std::string sslCaFile() const;
634 
635  /**
636  * Sets the minimal SSL/TLS protocol version that will be declared during the SSL/TLS handshake.
637  *
638  * @note This call is thread-safe.
639  */
640  Session & sslMinProtocolVersion(SslProtocolMinMaxVersion::Enum version);
641 
642  /**
643  * Returns the minimal SSL/TLS protocol version that will be declared during the SSL/TLS handshake.
644  *
645  * @note This call is thread-safe.
646  */
647  SslProtocolMinMaxVersion::Enum sslMinProtocolVersion() const;
648 
649  /**
650  * Sets the maximal SSL/TLS protocol version that will be declared during the SSL/TLS handshake.
651  *
652  * @note This call is thread-safe.
653  */
654  Session & sslMaxProtocolVersion(SslProtocolMinMaxVersion::Enum version);
655 
656  /**
657  * Returns the maximal SSL/TLS protocol version that will be declared during the SSL/TLS handshake.
658  *
659  * @note This call is thread-safe.
660  */
661  SslProtocolMinMaxVersion::Enum sslMaxProtocolVersion() const;
662 
663  /**
664  * Establishes the FIX Connection as an Acceptor.
665  *
666  * The Acceptor is the receiving party of the FIX session. It listens for the incoming connection on the pre-defined port.
667  * The acceptor has the responsibility to perform the first level authentication and formally declares
668  * the connection request "accepted" through the transmission of an acknowledgment Logon message.
669  *
670  * @note This call is thread-safe.
671  */
672  Session & logonAsAcceptor();
673 
674  /**
675  * Establishes the FIX Connection as an Initiator using the ResetSeqNumFlag (tag 141) field.
676  *
677  * The Initiator establishes the telecommunications link and initiates the session via the transmission
678  * of the initial Logon message.
679  * The method is blocked until the acknowledgment Logon message is received or the timeout expired.
680  * The timeout value is equal to the triple heartbeat interval.
681  *
682  * @note This call is thread-safe.
683  */
684  Session & logonAsInitiator(const std::string & host, int port, bool setResetSeqNumFlag);
685 
686  /**
687  * Establishes the FIX Connection as an Initiator.
688  *
689  * The Initiator establishes the telecommunications link and initiates the session via the transmission
690  * of the initial Logon message.
691  * The method is blocked until the acknowledgment Logon message is received or the timeout expired.
692  * The timeout value is equal to the triple heartbeat interval.
693  *
694  * @note This call is thread-safe.
695  */
696  Session & logonAsInitiator(const std::string & host, int port);
697 
698  /**
699  * Establishes the FIX Connection as an Initiator using the given Heartbeat interval (seconds).
700  * The method is blocked until the acknowledgment Logon message is received or the timeout expired.
701  * The timeout value is equal to the triple heartbeat interval.
702  *
703  * @note This call is thread-safe.
704  */
705  Session & logonAsInitiator(const std::string & host, int port, int heartbeatIntervalSec);
706 
707  /**
708  * Establishes the FIX Connection as an Initiator using the given Heartbeat interval (seconds) and the ResetSeqNumFlag(141) field.
709  * The method is blocked until the acknowledgment Logon message is received or the timeout expired.
710  * The timeout value is equal to the triple heartbeat interval.
711  *
712  * @note This call is thread-safe.
713  */
714  Session & logonAsInitiator(const std::string & host, int port, int heartbeatIntervalSec, bool setResetSeqNumFlag);
715 
716  /**
717  * Establishes the FIX Connection as an Initiator using the custom Logon message.
718  * The method is blocked until the acknowledgment Logon message is received or the timeout expired.
719  * The timeout value is equal to the triple heartbeat interval.
720  *
721  * @note This call is thread-safe.
722  */
723  Session & logonAsInitiator(const std::string & host, int port, int heartbeatIntervalSec, Message * customLogonMsg);
724 
725  /**
726  * Establishes the FIX Connection as an Initiator using the custom Logon message and the ResetSeqNumFlag(141) field.
727  * The method is blocked until the acknowledgment Logon message is received or the timeout expired.
728  * The timeout value is equal to the triple heartbeat interval.
729  *
730  * @note This call is thread-safe.
731  */
732  Session & logonAsInitiator(const std::string & host, int port, int heartbeatIntervalSec, Message * customLogonMsg, bool setResetSeqNumFlag);
733 
734  /**
735  * Establishes the FIX Connection asynchronously as an Initiator using the custom Logon message and the ResetSeqNumFlag(141) field.
736  * The method returns immediately without waiting the acknowledgment Logon message.
737  * Returns the `SharedFuture` object that can be used to wait for the result of the asynchronous logon method.
738  *
739  * @note This call is thread-safe.
740  */
741  Threading::SharedFuture<void> logonAsInitiatorAsync(const std::string & host, int port, int heartbeatIntervalSec, Message * customLogonMsg, bool setResetSeqNumFlag);
742 
743  /**
744  * Terminates the FIX Connection.
745  *
746  * The initial Logout message is sent to the counterparty and the method is blocked until the acknowledgment
747  * Logout message is received or the timeout expired.
748  * The timeout value is equal to the triple heartbeat interval or,
749  * in case there are no incoming messages, heartbeat interval plus reasonable transmission time.
750  *
751  * @note This call is thread-safe.
752  */
753  Session & logout();
754 
755  /**
756  * Terminates the FIX Connection.
757  *
758  * The initial Logout message is sent to the counterparty and the method is blocked until the acknowledgment
759  * Logout message is received or the timeout expired.
760  * The timeout value is equal to the triple heartbeat interval or,
761  * in case there are no incoming messages, heartbeat interval plus reasonable transmission time.
762  *
763  * @param text Free format text string that is sent to the counterparty in the Text(58) field of the initial
764  * Logout message.
765  *
766  * @note This call is thread-safe.
767  */
768  Session & logout(const std::string & text);
769 
770  /**
771  * Terminates the FIX Connection.
772  *
773  * The initial Logout message is sent to the counterparty and the method returns immediately
774  * without waiting for the acknowledgment Logout message.
775  * Returns the `SharedFuture` object that can be used to wait for the result of the asynchronous logout method.
776  *
777  * @param text The free format text string that is sent to the counterparty in the Text(58) field of the initial
778  * Logout message.
779  *
780  * @note This call is thread-safe.
781  */
782  Threading::SharedFuture<void> logoutAsync(const std::string & text);
783 
784  /**
785  * Terminates the FIX Connection.
786  *
787  * The initial Logout message is sent to the counterparty and the method is blocked until the acknowledgment
788  * Logout message is received or the timeout expired.
789  * The timeout value is equal to the triple heartbeat interval or,
790  * in case there are no incoming messages, the heartbeat interval plus reasonable transmission time.
791  *
792  * @param customLogoutMessage The custom Logout message that is sent to the counterparty.
793  *
794  * @note This call is thread-safe.
795  */
796  Session & logout(Message * customLogoutMessage);
797  Session & logout(FlatMessage * customLogoutMessage);
798 
799  /**
800  * Terminates the FIX Connection.
801  *
802  * The initial Logout message is sent to the counterparty and the method returns immediately
803  * without waiting the acknowledgment Logout message.
804  * Returns the `SharedFuture` object that can be used to wait for the result of the asynchronous logout method.
805  *
806  * @param customLogoutMessage The custom Logout message that is sent to the counterparty.
807  *
808  * @note This call is thread-safe.
809  */
810  Threading::SharedFuture<void> logoutAsync(Message * customLogoutMessage);
811  Threading::SharedFuture<void> logoutAsync(FlatMessage * customLogoutMessage);
812 
813  /**
814  * Terminates the FIX connection in the non-graceful way (without the exchange of Logout (MsgType=5) messages).
815  *
816  * @note This call is thread-safe.
817  */
818  Session & breakConnection();
819 
820  /**
821  * Sends the message to the counterparty.
822  *
823  * As soon as a session is created, it is possible to start sending messages via the session.
824  * If the session is not established, the messages are stored in the session storage and will be sent in replay to the resend request
825  * when the connection is established with the counterparty and the sequence numbers mismatch is detected.
826  *
827  * @note This call is asynchronous.
828  *
829  * @note This call is thread-safe.
830  */
831  Session & send(Message * msg);
832  Session & send(FlatMessage * msg);
833 
834  /**
835  * Performs sending via a specific API (e.g. zero-copy send) of the message to the counterparty.
836  *
837  * As soon as a session is created, it is possible to start sending messages via the session.
838  * If the session is not established, the messages are stored in the session storage and will be sent in replay to the resend request
839  * when the connection is established with the counterparty and the sequence numbers mismatch is detected.
840  *
841  * @note This call is asynchronous.
842  *
843  * @note This call is thread-safe.
844  */
845  Session & send(FlatMessage * msg, SessionSendMode::Enum mode);
846 
847  /**
848  * Message batch types.
849  */
850  template<typename MsgType> class MsgBatch;
851 
853  {
856 
857  static void init(MBT::CoreMsgBatchType & coreBatch);
858  static void init(SBT::CoreMsgBatchType & coreBatch);
859  static void add(MBT::MsgBatchType & batch, MBT::CoreMsgBatchType & coreBatch, MBT::MessagePtr & msg);
860  static void add(SBT::MsgBatchType & batch, SBT::CoreMsgBatchType & coreBatch, SBT::MessagePtr & msg);
861  static void clear(MBT::MsgBatchType & batch);
862  static void clear(SBT::MsgBatchType & batch);
863 
864  template<typename MsgType> friend class MsgBatch;
865  };
866 
867  template<typename MsgType>
868  class MsgBatch
869  {
870  typedef MsgBatchTraits<MsgType> Traits;
871 
872  friend class Session;
873 
874  typename Traits::MsgBatchType batch_;
875  typename Traits::CoreMsgBatchType coreBatch_;
876 
877  MsgBatch(const MsgBatch&);
878  MsgBatch & operator=(const MsgBatch&);
879 
880  public:
881 
882  typedef typename Traits::MessagePtr MessagePtr;
883  typedef typename Traits::MsgBatchType::iterator iterator;
884  typedef typename Traits::MsgBatchType::const_iterator const_iterator;
885 
886  MsgBatch() { MsgBatchHelper::init(coreBatch_); }
888 
889  void add(MessagePtr & msg) { MsgBatchHelper::add(batch_, coreBatch_, msg); }
890 
891  MsgType & operator[](size_t index) { return *batch_[index]; }
892  const MsgType & operator[](size_t index) const { return *batch_[index]; }
893 
894  size_t size() const { return batch_.size(); }
895 
896  const_iterator begin() const { return batch_.begin(); }
897  iterator begin() { return batch_.begin(); }
898 
899  const_iterator end() const { return batch_.end(); }
900  iterator end() { return batch_.end(); }
901  };
902 
905  typedef FlatMessageBatch SerializedMessageBatch;
906 
907  /**
908  * Sends messages in a batch to the counterparty.
909  *
910  * As soon as a session is created, it is possible to start sending messages via the session.
911  * If the session is not established, the messages are stored in the session storage and will be sent in replay to the resend request
912  * when the connection is established with the counterparty and the sequence numbers mismatch is detected.
913  *
914  *@param msgs The message batch to send.
915  *@param maxPacketSize The maximum number of bytes written to the socket's send buffer together.
916  * This parameter could be used to reduce the probability that the operating system will fragment a FIX message across multiple TCP packets.
917  *
918  * @note The message batch should not be empty and the maxPacketSize parameter should not be less than any message size in the batch.
919  * Otherwise, the method call can produce an error and the session can close the connection.
920  *
921  * @note This call is asynchronous.
922  *
923  * @note This call is thread-safe.
924  */
925  Session & send(MessageBatch & msgs, size_t maxPacketSize = (std::numeric_limits<size_t>::max)());
926  Session & send(FlatMessageBatch & msgs, size_t maxPacketSize = (std::numeric_limits<size_t>::max)());
927 
928  /**
929  * Performs sending via a specific API (e.g. zero-copy send) of messages to the counterparty.
930  *
931  * As soon as a session is created, it is possible to start sending messages via the session.
932  * If the session is not established, the messages are stored in the session storage and will be sent in replay to the resend request
933  * when the connection is established with the counterparty and the sequence numbers mismatch is detected.
934  *
935  * @note This call is asynchronous.
936  *
937  * @note This call is thread-safe.
938  */
939  Session & send(FlatMessageBatch & msgs, SessionSendMode::Enum mode, size_t maxPacketSize = (std::numeric_limits<size_t>::max)());
940 
941  /**
942  * Sends a serialized message(s) to the counterparty without any fields updating.
943  * One can use the preFill method to prepare a message(s) for sending.
944  *
945  * As soon as a session is created, it is possible to start sending messages via the session.
946  * If the session is not established, the messages are stored in the session storage and will be sent in replay to the resend request
947  * when the connection is established with the counterparty and the sequence numbers mismatch is detected.
948  *
949  * @note It checks the validity of the sequence number of the provided message.
950  * If the sequence number is incorrect, the sequence number, message length, and checksum will be updated during sending.
951  *
952  * @note This call is asynchronous.
953  *
954  * @note This call is thread-safe.
955  */
956  Session & sendAsIs(FlatMessage * msg);
957 
958  /**
959  * Sends a serialized message(s) to the counterparty without any fields updating.
960  * One can use the preFill method to prepare a message(s) for sending.
961  *
962  * As soon as a session is created, it is possible to start sending messages via the session.
963  * If the session is not established, the messages are stored in the session storage and will be sent in replay to the resend request
964  * when the connection is established with the counterparty and the sequence numbers mismatch is detected.
965  *
966  *@param msgs The message batch to send.
967  *@param maxPacketSize The maximum number of bytes written to the socket's send buffer together.
968  * This parameter could be used to reduce the probability that the operating system will fragment a FIX message across multiple TCP packets.
969  *
970  * @note The message batch should not be empty and the maxPacketSize parameter should not be less than any message size in the batch.
971  * Otherwise, the method call can produce an error and the session can close the connection.
972  *
973  * @note It checks the validity of the sequence number of the provided messages.
974  * If the sequence number is incorrect, the sequence number, message length, and checksum will be updated during sending.
975  *
976  * @note This call is asynchronous.
977  *
978  * @note This call is thread-safe.
979  */
980  Session & sendAsIs(FlatMessageBatch & msgs, size_t maxPacketSize = (std::numeric_limits<size_t>::max)());
981 
982  /**
983  * Performs the throttling of a session that must be called before each send function call.
984  * If the count of messages per time unit exceeds the throttling limit, the function will be blocked until the given time interval is passed.
985  *
986  * @note This call is thread-safe.
987  */
988  Session & throttle();
989 
990  /**
991  * Checks the throttling of a session that must be called before each send function call.
992  * If the count of messages per time unit exceeds the throttling limit, the function returns the delay (in milliseconds) until the sending becomes possible. Otherwise, it returns 0.
993  *
994  *@param resetWhenDelay The flag to indicate if the amount of messages per throttling interval should be reset when a delay is returned.
995  *
996  * @note This call is thread-safe.
997  */
998  size_t tryThrottle(bool resetWhenDelay = false);
999 
1000  /**
1001  * Sets throttling limit parameters.
1002  *
1003  *@param messagesCount The message limit per time unit.
1004  *@param intervalInMs The time interval to limit messages.
1005  *
1006  * @note This call is thread-safe.
1007  */
1008  Session & throttlingLimit(size_t messagesCount, size_t intervalInMs = 1000);
1009 
1010  /**
1011  * This method warms up the sending path.
1012  *
1013  *@param msg The message to warm up the assembly part of the sending path.
1014  *@param warmupFlags Specific flags which can be used to turn on the warmup feature for a specific NIC.
1015 
1016  * @note This call is thread-safe.
1017  */
1018  Session & warmUp(FlatMessage* msg, int warmupFlags = 0);
1019 
1020  /**
1021  * Returns 'true' if the given flags work as expected and a real data is not sent to the wire, otherwise - 'false'.
1022  *
1023  *@param warmupFlags Warmup flags for checking.
1024  *@param baseListenPort The base listen port to use during the checking.
1025  *@param localNetworkInterface The IP address to bind for listen and outgoing test sockets.
1026  *
1027  * @note This call is thread-safe.
1028  */
1029  static bool checkWarmupFlags(int warmupFlags, unsigned short baseListenPort = 5000, const std::string & localNetworkInterface = "127.0.0.1");
1030 
1031  /**
1032  * Pre-fills session-level fields that are constant during the session's lifetime - SenderCompId, TargetCompId, SenderLocationId, TargetLocationID, SenderSubID, TargetSubID.
1033  *
1034  * @note This call is thread-safe.
1035  */
1036  void preFill(Message & msg) const;
1037 
1038  /**
1039  * Pre-fills the following fields in the message or messages batch for sending as is:
1040  * - Session-level fields that are constant during the session's lifetime - SenderCompId, TargetCompId, SenderLocationId, TargetLocationI, SenderSubID, TargetSubID.
1041  * - The MsgSeqNum field in accordance with the session outgoing sequence number.
1042  * - The SendingTime field.
1043  * - BodyLength and CheckSum fields.
1044  *
1045  * @note This call is thread-safe.
1046  */
1047  void preFill(FlatMessage & msg) const;
1048  void preFill(FlatMessageBatch & msgs) const;
1049 
1050  /**
1051  * Shutdowns the session.
1052  *
1053  * @note This call is thread-safe.
1054  */
1055  Session & shutdown();
1056 
1057  /**
1058  * Returns the text description of this session.
1059  *
1060  * @note This call is thread-safe.
1061  */
1062  operator const std::string & () const;
1063 
1064  /**
1065  * Returns the underlying storage Id.
1066  *
1067  * @note This call is thread-safe.
1068  */
1069  const std::string & storageId() const;
1070 
1071  /**
1072  * Flushes all internal buffers of the underlying storage.
1073  *
1074  *@param syncData When it is true, the method will synchronize a file's state with the storage device.
1075  * On Linux it will call 'fsync()', on Windows '_commit()' functions.
1076  *
1077  * @note This call is thread-safe.
1078  */
1079  Session & flushSessionStorage(bool syncData = false);
1080 
1081  /**
1082  * Returns the counterparty host name.
1083  *
1084  * @note The method performs a DNS request for the first time.
1085  * Therefore, it can block the thread execution for a long time until the DNS request is completed.
1086  *
1087  * @note This call is thread-safe.
1088  */
1089  std::string counterpartyHost() const;
1090 
1091  /**
1092  * Returns the counterparty address.
1093  *
1094  * @note This call is thread-safe.
1095  */
1096  std::string counterpartyIpAddress() const;
1097 
1098  /**
1099  * Returns the counterparty port number.
1100  *
1101  * @note This call is thread-safe.
1102  */
1103  size_t counterpartyPort() const;
1104 
1105  /**
1106  * Returns the Session's Custom Key.
1107  *
1108  * @note This call is thread-safe.
1109  */
1110  const std::string & customKey() const;
1111 
1112  /**
1113  * Returns the total number of bytes in the outbound queue.
1114  *
1115  * @note This call is thread-safe.
1116  */
1117  size_t outboundQueueBytes() const;
1118 
1119  /**
1120  * Returns the Heartbeat interval (in seconds).
1121  */
1122  int heartbeatIntervalSec() const;
1123 
1124  /**
1125  * Returns 'true' if inbound messages are logged, otherwise - 'false'.
1126  * By default, the value is 'true'.
1127  */
1128  bool logInboundMessages() const;
1129 
1130  /**
1131  * The option to log inbound messages.
1132  */
1133  Session & logInboundMessages(bool value);
1134 
1135  /**
1136  * Returns 'true' if outbound messages are logged, otherwise - 'false'.
1137  * By default, the value is 'true'.
1138  */
1139  bool logOutboundMessages() const;
1140 
1141  /**
1142  * The option to log outbound messages.
1143  */
1144  Session & logOutboundMessages(bool value);
1145 
1146  /**
1147  * Incoming message types to be filtered out from the logs.
1148  */
1149  typedef std::set<std::string> InboundMessageLogFilter;
1150 
1151  /**
1152  * Returns incoming message types to be filtered out from the logs.
1153  *
1154  * @note This call is thread-safe.
1155  */
1156  InboundMessageLogFilter inboundMessageLogFilter() const;
1157 
1158  /**
1159  * Sets incoming message types to be filtered out from the logs.
1160  *
1161  * @note This call is thread-safe.
1162  */
1163  Session & inboundMessageLogFilter(const InboundMessageLogFilter & filter);
1164 
1165  /**
1166  * Outgoing message types to be filtered out from the logs.
1167  */
1168  typedef std::set<std::string> OutboundMessageLogFilter;
1169 
1170  /**
1171  * Returns outgoing message types to be filtered out from the logs.
1172  *
1173  * @note This call is thread-safe.
1174  */
1175  OutboundMessageLogFilter outboundMessageLogFilter() const;
1176 
1177  /**
1178  * Sets outgoing message types to be filtered out from the logs.
1179  *
1180  * @note This call is thread-safe.
1181  */
1182  Session & outboundMessageLogFilter(const OutboundMessageLogFilter & filter);
1183 
1184  /**
1185  * Returns 'true' if outbound messages are logged before sending, otherwise - 'false'.
1186  * By default, the value is 'true'.
1187  *
1188  * @note This call is thread-safe.
1189  */
1190  bool logBeforeSending() const;
1191 
1192  /**
1193  * The option to switch on/off the logging of outbound messages before/after sending.
1194  *
1195  * @note This call is thread-safe.
1196  */
1197  Session & logBeforeSending(bool value);
1198 
1199  /**
1200  * Returns the expected sequence number of the next incoming message.
1201  *
1202  * @note This call is thread-safe.
1203  */
1204  SequenceNumber inSeqNum() const;
1205 
1206  /**
1207  * Sets the expected sequence number of the next incoming message.
1208  *
1209  * @note This call is thread-safe.
1210  */
1211  Session & inSeqNum(SequenceNumber seqNum);
1212 
1213  /**
1214  * Returns the sequence number of the next outgoing message.
1215  *
1216  * @note This call is thread-safe.
1217  */
1218  SequenceNumber outSeqNum() const;
1219 
1220  /**
1221  * Sets the sequence number of the next outgoing message.
1222  *
1223  * @note This call is thread-safe.
1224  */
1225  Session & outSeqNum(SequenceNumber seqNum);
1226 
1227  /**
1228  * Represents an unlimited number of messages to be requested in one Resend Request (MsgType=2) message.
1229  * The default value is 0.
1230  */
1231  static const unsigned int ResendRequestMaximumRangeNoLimit;
1232 
1233  /**
1234  * Sets the maximum number of messages to be requested in one Resend Request (MsgType=2) message.
1235  *
1236  * @see Session::ResendRequestMaximumRangeNoLimit.
1237  *
1238  * @param range The maximum number of messages to be requested in one Resend Request (MsgType=2) message. Cannot be negative.
1239  *
1240  * @note This call is thread-safe.
1241  */
1242  Session & resendRequestMaximumRange(int range);
1243 
1244  /**
1245  * Returns the maximum number of messages to be requested in one Resend Request (MsgType=2) message.
1246  * By default, the value is zero (no limit).
1247  *
1248  * @see Session::ResendRequestMaximumRangeNoLimit.
1249  *
1250  * @note This call is thread-safe.
1251  */
1252  int resendRequestMaximumRange() const;
1253 
1254  /**
1255  * Sets the number of sent messages that are available for resending on the counterparty's Resend Request <2> message.
1256  *
1257  * @note This call is thread-safe.
1258  */
1259  Session & resendingQueueSize(size_t value);
1260 
1261  /**
1262  * Returns the number of sent messages that are available for resending on the counterparty's Resend Request <2> message.
1263  * By default, the value is -1 that means that the corresponding Engine setting's value is used ('1000' by default).
1264  *
1265  * @note This call is thread-safe.
1266  */
1267  size_t resendingQueueSize() const;
1268 
1269  /**
1270  * Sets the maximum number of messages sent in reply to the Resend Request <2> before temporarily releasing the Session’s lock.
1271  *
1272  * @note This call is thread-safe.
1273  */
1274  Session & resendingBatchSize(size_t value);
1275 
1276  /**
1277  * Returns the maximum number of messages sent in reply to the Resend Request <2> before temporarily releasing the Session’s lock.
1278  *
1279  * @note This call is thread-safe.
1280  */
1281  size_t resendingBatchSize() const;
1282 
1283  /**
1284  * Returns the session role.
1285  *
1286  * @note This call is thread-safe.
1287  */
1288  SessionRole::Enum role() const;
1289 
1290  /**
1291  * Returns the assigned value used to identify the firm sending message (the SenderCompID (tag 49) field value in outgoing messages).
1292  *
1293  * @note This call is thread-safe.
1294  */
1295  const std::string & senderCompId() const;
1296 
1297  /**
1298  * Returns 'true' if the LastMsgSeqNumProcessed (tag 369) field is specified on every message sent, otherwise - 'false'.
1299  * By default, the option value is false.
1300  */
1301  bool specifyLastMsgSeqNumProcessed() const;
1302 
1303  /**
1304  * The option to specify the LastMsgSeqNumProcessed (tag 369) field on every message sent.
1305  * Useful for detecting a backlog with a counterparty.
1306  *
1307  * @note The option does not affect the FlatMessage send.
1308  */
1309  Session & specifyLastMsgSeqNumProcessed(bool specify);
1310 
1311  /**
1312  * Returns 'true' if updating of the SendingTime is turn on for every message, otherwise - 'false'.
1313  * By default, the option value is true.
1314  */
1315  bool updateSendingTimeField() const;
1316 
1317  /**
1318  * The option to specify updating of the SendingTime of every sent message.
1319  */
1320  Session & updateSendingTimeField(bool specify);
1321 
1322  /**
1323  * Sets the time format of the SendingTime of every sent message.
1324  * By default, the YYYYMMDDHHMMSSMsec format is used.
1325  */
1326  Session & sendingTimeFormat(TimestampFormat::Enum format);
1327 
1328  /**
1329  * Returns the assigned value used to identify the receiving firm (the TargetCompID (tag 56) field value in outgoing messages).
1330  *
1331  * @note This call is thread-safe.
1332  */
1333  const std::string & targetCompId() const;
1334 
1335  /**
1336  * The instance of the FIX dictionary or standard FIX messages dictionary which is used by the session.
1337  */
1338  Dictionary dictionary() const;
1339 
1340  /**
1341  * Returns the CPU affinity of the receiving thread.
1342  */
1343  const OnixS::Threading::CpuIndexes & receivingThreadAffinity() const;
1344 
1345  /**
1346  * Sets the CPU affinity of the receiving thread.
1347  */
1348  Session & receivingThreadAffinity(const OnixS::Threading::CpuIndexes & cpuIndexes);
1349 
1350  /**
1351  * Sets the CPU affinity of the receiving thread to a CPU.
1352  */
1353  Session & receivingThreadAffinity(const OnixS::Threading::CpuIndex cpuIndex);
1354 
1355  /**
1356  * Returns the CPU affinity of the sending thread.
1357  */
1358  const OnixS::Threading::CpuIndexes & sendingThreadAffinity() const;
1359 
1360  /**
1361  * Sets the CPU affinity index of the sending thread.
1362  */
1363  Session & sendingThreadAffinity(const OnixS::Threading::CpuIndexes & cpuIndexes);
1364 
1365  /**
1366  * Sets the CPU affinity index of the sending thread a CPU.
1367  */
1368  Session & sendingThreadAffinity(const OnixS::Threading::CpuIndex cpuIndex);
1369 
1370  /**
1371  * Represents an undefined value of priority and policy.
1372  */
1373  static const int UndefinedPriorityAndPolicy;
1374 
1375  /**
1376  * Returns the priority of the receiving thread.
1377  */
1378  int receivingThreadPriority() const;
1379 
1380  /**
1381  * Sets the priority of the receiving thread.
1382  */
1383  Session & receivingThreadPriority(int priority);
1384 
1385  /**
1386  * Returns the priority of the sending thread.
1387  */
1388  int sendingThreadPriority() const;
1389 
1390  /**
1391  * Sets the priority of the sending thread.
1392  */
1393  Session & sendingThreadPriority(int priority);
1394 
1395  /**
1396  * Returns the scheduling policy of the receiving thread.
1397  */
1398  int receivingThreadPolicy() const;
1399 
1400  /**
1401  * Sets the scheduling policy of the receiving thread.
1402  */
1403  Session & receivingThreadPolicy(int policy);
1404 
1405  /**
1406  * Returns the scheduling policy of the sending thread.
1407  */
1408  int sendingThreadPolicy() const;
1409 
1410  /**
1411  * Sets the scheduling policy of the sending thread.
1412  */
1413  Session & sendingThreadPolicy(int policy);
1414 
1415  /**
1416  * Returns the sent message if it can be found by the given message sequence number, otherwise - NULL.
1417  *
1418  * @note The returned message is owned by the application and should be released after usage.
1419  *
1420  * @note This call is thread-safe.
1421  */
1422  Message * findSentMessage(SequenceNumber messageSequenceNumber);
1423  FlatMessage * findSentFlatMessage(SequenceNumber messageSequenceNumber);
1424 
1425  /**
1426  * Returns an array of sent messages if it can be found by the given message sequence number range, otherwise - empty array.
1427  *
1428  * @note The returned messages are owned by the application and should be released after usage.
1429  *
1430  * @note This call is thread-safe.
1431  */
1432  MsgBatchTraits<Message>::MsgBatchType findSentMessages(SequenceNumber beginSequenceNumber, SequenceNumber endSequenceNumber);
1433  MsgBatchTraits<FlatMessage>::MsgBatchType findSentFlatMessages(SequenceNumber beginSequenceNumber, SequenceNumber endSequenceNumber);
1434 
1435  /**
1436  * When the message gap is detected the "Resend Request" FIX Message is sent and the Session state is changed to "AwaitReplyOnResendRequest".
1437  * By default, in this state the incoming new messages (without the PossDupFlag (tag #43) flag) are ignored because we expect them to be re-sent later again with the PossDupFlag flag.
1438  *
1439  * This property allows to change this behavior and report the new messages anyway.
1440  *
1441  * @note In this mode, messages could be reported out of the original order: e.g. MsgSeqNum could be: 3 (original), 4 (original), 2 (PossDupFlag='Y'), 3 (PossDupFlag='Y'), 4 (PossDupFlag='Y')
1442  * and some messages could be received two times: first time without PossDupFlag='Y' and second time - with this flag.
1443  */
1444  Session & reportNewMessagesWhileWaitingForMissedMessages(bool report);
1445 
1446  /**
1447  * Returns 'true' if the new messages are reported even when the message gap is detected and the reply on the "Resend Request" message is expected, otherwise - 'false'.
1448  */
1449  bool reportNewMessagesWhileWaitingForMissedMessages() const;
1450 
1451  /**
1452  * By default, the "Resend Request" message is sent only once - when the first gap is detected.
1453  * This property allows to change this behavior and send the "Resend Request" message on each detected message sequence number gap.
1454  */
1455  Session & sendResendRequestOnEachMessageGap(bool send);
1456 
1457  /**
1458  * Returns 'true' if the "Resend Request" message is sent on each detected message sequence number gap, otherwise - 'false'.
1459  */
1460  bool sendResendRequestOnEachMessageGap() const;
1461 
1462  /**
1463  * By default, the "Resend Request" message requests all messages begin from the first missed one.
1464  * This property allows to change this behavior and request only missed messages.
1465  *
1466  * @note This method can be called only when the session is disconnected.
1467  */
1468  Session & requestOnlyMissedMessages(bool request);
1469 
1470  /**
1471  * Returns 'true' if the "Resend Request" message requests only missed messages, otherwise - 'false'.
1472  */
1473  bool requestOnlyMissedMessages() const;
1474 
1475  /**
1476  * By default, if the "Session Level Reject" message is received in replay to the "Resend Request" then this is considered as a serious problem and the FIX connection will be closed.
1477  * This property allows to change this behavior and consider the "Session Level Reject" on the "Resend Request" as the "Sequence Reset Gap Fill" message.
1478  */
1479  Session & considerRejectOnResendRequestAsGapFill(bool consider);
1480 
1481  /**
1482  * Returns 'true' if the "Reject" on the "Resend Request" is considered as the "Sequence Reset Gap Fill" message, otherwise - 'false'.
1483  */
1484  bool considerRejectOnResendRequestAsGapFill() const;
1485 
1486  /**
1487  * By default, if the incoming message has a sequence number less than expected and the PossDupFlag is not set, it indicates
1488  * a serious error and leads to FIX connection closing.
1489  * This property allows to change this behavior and consider the sequence number of the incoming message, which less than expected, as an expected one.
1490  */
1491  Session & ignoreLessThanExpectedSequenceNumber(bool ignore);
1492 
1493  /**
1494  * Returns 'true' if the sequence number of the incoming message, which less than expected, is considered as an expected one, otherwise - 'false'.
1495  */
1496  bool ignoreLessThanExpectedSequenceNumber() const;
1497 
1498  /**
1499  * The option to automatically reset the local sequence numbers to 1 during every logon.
1500  */
1501  Session & resetLocalSequenceNumbersOnLogon(bool reset);
1502 
1503  /**
1504  * Returns 'true' if local sequence numbers are reset automatically to 1 during every logon, otherwise - 'false'.
1505  */
1506  bool resetLocalSequenceNumbersOnLogon() const;
1507 
1508  /**
1509  * If the requestOnlyMissedMessages option is true and the sequence number of an incoming FIX message
1510  * greater that expected then the resend functionality is run and this incoming message is stored
1511  * in the incoming message gap queue for further processing.
1512  * This property allows to set maximum size of that queue.
1513  */
1514  Session & incomingMessageGapQueueMaximumSize(size_t maxSize);
1515 
1516  /**
1517  * Returns the maximum size of the incoming message gap queue.
1518  * By default, the value equal to 1000.
1519  */
1520  size_t incomingMessageGapQueueMaximumSize() const;
1521 
1522  /**
1523  * Registers the Session listener.
1524  *
1525  * @throw An exception if the listener is already registered.
1526  */
1527  Session & registerListener(ISessionListener * listener);
1528 
1529  /**
1530  * Unregisters the Session listener.
1531  */
1532  Session & unregisterListener(ISessionListener * listener);
1533 
1534  /**
1535  * Unregisters all Session listener.
1536  */
1537  Session & unregisterAllListeners();
1538 
1539  /**
1540  * Backups the current log files and resets the local sequence numbers to 1.
1541  *
1542  * @note This method can be called only when the session is disconnected.
1543  *
1544  * @note This call is thread-safe.
1545  */
1546  Session & resetLocalSequenceNumbers();
1547 
1548  /**
1549  * Sends a Logon message with the ResetSeqNumFlag set.
1550  *
1551  * @note This call is thread-safe.
1552  */
1553  Session & resetSeqNumViaLogonExchange();
1554 
1555  /**
1556  * Returns the SenderSubID (tag 50) field values for all outgoing messages.
1557  *
1558  * @note This call is thread-safe.
1559  */
1560  std::string senderSubId() const;
1561 
1562  /**
1563  * Sets the SenderSubID (tag 50) field values for all outgoing messages.
1564  *
1565  * @note This call is thread-safe.
1566  */
1567  Session & senderSubId(const std::string & value);
1568 
1569  /**
1570  * Returns the TargetSubID (tag 57) field values for all outgoing messages.
1571  *
1572  * @note This call is thread-safe.
1573  */
1574  std::string targetSubId() const;
1575 
1576  /**
1577  * Sets the TargetSubID (tag 57) field values for all outgoing messages.
1578  *
1579  * @note This call is thread-safe.
1580  */
1581  Session & targetSubId(const std::string & value);
1582 
1583  /**
1584  * Returns the SenderLocationID (tag 142) field values for all outgoing messages.
1585  *
1586  * @note This call is thread-safe.
1587  */
1588  std::string senderLocationId() const;
1589 
1590  /**
1591  * Sets the SenderLocationID (tag 142) field values for all outgoing messages.
1592  *
1593  * @note This call is thread-safe.
1594  */
1595  Session & senderLocationId(const std::string & value);
1596 
1597  /**
1598  * Returns the TargetLocationID (tag 143) field values for all outgoing messages.
1599  *
1600  * @note This call is thread-safe.
1601  */
1602  std::string targetLocationId() const;
1603 
1604  /**
1605  * Sets the TargetLocationID (tag 143) field values for all outgoing messages.
1606  *
1607  * @note This call is thread-safe.
1608  */
1609  Session & targetLocationId(const std::string & value);
1610 
1611  /**
1612  * Options to turn on/off incoming message sequence numbers validation.
1613  */
1614  Session & validateSequenceNumbers(bool value);
1615 
1616  /**
1617  * Returns the current status of the incoming message sequence numbers validation.
1618  * By default, the option value is true.
1619  */
1620  bool validateSequenceNumbers() const;
1621 
1622  /**
1623  * Returns the thread name suffix for receiving (R:threadNameSuffix) and sending (S:threadNameSuffix) threads.
1624  *
1625  * @note This call is thread-safe.
1626  */
1627  std::string threadNameSuffix() const;
1628 
1629  /**
1630  * Sets the thread name suffix for receiving ("R:threadNameSuffix") and sending ("S:threadNameSuffix") threads.
1631  **
1632  * If the threadNameSuffix is not specified, it is set by default to ("R:senderCompId-targetCompId")("S:senderCompId-targetCompId").
1633  **
1634  * @note This method can be called only when the session is disconnected.
1635  * @throw An exception if the session state is not Disconnected.
1636  *
1637  * @note This call is thread-safe.
1638  */
1639  Session & threadNameSuffix(const std::string & value);
1640 
1641  /**
1642  * Sends the Test Request (MsgType 1) message.
1643  * If the timeout is specified, the method blocks until the heartbeat message is received from the counterparty or timeout ended.
1644  *
1645  * @param testReqId The identifier included in the Test Request (MsgType 1) message to be returned in the resulting Heartbeat (MsgType 0) message from the counterparty.
1646  * @param timeout The maximum interval to wait until the reply is received from the counterparty.
1647  *
1648  * @note This call is thread-safe.
1649  */
1650  Session & sendTestRequest(const std::string & testReqId = "", const TimeSpan & timeout = TimeSpan::zero());
1651 
1652  /**
1653  * Sends the Resend Request (MsgType 2) message.
1654  *
1655  * @note Normally, the "Resend Request" message is sent automatically. This method allows to simulate a sequence gap by sending this message manually.
1656  * This can be needed in some venue specific cases. This method should not be used in the normal work.
1657  *
1658  * @param beginSeqNumber The begin sequence number of the first requested message in the range.
1659  *
1660  * @note This call is thread-safe.
1661  */
1662  Session & sendResendRequest(SequenceNumber beginSeqNumber);
1663 
1664  /**
1665  * Sends the Reject (MsgType 3) message.
1666  *
1667  * @param refSeqNumber The MsgSeqNum of rejected message.
1668  * @param text The message to explain the reason for the rejection.
1669  *
1670  * @note This call is thread-safe.
1671  */
1672  Session & sendReject(SequenceNumber refSeqNumber, const std::string & text);
1673 
1674  /**
1675  * Returns the time when logical session was created or the last sequence number reset operation was performed.
1676  * The originating value is extracted from the attached storage using the ISessionStorage::sessionCreationTime() method.
1677  *
1678  * @note This call is thread-safe.
1679  */
1680  Timestamp creationTime() const;
1681 
1682  /**
1683  * Returns the session string presentation.
1684  *
1685  * @note This call is thread-safe.
1686  */
1687  std::string toString() const;
1688 
1689  /**
1690  * Represents an invalid value of the socket handle.
1691  */
1693 
1694  /**
1695  * Returns the socket handle which the session uses to transmit the FIX data.
1696  *
1697  * @note This call is thread-safe.
1698  */
1699  OnixS::Sockets::Handle socketHandle();
1700 
1701  /**
1702  * Additional options, which should be set to the session socket when it is created.
1703  * For initiator sessions, options are set before the socket connect(..) call.
1704  * For acceptor sessions, options are set after the socket accept(..) call.
1705  */
1706  Session & socketOptions(const OnixS::Sockets::SocketOptions & options);
1707 
1708  /**
1709  * Inbound and outbound messages, the session's state data are stored in this directory.
1710  *
1711  * @note This method can be called only when the session is disconnected.
1712  * @throw An exception if the session state is not Disconnected.
1713  *
1714  * @note This call is thread-safe.
1715  */
1716  Session & logDirectory(const std::string & value);
1717 
1718  /**
1719  * Inbound and outbound messages, the session's state data are stored in this directory.
1720  *
1721  * @note This call is thread-safe.
1722  */
1723  const std::string & logDirectory() const;
1724 
1725  /**
1726  * Sets the timeout during which counterparty should send a reply to the "Resend Request" message.
1727  * If a counterparty does not reply or reply incorrectly during this timeout, then the ISessionListener::onWarning is called.
1728  * By default, the resend request timeout equal to zero, which means an infinite timeout.
1729  *
1730  * @note The resend timeout is checked when an incoming message is received or when the receive timeout is elapsed.
1731  * Therefore, the actual timeout can be greater than the specified one or can be rounded to the value equal to the heartbeat interval + reasonable transmission time.
1732  *
1733  * @note This call is thread-safe.
1734  */
1735  Session & resendTimeout(const TimeSpan & timeout);
1736 
1737  /**
1738  * Returns the timeout during which the counterparty should send a reply to the "Resend Request" message.
1739  *
1740  * @note This call is thread-safe.
1741  */
1742  TimeSpan resendTimeout() const;
1743 
1744  /**
1745  * The collection of scrambled tags.
1746  */
1747  typedef std::vector<Tag> ScrambledFields;
1748 
1749  /**
1750  * Sets scrambled fields in the Logon(A) message, in the session storage, for security reasons.
1751  *
1752  * @note This call is thread-safe.
1753  */
1754  Session & scrambleLogonFields(const ScrambledFields & fields);
1755 
1756  /**
1757  * Returns scrambled fields in the Logon(A) message.
1758  */
1759  ScrambledFields scrambleLogonFields() const;
1760 
1761  /**
1762  * Sets the send queue maximum size in bytes.
1763  * The TCP connection will be disconnected when an overflow issue happens and the sending queue size exceeds this size.
1764  *
1765  * @note This call is thread-safe.
1766  */
1767  Session & sendQueueMaxSize(size_t size);
1768 
1769  /**
1770  * Returns the send queue maximum size in bytes.
1771  * When it is not set, the corresponding Engine setting's value is used (0.5 GB by default).
1772  */
1773  size_t sendQueueMaxSize() const;
1774 
1775  /**
1776  * Sets the socket TCP connect timeout.
1777  *
1778  * @note This call is thread-safe.
1779  */
1780  Session & connectTimeout(const TimeSpan & timeout);
1781 
1782  /**
1783  * Returns the socket TCP connect timeout (30 sec by default).
1784  *
1785  * @note This call is thread-safe.
1786  */
1787  TimeSpan connectTimeout() const;
1788 
1789  /**
1790  * Returns the size of the TCP buffer allocated to the FIX connection for receiving data.
1791  * If '-1' then the default operating system value is used.
1792  *
1793  * @note This call is thread-safe.
1794  */
1795  int receiveBufferSize() const;
1796 
1797  /**
1798  * Sets the size of the TCP buffer allocated to the FIX connection for the receiving data.
1799  * If '-1' then the default operating system value is used.
1800  *
1801  * @note This call is thread-safe.
1802  */
1803  Session & receiveBufferSize(int value);
1804 
1805  /**
1806  * Returns the size of the TCP buffer allocated to the FIX connection for the sending data.
1807  * If '-1' then the default operating system value is used.
1808  *
1809  * @note This call is thread-safe.
1810  */
1811  int sendBufferSize() const;
1812 
1813  /**
1814  * Sets the size of the TCP buffer allocated to the FIX connection for the sending data.
1815  * If '-1' then the default operating system value is used.
1816  *
1817  * @note This call is thread-safe.
1818  */
1819  Session & sendBufferSize(int value);
1820 
1821  /**
1822  * Returns the value of the option to enable received data timestamp.
1823  * The default value is `false`.
1824  *
1825  * @note This call is thread-safe.
1826  */
1827  bool enableRxTimestamp() const;
1828 
1829  /**
1830  * Sets the value of the option to enable received data timestamp.
1831  *
1832  * @note Available on Linux only.
1833  * @note This call is thread-safe.
1834  */
1835  Session & enableRxTimestamp(bool value);
1836 
1837  /**
1838  * Schedule the memory usage optimization.
1839  * The session will perform the actual memory usage optimization in two phases:
1840  * - After receiving and processing the next incoming session-level message (receiving part).
1841  * - Before sending the next outgoing session-level message (sending part).
1842  */
1843  void scheduleShrinkToFit();
1844 
1845  /**
1846  * HTTP proxy settings.
1847  */
1849  {
1851  :host(), port(), username(), password()
1852  {}
1853 
1854  ProxySettings(const std::string & proxyHost, int proxyPort, const std::string & proxyUsername = std::string(), const std::string & proxyPassword = std::string())
1855  :host(proxyHost), port(proxyPort), username(proxyUsername), password(proxyPassword)
1856  {}
1857 
1858  std::string host;
1859  int port;
1860  std::string username;
1861  std::string password;
1862  };
1863 
1864  /**
1865  * Sets HTTP proxy settings.
1866  */
1867  Session & proxySettings(const ProxySettings & settings);
1868 
1869  /**
1870  * Returns HTTP proxy settings.
1871  */
1872  ProxySettings proxySettings() const;
1873 
1874  /**
1875  * Returns the session message mode.
1876  */
1877  MessageMode::Enum messageMode() const;
1878 
1879  /**
1880  * Sets the session message mode.
1881  */
1882  void messageMode(MessageMode::Enum mode);
1883 
1884  struct Impl; ///< Implementation details.
1885 
1886 private:
1887  void init(
1888  const std::string & senderCompId,
1889  const std::string & targetCompId,
1890  const Dictionary & dictionary,
1891  ISessionListener * listener,
1892  bool keepSequenceNumbersAfterLogout,
1893  SessionStorageType::Enum storageType,
1894  ISessionStorage * storage,
1895  const std::string & customSessionKey,
1896  ISessionReactor * reactor);
1897 
1898  Impl * impl_;
1899 
1900  friend class Engine::Impl;
1901 };
1902 
1903 /// Stream output.
1905 std::ostream & operator << (std::ostream & os, const Session & session);
1906 }
1907 }
The FIX Session - a bi-directional stream of ordered messages between two parties within a continuous...
Definition: Session.h:97
The file based storage. The session&#39;s state and messages are persisted to the file system...
ONIXS_FIXENGINE_API std::ostream & operator<<(std::ostream &os, const Group &group)
Stream output.
Traits::MsgBatchType::iterator iterator
Definition: Session.h:883
MsgType & operator[](size_t index)
Definition: Session.h:891
std::set< std::string > InboundMessageLogFilter
Incoming message types to be filtered out from the logs.
Definition: Session.h:1149
static const OnixS::Sockets::Handle InvalidSocketHandle
Represents an invalid value of the socket handle.
Definition: Session.h:1692
const_iterator begin() const
Definition: Session.h:896
size_t CpuIndex
Logical processors that a thread is allowed to run on (first logical CPU has index 0)...
Definition: Thread.h:31
static TimeSpan zero()
The zero value of the time span.
int Handle
Type alias for socket handle.
Definition: Definitions.h:50
std::set< std::string > OutboundMessageLogFilter
Outgoing message types to be filtered out from the logs.
Definition: Session.h:1168
size_t size() const
Definition: Session.h:894
#define ONIXS_FIXENGINE_NULLPTR
Definition: Compiler.h:200
The session&#39;s Listener.
FlatMessageBatch SerializedMessageBatch
Definition: Session.h:905
std::vector< Tag > ScrambledFields
The collection of scrambled tags.
Definition: Session.h:1747
std::vector< OnixS::FIX::Core::Messaging::Message * > CoreMsgBatchType
Definition: Session.h:91
const MsgType & operator[](size_t index) const
Definition: Session.h:892
#define ONIXS_FIXENGINE_API
Definition: ABI.h:45
HTTP proxy settings.
Definition: Session.h:1848
const_iterator end() const
Definition: Session.h:899
PtrTraits< Message >::UniquePtr MessagePtr
Definition: Session.h:89
Provides an access to FIX fields from a flat (tag=value) message.
Definition: FlatMessage.h:109
virtual size_t resendingQueueSize() const =0
Returns the number of sent messages that are available for resending on counterparty&#39;s Resend Request...
Message batch types.
Definition: Session.h:850
ProxySettings(const std::string &proxyHost, int proxyPort, const std::string &proxyUsername=std::string(), const std::string &proxyPassword=std::string())
Definition: Session.h:1854
std::set< CpuIndex > CpuIndexes
Definition: Thread.h:32
MsgBatch< FlatMessage > FlatMessageBatch
Definition: Session.h:904
Identifies the FIX messages dictionary.
Definition: Dictionary.h:73
std::vector< Message * > MsgBatchType
Definition: Session.h:90
static const int UndefinedPriorityAndPolicy
Represents an undefined value of priority and policy.
Definition: Session.h:1373
Traits::MsgBatchType::const_iterator const_iterator
Definition: Session.h:884
The session message mode.
Definition: Session.h:62
ONIXS_FIXENGINE_API_DECL(class, IEngineListener)
virtual void clear()=0
Clears the storage.
The immutable secure string.
Definition: SecureString.h:29
std::pair< unsigned short, unsigned short > LocalPortRange
The local port range type.
Definition: Session.h:299
PtrTraits< MsgType >::UniquePtr MessagePtr
Definition: Session.h:81
The time span related functionality.
Definition: TimeSpan.h:93
std::vector< FlatMessage * > MsgBatchType
Definition: Session.h:82
MsgBatch< Message > MessageBatch
Definition: Session.h:903
The session&#39;s pluggable storage.
The session&#39;s network stack reactor interface.
unsigned int SequenceNumber
Alias for the sequence number.
std::vector< OnixS::FIX::Core::Messaging::Extras::FlatMessage * > CoreMsgBatchType
Definition: Session.h:83
Represents a future result of an asynchronous operation - a result that will eventually appear in the...
Definition: Future.h:253
Encapsulates operations over a FIX Message.
Definition: Message.h:49
virtual SequenceNumber outSeqNum()=0
Returns the last outgoing sequence number.
std::vector< SocketOption > SocketOptions
Storage type of socket options.
Definition: Definitions.h:67
std::auto_ptr< T > UniquePtr
Definition: Definitions.h:32
Traits::MessagePtr MessagePtr
Definition: Session.h:882
void add(MessagePtr &msg)
Definition: Session.h:889
The timestamps related functionality.
Definition: Timestamp.h:91
static const unsigned int ResendRequestMaximumRangeNoLimit
Represents an unlimited number of messages to be requested in one Resend Request (MsgType=2) message...
Definition: Session.h:1231
virtual SequenceNumber inSeqNum()=0
Returns the last inbound sequence number.