forked from connamara/quickfixn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAbstractInitiator.cs
394 lines (343 loc) · 13 KB
/
AbstractInitiator.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
#nullable enable
using System.Threading;
using System.Collections.Generic;
using System;
using QuickFix.Logger;
namespace QuickFix
{
public abstract class AbstractInitiator : IInitiator
{
// from constructor
private readonly SessionSettings _settings;
private readonly object _sync = new();
private readonly Dictionary<SessionID, Session> _sessions = new();
private readonly HashSet<SessionID> _sessionIDs = new();
private readonly HashSet<SessionID> _pending = new();
private readonly HashSet<SessionID> _connected = new();
private readonly HashSet<SessionID> _disconnected = new();
private readonly SessionFactory _sessionFactory;
private Thread? _thread;
#region Properties
public bool IsStopped { get; private set; } = true;
#endregion
protected AbstractInitiator(
IApplication app,
IMessageStoreFactory storeFactory,
SessionSettings settings,
ILogFactory? logFactoryNullable,
IMessageFactory? messageFactoryNullable)
{
_settings = settings;
var logFactory = logFactoryNullable ?? new NullLogFactory();
var msgFactory = messageFactoryNullable ?? new DefaultMessageFactory();
_sessionFactory = new SessionFactory(app, storeFactory, logFactory, msgFactory);
HashSet<SessionID> definedSessions = _settings.GetSessions();
if (0 == definedSessions.Count)
throw new ConfigError("No sessions defined");
}
public void Start()
{
if (_disposed)
throw new ObjectDisposedException(this.GetType().Name);
// create all sessions
foreach (SessionID sessionId in _settings.GetSessions())
{
Dictionary dict = _settings.Get(sessionId);
CreateSession(sessionId, dict);
}
if (0 == _sessions.Count)
throw new ConfigError("No sessions defined for initiator");
// start it up
IsStopped = false;
OnConfigure(_settings);
_thread = new Thread(OnStart);
_thread.Start();
}
/// <summary>
/// Add new session as an ad-hoc (dynamic) operation
/// </summary>
/// <param name="sessionId">ID of new session</param>
/// <param name="dict">config settings for new session</param>
/// <returns>true if session added successfully, false if session already exists or is not an initiator</returns>
public bool AddSession(SessionID sessionId, Dictionary dict)
{
lock (_settings)
if (!_settings.Has(sessionId)) // session won't be in settings if ad-hoc creation after startup
_settings.Set(sessionId, dict); // need to to this here to merge in default config settings
else
return false; // session already exists
if (CreateSession(sessionId, dict))
return true;
lock (_settings) // failed to create new session
_settings.Remove(sessionId);
return false;
}
/// <summary>
/// Create session, either at start-up or as an ad-hoc operation
/// </summary>
/// <param name="sessionId">ID of new session</param>
/// <param name="dict">config settings for new session</param>
/// <returns>true if session added successfully, false if session already exists or is not an initiator</returns>
private bool CreateSession(SessionID sessionId, Dictionary dict)
{
if (dict.GetString(SessionSettings.CONNECTION_TYPE) == "initiator" && !_sessionIDs.Contains(sessionId))
{
Session session = _sessionFactory.Create(sessionId, dict);
lock (_sync)
{
_sessionIDs.Add(sessionId);
_sessions[sessionId] = session;
SetDisconnected(sessionId);
}
return true;
}
return false;
}
/// <summary>
/// Ad-hoc removal of an existing session
/// </summary>
/// <param name="sessionId">ID of session to be removed</param>
/// <param name="terminateActiveSession">if true, force disconnection and removal of session even if it has an active connection</param>
/// <returns>true if session removed or not already present; false if could not be removed due to an active connection</returns>
public bool RemoveSession(SessionID sessionId, bool terminateActiveSession)
{
Session? session = null;
bool disconnectRequired = false;
lock (_sync)
{
if (_sessionIDs.Contains(sessionId))
{
session = _sessions[sessionId];
if (session.IsLoggedOn && !terminateActiveSession)
return false;
_sessions.Remove(sessionId);
disconnectRequired = IsConnected(sessionId) || IsPending(sessionId);
if (disconnectRequired)
SetDisconnected(sessionId);
_disconnected.Remove(sessionId);
_sessionIDs.Remove(sessionId);
}
}
lock (_settings)
_settings.Remove(sessionId);
if (disconnectRequired)
session?.Disconnect("Dynamic session removal");
OnRemove(sessionId); // ensure session's reader thread is gone before we dispose session
session?.Dispose();
return true;
}
/// <summary>
/// Logout existing session and close connection. Attempt graceful disconnect first.
/// </summary>
public void Stop()
{
Stop(false);
}
/// <summary>
/// Logout existing session and close connection
/// </summary>
/// <param name="force">If true, terminate immediately. </param>
public void Stop(bool force)
{
if (_disposed)
throw new ObjectDisposedException(this.GetType().Name);
if (IsStopped)
return;
lock (_sync)
{
foreach (SessionID sessionId in _connected)
{
Session? session = Session.LookupSession(sessionId);
if (session is not null && session.IsEnabled)
{
session.Logout();
}
}
}
if (!force)
{
// TODO change this duration to always exceed LogoutTimeout setting
for (int second = 0; (second < 10) && IsLoggedOn; ++second)
Thread.Sleep(1000);
}
lock (_sync)
{
HashSet<SessionID> connectedSessionIDs = new HashSet<SessionID>(_connected);
foreach (SessionID sessionId in connectedSessionIDs) {
Session? session = Session.LookupSession(sessionId);
if (session is not null)
SetDisconnected(session.SessionID);
}
}
IsStopped = true;
OnStop();
// Give OnStop() time to finish its business
_thread?.Join(5000);
_thread = null;
// dispose all sessions and clear all session sets
lock (_sync)
{
foreach (Session s in _sessions.Values)
s.Dispose();
_sessions.Clear();
_sessionIDs.Clear();
_pending.Clear();
_connected.Clear();
_disconnected.Clear();
}
}
public bool IsLoggedOn
{
get
{
lock (_sync)
{
foreach (SessionID sessionId in _connected)
{
Session? session = Session.LookupSession(sessionId);
return session is not null && session.IsLoggedOn;
}
}
return false;
}
}
#region Virtual Methods
/// <summary>
/// Override this to configure additional implemenation-specific settings
/// </summary>
/// <param name="settings"></param>
protected virtual void OnConfigure(SessionSettings settings)
{ }
/// <summary>
/// Implement this to provide custom reaction behavior to an ad-hoc session removal.
/// (This is called after the session is removed.)
/// </summary>
/// <param name="sessionId">ID of session that was removed</param>
protected virtual void OnRemove(SessionID sessionId)
{ }
#endregion
#region Abstract Methods
/// <summary>
/// Implemented to start connecting to targets.
/// </summary>
protected abstract void OnStart();
/// <summary>
/// Implemented to connect and poll for events.
/// </summary>
/// <param name="timeout"></param>
/// <returns></returns>
protected abstract bool OnPoll(double timeout);
/// <summary>
/// Implemented to stop a running initiator.
/// </summary>
protected abstract void OnStop();
/// <summary>
/// Implemented to connect a session to its target.
/// </summary>
/// <param name="session"></param>
/// <param name="settings"></param>
protected abstract void DoConnect(Session session, QuickFix.Dictionary settings);
#endregion
#region Protected Methods
protected void Connect()
{
lock (_sync)
{
HashSet<SessionID> disconnectedSessions = new HashSet<SessionID>(_disconnected);
foreach (SessionID sessionId in disconnectedSessions)
{
Session? session = Session.LookupSession(sessionId);
if (session is not null && session.IsEnabled)
{
if (session.IsNewSession)
session.Reset("New session");
if (session.IsSessionTime)
DoConnect(session, _settings.Get(sessionId));
}
}
}
}
protected void SetPending(SessionID sessionId)
{
lock (_sync)
{
_pending.Add(sessionId);
_connected.Remove(sessionId);
_disconnected.Remove(sessionId);
}
}
protected void SetConnected(SessionID sessionId)
{
lock (_sync)
{
_pending.Remove(sessionId);
_connected.Add(sessionId);
_disconnected.Remove(sessionId);
}
}
protected void SetDisconnected(SessionID sessionId)
{
lock (_sync)
{
if (_sessionIDs.Contains(sessionId))
{
_pending.Remove(sessionId);
_connected.Remove(sessionId);
_disconnected.Add(sessionId);
}
}
}
protected bool IsPending(SessionID sessionId)
{
lock (_sync)
{
return _pending.Contains(sessionId);
}
}
protected bool IsConnected(SessionID sessionId)
{
lock (_sync)
{
return _connected.Contains(sessionId);
}
}
protected bool IsDisconnected(SessionID sessionId)
{
lock (_sync)
{
return _disconnected.Contains(sessionId);
}
}
#endregion
/// <summary>
/// Get the SessionIDs for the sessions managed by this initiator.
/// </summary>
/// <returns>the SessionIDs for the sessions managed by this initiator</returns>
public HashSet<SessionID> GetSessionIDs()
{
return new HashSet<SessionID>(_sessions.Keys);
}
private bool _disposed = false;
/// <summary>
/// Any subclasses of AbstractInitiator should override this if they have resources to dispose
/// that aren't already covered in its OnStop() handler.
/// Any override should call base.Dispose(disposing).
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
this.Stop();
}
_disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~AbstractInitiator() => Dispose(false);
}
}