-
Notifications
You must be signed in to change notification settings - Fork 564
/
Session.cs
executable file
·1611 lines (1398 loc) · 58.1 KB
/
Session.cs
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#nullable enable
using System;
using System.Collections.Generic;
using System.Threading;
using QuickFix.Fields;
using QuickFix.Fields.Converters;
using QuickFix.Logger;
using QuickFix.Store;
namespace QuickFix
{
/// <summary>
/// The Session is the primary FIX abstraction for message communication.
/// It performs sequencing and error recovery and represents a communication
/// channel to a counterparty. Sessions are independent of specific communication
/// layer connections. A Session is defined as starting with message sequence number
/// of 1 and ending when the session is reset. The Session could span many sequential
/// connections (it cannot operate on multiple connections simultaneously).
/// </summary>
public class Session : IDisposable
{
#region Private Members
private static readonly Dictionary<SessionID, Session> Sessions = new();
private static readonly HashSet<string> AdminMsgTypes = new() { "0", "A", "1", "2", "3", "4", "5" };
private readonly object _sync = new();
private IResponder? _responder;
private readonly SessionSchedule _schedule;
private readonly SessionState _state;
private readonly IMessageFactory _msgFactory;
private readonly bool _appDoesEarlyIntercept;
#endregion
#region Properties
// state
public IMessageStore MessageStore => _state.MessageStore;
public ILog Log => _state.Log;
public bool IsInitiator => _state.IsInitiator;
public bool IsAcceptor => !_state.IsInitiator;
public bool IsEnabled => _state.IsEnabled;
public bool IsSessionTime => _schedule.IsSessionTime(DateTime.UtcNow);
public bool IsLoggedOn => ReceivedLogon && SentLogon;
public bool SentLogon => _state.SentLogon;
public bool ReceivedLogon => _state.ReceivedLogon;
public bool IsNewSession
{
get
{
DateTime? creationTime = _state.CreationTime;
return creationTime.HasValue == false
|| _schedule.IsNewSession(creationTime.Value, DateTime.UtcNow);
}
}
/// <summary>
/// Session setting for heartbeat interval (in seconds)
/// </summary>
public int HeartBtInt => _state.HeartBtInt;
/// <summary>
/// Session setting for enabling message latency checks
/// </summary>
public bool CheckLatency { get; set; }
/// <summary>
/// Session setting for maximum message latency (in seconds)
/// </summary>
public int MaxLatency { get; set; }
/// <summary>
/// Send a logout if counterparty times out and does not heartbeat
/// in response to a TestRequeset. Defaults to false
/// </summary>
public bool SendLogoutBeforeTimeoutDisconnect { get; set; }
/// <summary>
/// Gets or sets the next expected outgoing sequence number
/// </summary>
public SeqNumType NextSenderMsgSeqNum
{
get => _state.NextSenderMsgSeqNum;
set => _state.NextSenderMsgSeqNum = value;
}
/// <summary>
/// Gets or sets the next expected incoming sequence number
/// </summary>
public SeqNumType NextTargetMsgSeqNum
{
get => _state.NextTargetMsgSeqNum;
set => _state.NextTargetMsgSeqNum = value;
}
/// <summary>
/// Logon timeout in seconds
/// </summary>
public int LogonTimeout
{
get => _state.LogonTimeout;
set => _state.LogonTimeout = value;
}
/// <summary>
/// Logout timeout in seconds
/// </summary>
public int LogoutTimeout
{
get => _state.LogoutTimeout;
set => _state.LogoutTimeout = value;
}
// unsynchronized properties
/// <summary>
/// Whether to persist messages or not. Setting to false forces quickfix
/// to always send GapFills instead of resending messages.
/// </summary>
public bool PersistMessages { get; set; }
/// <summary>
/// Determines if session state should be restored from persistance
/// layer when logging on. Useful for creating hot failover sessions.
/// </summary>
public bool RefreshOnLogon { get; set; }
/// <summary>
/// Reset sequence numbers on logon request
/// </summary>
public bool ResetOnLogon { get; set; }
/// <summary>
/// Reset sequence numbers to 1 after a normal logout
/// </summary>
public bool ResetOnLogout { get; set; }
/// <summary>
/// Reset sequence numbers to 1 after abnormal termination
/// </summary>
public bool ResetOnDisconnect { get; set; }
/// <summary>
/// Whether to send redundant resend requests
/// </summary>
public bool SendRedundantResendRequests { get; set; }
/// <summary>
/// Whether to resend session level rejects (msg type '3') when servicing a resend request
/// </summary>
public bool ResendSessionLevelRejects { get; set; }
/// <summary>
/// Whether to validate length and checksum of messages
/// </summary>
public bool ValidateLengthAndChecksum { get; set; }
/// <summary>
/// Whether to validates Comp IDs for each message
/// </summary>
public bool CheckCompID { get; set; }
/// <summary>
/// Determines if milliseconds should be added to timestamps.
/// Only avilable on FIX4.2. or greater
/// </summary>
public bool MillisecondsInTimeStamp
{
get => TimeStampPrecision == TimeStampPrecision.Millisecond;
set => TimeStampPrecision = value ? TimeStampPrecision.Millisecond : TimeStampPrecision.Second;
}
/// <summary>
/// Gets or sets the time stamp precision.
/// </summary>
/// <value>
/// The time stamp precision.
/// </value>
public TimeStampPrecision TimeStampPrecision
{
get;
set;
}
/// <summary>
/// Adds the last message sequence number processed in the header (tag 369)
/// </summary>
public bool EnableLastMsgSeqNumProcessed { get; set; }
/// <summary>
/// Ignores resend requests marked poss dup
/// </summary>
public bool IgnorePossDupResendRequests { get; set; }
/// <summary>
/// Sets a maximum number of messages to request in a resend request.
/// </summary>
public SeqNumType MaxMessagesInResendRequest { get; set; }
/// <summary>
/// This is the FIX field value, e.g. "6" for FIX44
/// </summary>
public ApplVerID? TargetDefaultApplVerId { get; set; }
/// <summary>
/// This is the FIX field value, e.g. "6" for FIX44
/// </summary>
public string SenderDefaultApplVerID { get; set; }
public SessionID SessionID { get; set; }
public IApplication Application { get; }
public DataDictionaryProvider DataDictionaryProvider { get; }
public DataDictionary.DataDictionary SessionDataDictionary { get; }
public DataDictionary.DataDictionary ApplicationDataDictionary { get; }
/// <summary>
/// Returns whether the Session has a Responder. This method is synchronized
/// </summary>
public bool HasResponder { get { Thread.MemoryBarrier(); return _responder is not null; } }
/// <summary>
/// Returns whether the Sessions will allow ResetSequence messages sent as
/// part of a resend request (PossDup=Y) to omit the OrigSendingTime
/// </summary>
public bool RequiresOrigSendingTime { get; set; }
#endregion
public Session(
bool isInitiator,
IApplication app,
IMessageStoreFactory storeFactory,
SessionID sessId,
DataDictionaryProvider dataDictProvider,
SessionSchedule sessionSchedule,
int heartBtInt,
ILogFactory logFactory,
IMessageFactory msgFactory,
string senderDefaultApplVerId)
{
_schedule = sessionSchedule;
_msgFactory = msgFactory;
_appDoesEarlyIntercept = app is IApplicationExt;
Application = app;
SessionID = sessId;
DataDictionaryProvider = new DataDictionaryProvider(dataDictProvider);
SenderDefaultApplVerID = senderDefaultApplVerId;
SessionDataDictionary = DataDictionaryProvider.GetSessionDataDictionary(SessionID.BeginString);
ApplicationDataDictionary = SessionID.IsFIXT
? DataDictionaryProvider.GetApplicationDataDictionary(SenderDefaultApplVerID)
: SessionDataDictionary;
ILog log = logFactory.Create(sessId);
_state = new SessionState(isInitiator, log, heartBtInt, storeFactory.Create(sessId));
// Configuration defaults.
// Will be overridden by the SessionFactory with values in the user's configuration.
PersistMessages = true;
ResetOnDisconnect = false;
SendRedundantResendRequests = false;
ResendSessionLevelRejects = false;
ValidateLengthAndChecksum = true;
CheckCompID = true;
TimeStampPrecision = TimeStampPrecision.Millisecond;
EnableLastMsgSeqNumProcessed = false;
MaxMessagesInResendRequest = 0;
SendLogoutBeforeTimeoutDisconnect = false;
IgnorePossDupResendRequests = false;
RequiresOrigSendingTime = true;
CheckLatency = true;
MaxLatency = 120;
if (!IsSessionTime)
Reset("Out of SessionTime (Session construction)");
else if (IsNewSession)
Reset("New session");
lock (Sessions)
{
Sessions[SessionID] = this;
}
Application.OnCreate(SessionID);
Log.OnEvent("Created session");
}
#region Static Methods
/// <summary>
/// Looks up a Session by its SessionID
/// </summary>
/// <param name="sessionId">the SessionID of the Session</param>
/// <returns>the Session if found, else returns null</returns>
public static Session? LookupSession(SessionID sessionId)
{
lock (Sessions) {
if (Sessions.TryGetValue(sessionId, out Session? result))
return result;
}
return null;
}
/// <summary>
/// Looks up a Session by its SessionID
/// </summary>
/// <param name="sessionId">the SessionID of the Session</param>
/// <returns>the true if Session exists, false otherwise</returns>
public static bool DoesSessionExist(SessionID sessionId)
{
return LookupSession(sessionId) is not null;
}
/// <summary>
/// Sends a message to the session specified by the provider session ID.
/// </summary>
/// <param name="message">FIX message</param>
/// <param name="sessionId">target SessionID</param>
/// <returns>true if send was successful, false otherwise</returns>
public static bool SendToTarget(Message message, SessionID sessionId)
{
message.SetSessionID(sessionId);
Session? session = Session.LookupSession(sessionId);
if (session is null)
throw new SessionNotFound(sessionId);
return session.Send(message);
}
/// <summary>
/// Send to session indicated by header fields in message
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public static bool SendToTarget(Message message)
{
return SendToTarget(message, message.GetSessionID(message));
}
#endregion
/// <summary>
/// Sends a message via the session indicated by the header fields
/// </summary>
/// <param name="message">message to send</param>
/// <returns>true if was sent successfully</returns>
public virtual bool Send(Message message)
{
message.Header.RemoveField(Fields.Tags.PossDupFlag);
message.Header.RemoveField(Fields.Tags.OrigSendingTime);
return SendRaw(message, 0);
}
/// <summary>
/// Sends a message
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public bool Send(string message)
{
lock (_sync)
{
if (_responder is null)
return false;
Log.OnOutgoing(message);
return _responder.Send(message);
}
}
/// <summary>
/// Sets some internal state variables to enable the session.
/// </summary>
public void Logon()
{
_state.IsEnabled = true;
_state.LogoutReason = "";
}
/// <summary>
/// Sets some internal state variables to disable the session.
/// Users will be disconnected on next cycle.
/// </summary>
public void Logout(string reason = "")
{
_state.IsEnabled = false;
_state.LogoutReason = reason;
}
/// <summary>
/// Logs out from session and closes the network connection
/// </summary>
/// <param name="reason"></param>
public void Disconnect(string reason)
{
lock (_sync)
{
if (_responder is not null)
{
Log.OnEvent($"Session {SessionID} disconnecting: {reason}");
_responder.Disconnect();
_responder = null;
}
else
{
Log.OnEvent("Session {SessionID} already disconnected: {reason}");
}
if (_state.ReceivedLogon || _state.SentLogon)
{
_state.ReceivedLogon = false;
_state.SentLogon = false;
Application.OnLogout(SessionID);
}
_state.SentLogout = false;
_state.ReceivedReset = false;
_state.SentReset = false;
_state.ClearQueue();
_state.LogoutReason = "";
if (ResetOnDisconnect)
_state.Reset("ResetOnDisconnect");
_state.SetResendRange(0, 0);
}
}
/// <summary>
/// There's no message to process, but check the session state to see if there's anything to do
/// (e.g. send heartbeat, logout at end of session, etc)
/// </summary>
public void Next()
{
if (!HasResponder)
return;
if (!IsSessionTime)
{
if(IsInitiator)
Reset("Out of SessionTime (Session.Next())");
else
Reset("Out of SessionTime (Session.Next())", "Message received outside of session time");
return;
}
if (IsNewSession)
_state.Reset("New session (detected in Next())");
if (!IsEnabled)
{
if (!IsLoggedOn)
return;
if (!_state.SentLogout)
{
Log.OnEvent("Initiated logout request");
GenerateLogout(_state.LogoutReason);
}
}
if (!_state.ReceivedLogon)
{
if (_state.ShouldSendLogon && IsTimeToGenerateLogon())
{
if (GenerateLogon())
Log.OnEvent("Initiated logon request");
else
Log.OnEvent("Error during logon request initiation");
}
else if (_state.SentLogon && _state.LogonTimedOut())
{
Disconnect("Timed out waiting for logon response");
}
return;
}
if (0 == _state.HeartBtInt)
return;
if (_state.LogoutTimedOut())
Disconnect("Timed out waiting for logout response");
if (_state.WithinHeartbeat())
return;
if (_state.TimedOut())
{
if (SendLogoutBeforeTimeoutDisconnect)
GenerateLogout();
Disconnect("Timed out waiting for heartbeat");
}
else
{
if (_state.NeedTestRequest())
{
GenerateTestRequest("TEST");
_state.TestRequestCounter += 1;
Log.OnEvent("Sent test request TEST");
}
else if (_state.NeedHeartbeat())
{
GenerateHeartbeat();
}
}
}
/// <summary>
/// Process a message (in string form) from the counterparty
/// </summary>
/// <param name="msgStr"></param>
public void Next(string msgStr)
{
NextMessage(msgStr);
NextQueued();
}
/// <summary>
/// Process a message (in string form) from the counterparty
/// </summary>
/// <param name="msgStr"></param>
private void NextMessage(string msgStr)
{
Log.OnIncoming(msgStr);
MessageBuilder msgBuilder = new MessageBuilder(
msgStr,
SenderDefaultApplVerID,
ValidateLengthAndChecksum,
SessionDataDictionary,
ApplicationDataDictionary,
_msgFactory);
Next(msgBuilder);
}
/// <summary>
/// Process a message from the counterparty.
/// </summary>
/// <param name="msgBuilder"></param>
internal void Next(MessageBuilder msgBuilder)
{
if (!IsSessionTime)
{
Reset("Out of SessionTime (Session.Next(message))", "Message received outside of session time");
return;
}
if (IsNewSession)
_state.Reset("New session (detected in Next(Message))");
Message? message = null; // declared outside of try-block so that catch-blocks can use it
try
{
message = msgBuilder.Build();
if (_appDoesEarlyIntercept)
((IApplicationExt)Application).FromEarlyIntercept(message, SessionID);
string msgType = msgBuilder.MsgType.Obj;
string beginString = msgBuilder.BeginString;
if (!beginString.Equals(SessionID.BeginString))
throw new UnsupportedVersion(beginString);
if (MsgType.LOGON.Equals(msgType)) {
TargetDefaultApplVerId = SessionID.IsFIXT
? new ApplVerID(message.GetString(Fields.Tags.DefaultApplVerID))
: Message.GetApplVerID(beginString);
}
if (SessionID.IsFIXT && !Message.IsAdminMsgType(msgType))
{
DataDictionary.DataDictionary.Validate(message, SessionDataDictionary, ApplicationDataDictionary, beginString, msgType);
}
else
{
SessionDataDictionary.Validate(message, beginString, msgType);
}
if (MsgType.LOGON.Equals(msgType))
NextLogon(message);
else if (MsgType.LOGOUT.Equals(msgType))
NextLogout(message);
else if (!IsLoggedOn)
Disconnect($"Received msg type '{msgType}' when not logged on");
else if (MsgType.HEARTBEAT.Equals(msgType))
NextHeartbeat(message);
else if (MsgType.TEST_REQUEST.Equals(msgType))
NextTestRequest(message);
else if (MsgType.SEQUENCE_RESET.Equals(msgType))
NextSequenceReset(message);
else if (MsgType.RESEND_REQUEST.Equals(msgType))
NextResendRequest(message);
else
{
if (!Verify(message))
return;
_state.IncrNextTargetMsgSeqNum();
}
}
catch (InvalidMessage e)
{
Log.OnEvent(e.Message);
try
{
if (MsgType.LOGON.Equals(msgBuilder.MsgType.Obj))
Disconnect("Logon message is not valid");
}
catch (MessageParseError)
{ }
throw;
}
catch (TagException e)
{
if (e.InnerException is not null)
Log.OnEvent(e.InnerException.Message);
GenerateReject(msgBuilder, e.sessionRejectReason, e.Field);
}
catch (UnsupportedVersion uvx)
{
if (MsgType.LOGOUT.Equals(msgBuilder.MsgType.Obj))
{
NextLogout(message!);
}
else
{
Log.OnEvent(uvx.ToString());
GenerateLogout(uvx.Message);
_state.IncrNextTargetMsgSeqNum();
}
}
catch (UnsupportedMessageType e)
{
Log.OnEvent("Unsupported message type: " + e.Message);
GenerateBusinessMessageReject(message!, Fields.BusinessRejectReason.UNKNOWN_MESSAGE_TYPE, 0);
}
catch (FieldNotFoundException e)
{
Log.OnEvent("Rejecting invalid message, field not found: " + e.Message);
if (string.CompareOrdinal(SessionID.BeginString, FixValues.BeginString.FIX42) >= 0 && message!.IsApp())
{
GenerateBusinessMessageReject(message, Fields.BusinessRejectReason.CONDITIONALLY_REQUIRED_FIELD_MISSING, e.Field);
}
else
{
if (MsgType.LOGON.Equals(msgBuilder.MsgType.Obj))
{
Log.OnEvent("Required field missing from logon");
Disconnect("Required field missing from logon");
}
else
GenerateReject(msgBuilder, new QuickFix.FixValues.SessionRejectReason(SessionRejectReason.REQUIRED_TAG_MISSING, "Required Tag Missing"), e.Field);
}
}
catch (RejectLogon e)
{
GenerateLogout(e.Message);
Disconnect(e.ToString());
}
Next();
}
protected void NextLogon(Message logon)
{
Fields.ResetSeqNumFlag resetSeqNumFlag = new Fields.ResetSeqNumFlag(false);
if (logon.IsSetField(resetSeqNumFlag))
logon.GetField(resetSeqNumFlag);
_state.ReceivedReset = resetSeqNumFlag.Obj;
if (_state.ReceivedReset)
{
Log.OnEvent("Sequence numbers reset due to ResetSeqNumFlag=Y");
if (!_state.SentReset)
{
_state.Reset("Reset requested by counterparty");
}
}
if (IsAcceptor && ResetOnLogon)
_state.Reset("ResetOnLogon");
if (RefreshOnLogon)
Refresh();
if (!Verify(logon, false, true))
return;
if (!IsGoodTime(logon))
{
Log.OnEvent("Logon has bad sending time");
Disconnect("bad sending time");
return;
}
_state.ReceivedLogon = true;
Log.OnEvent("Received logon");
if (IsAcceptor)
{
int heartBtInt = logon.GetInt(Fields.Tags.HeartBtInt);
_state.HeartBtInt = heartBtInt;
GenerateLogon(logon);
Log.OnEvent($"Responding to logon request; heartbeat is {heartBtInt} seconds");
}
_state.SentReset = false;
_state.ReceivedReset = false;
SeqNumType msgSeqNum = logon.Header.GetULong(Fields.Tags.MsgSeqNum);
if (IsTargetTooHigh(msgSeqNum) && !resetSeqNumFlag.Obj)
{
DoTargetTooHigh(logon, msgSeqNum);
}
else
{
_state.IncrNextTargetMsgSeqNum();
}
if (IsLoggedOn)
Application.OnLogon(SessionID);
}
protected void NextTestRequest(Message testRequest)
{
if (!Verify(testRequest))
return;
GenerateHeartbeat(testRequest);
_state.IncrNextTargetMsgSeqNum();
}
protected void NextResendRequest(Message resendReq)
{
if (!Verify(resendReq, false, false))
return;
try {
SeqNumType msgSeqNum;
if (!(IgnorePossDupResendRequests && resendReq.Header.IsSetField(Tags.PossDupFlag)))
{
SeqNumType begSeqNo = resendReq.GetULong(Fields.Tags.BeginSeqNo);
SeqNumType endSeqNo = resendReq.GetULong(Fields.Tags.EndSeqNo);
Log.OnEvent("Got resend request from " + begSeqNo + " to " + endSeqNo);
if (endSeqNo == 999999 || endSeqNo == 0)
{
endSeqNo = _state.NextSenderMsgSeqNum - 1;
}
if (!PersistMessages)
{
endSeqNo++;
SeqNumType next = _state.NextSenderMsgSeqNum;
if (endSeqNo > next)
endSeqNo = next;
GenerateSequenceReset(resendReq, begSeqNo, endSeqNo);
msgSeqNum = resendReq.Header.GetULong(Tags.MsgSeqNum);
if (!IsTargetTooHigh(msgSeqNum) && !IsTargetTooLow(msgSeqNum))
{
_state.IncrNextTargetMsgSeqNum();
}
return;
}
List<string> messages = new List<string>();
_state.Get(begSeqNo, endSeqNo, messages);
SeqNumType current = begSeqNo;
SeqNumType begin = 0;
foreach (string msgStr in messages)
{
Message msg = new Message();
msg.FromString(msgStr, true, SessionDataDictionary, ApplicationDataDictionary, _msgFactory, ignoreBody: false);
msgSeqNum = msg.Header.GetULong(Tags.MsgSeqNum);
if (current != msgSeqNum && begin == 0)
{
begin = current;
}
if (IsAdminMessage(msg) && !(ResendSessionLevelRejects && msg.Header.GetString(Tags.MsgType) == MsgType.REJECT))
{
if (begin == 0)
{
begin = msgSeqNum;
}
}
else
{
InitializeResendFields(msg);
if(!ResendApproved(msg, SessionID))
{
continue;
}
if (begin != 0)
{
GenerateSequenceReset(resendReq, begin, msgSeqNum);
}
Send(msg.ToString());
begin = 0;
}
current = msgSeqNum + 1;
}
SeqNumType nextSeqNum = _state.NextSenderMsgSeqNum;
if (++endSeqNo > nextSeqNum)
{
endSeqNo = nextSeqNum;
}
if (begin == 0)
{
begin = current;
}
if (endSeqNo > begin)
{
GenerateSequenceReset(resendReq, begin, endSeqNo);
}
}
msgSeqNum = resendReq.Header.GetULong(Tags.MsgSeqNum);
if (!IsTargetTooHigh(msgSeqNum) && !IsTargetTooLow(msgSeqNum))
{
_state.IncrNextTargetMsgSeqNum();
}
}
catch (Exception e)
{
Log.OnEvent("ERROR during resend request " + e.Message);
}
}
private bool ResendApproved(Message msg, SessionID sessionId)
{
try
{
Application.ToApp(msg, sessionId);
}
catch (DoNotSend)
{
return false;
}
return true;
}
protected void NextLogout(Message logout)
{
if (!Verify(logout, false, false))
return;
string disconnectReason;
if (!_state.SentLogout)
{
disconnectReason = "Received logout request";
Log.OnEvent(disconnectReason);
GenerateLogout(logout);
Log.OnEvent("Sending logout response");
}
else
{
disconnectReason = "Received logout response";
Log.OnEvent(disconnectReason);
}
_state.IncrNextTargetMsgSeqNum();
if (ResetOnLogout)
_state.Reset("ResetOnLogout");
Disconnect(disconnectReason);
}
protected void NextHeartbeat(Message heartbeat)
{
if (!Verify(heartbeat))
return;
_state.IncrNextTargetMsgSeqNum();
}
protected void NextSequenceReset(Message sequenceReset)
{
bool isGapFill = false;
if (sequenceReset.IsSetField(Fields.Tags.GapFillFlag))
isGapFill = sequenceReset.GetBoolean(Fields.Tags.GapFillFlag);
if (!Verify(sequenceReset, isGapFill, isGapFill))
return;
if (sequenceReset.IsSetField(Fields.Tags.NewSeqNo))
{
SeqNumType newSeqNo = sequenceReset.GetULong(Fields.Tags.NewSeqNo);
Log.OnEvent("Received SequenceReset FROM: " + _state.NextTargetMsgSeqNum + " TO: " + newSeqNo);
if (newSeqNo > _state.NextTargetMsgSeqNum)
{
_state.NextTargetMsgSeqNum = newSeqNo;
}
else
{
if (newSeqNo < _state.NextTargetMsgSeqNum)
GenerateReject(sequenceReset, FixValues.SessionRejectReason.VALUE_IS_INCORRECT);
}
}
}
public bool Verify(Message msg, bool checkTooHigh = true, bool checkTooLow = true)
{
SeqNumType msgSeqNum = 0;
string msgType;
try
{
msgType = msg.Header.GetString(Fields.Tags.MsgType);
string senderCompId = msg.Header.GetString(Fields.Tags.SenderCompID);
string targetCompId = msg.Header.GetString(Fields.Tags.TargetCompID);
if (!IsCorrectCompId(senderCompId, targetCompId))
{
GenerateReject(msg, FixValues.SessionRejectReason.COMPID_PROBLEM);
GenerateLogout();
return false;
}
if (checkTooHigh || checkTooLow)
msgSeqNum = msg.Header.GetULong(Fields.Tags.MsgSeqNum);
if (checkTooHigh && IsTargetTooHigh(msgSeqNum))
{
DoTargetTooHigh(msg, msgSeqNum);
return false;
}
else if (checkTooLow && IsTargetTooLow(msgSeqNum))
{
DoTargetTooLow(msg, msgSeqNum);
return false;
}
if ((checkTooHigh || checkTooLow) && _state.ResendRequested())
{
ResendRange range = _state.GetResendRange();
if (msgSeqNum >= range.EndSeqNo)
{
Log.OnEvent("ResendRequest for messages FROM: " + range.BeginSeqNo + " TO: " + range.EndSeqNo + " has been satisfied.");
_state.SetResendRange(0, 0);
}
else if (msgSeqNum >= range.ChunkEndSeqNo)
{
Log.OnEvent("Chunked ResendRequest for messages FROM: " + range.BeginSeqNo + " TO: " + range.ChunkEndSeqNo + " has been satisfied.");
SeqNumType newChunkEndSeqNo = Math.Min(range.EndSeqNo, range.ChunkEndSeqNo + MaxMessagesInResendRequest);
GenerateResendRequestRange(msg.Header.GetString(Fields.Tags.BeginString), range.ChunkEndSeqNo + 1, newChunkEndSeqNo);
range.ChunkEndSeqNo = newChunkEndSeqNo;
}
}
if (!IsGoodTime(msg))
{
Log.OnEvent("Sending time accuracy problem");
GenerateReject(msg, FixValues.SessionRejectReason.SENDING_TIME_ACCURACY_PROBLEM);
GenerateLogout();
return false;
}
}
catch (Exception e)
{
Log.OnEvent("Verify failed: " + e.Message);
Disconnect("Verify failed: " + e.Message);
return false;
}
_state.LastReceivedTimeDT = DateTime.UtcNow;
_state.TestRequestCounter = 0;
if (Message.IsAdminMsgType(msgType))
Application.FromAdmin(msg, SessionID);
else
Application.FromApp(msg, SessionID);
return true;
}
public void SetResponder(IResponder responder)
{
if (!IsSessionTime)
Reset("Out of SessionTime (Session.SetResponder)");
lock (_sync)
{
_responder = responder;
}
}
public void Refresh()
{
_state.Refresh();