diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 421e0a2bf..1a9d66335 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -25,7 +25,9 @@ "-p", "8002:8002", "-p", - "8003:8003" + "8003:8003", + "-p", + "12345:12345" ], "mounts": [ "source=${localEnv:HOME}/.bts/devcontainer-mounts/${devcontainerId},target=/home/bts,type=bind" @@ -45,4 +47,4 @@ ] } } -} +} \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json index 800b9d764..fffec54ed 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -26,11 +26,23 @@ "stopAtEntry": false, "console": "integratedTerminal" }, + { + "name": "(gdb) Launch", + "type": "cppdbg", + "request": "launch", + "program": "/home/bts/spark/build/sparkd-debug-clang/server/sparkd", + "args": ["run"], + "stopAtEntry": false, + "cwd": "/home/bts/spark/build/sparkd-debug-clang/server", + "environment": [], + "externalConsole": false, + "MIMode": "gdb", + }, { "name": "DataStreamQueryAnalyzer", "type": "coreclr", "request": "launch", - "preLaunchTask": "Build DataStream (Debug)", + //"preLaunchTask": "Build DataStreamQueryAnalyzer (Debug)", "program": "", "windows": { "program": "DataStreamQueryAnalyzer.exe", diff --git a/CMakeLists.txt b/CMakeLists.txt index 7a13fc041..ab6ca60c2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -132,6 +132,8 @@ else() COMMAND ln ARGS -sf ${CMAKE_BINARY_DIR}/src/server/sparkd/sparkd ${CMAKE_BINARY_DIR}/server COMMAND ln ARGS -sf ${CMAKE_BINARY_DIR}/data_files ${CMAKE_BINARY_DIR}/server COMMAND ln ARGS -sf ${CMAKE_BINARY_DIR}/src/lib/libspark.so ${CMAKE_BINARY_DIR}/server + COMMAND ln ARGS -sf ${EXTERNALS_ROOT}/lib/${CMAKE_BUILD_TYPE}/libonixs-fix-engine.so.4 ${CMAKE_BINARY_DIR}/server + COMMAND ln ARGS -sf ${EXTERNALS_ROOT}/lib/Release/libOnixS.IceImpactMulticastPriceFeedHandlerCpp.so.3.16.0.0 diff --git a/externals b/externals index ff5f02bbd..8069cc893 160000 --- a/externals +++ b/externals @@ -1 +1 @@ -Subproject commit ff5f02bbde0f584493835ac267af34b31e637845 +Subproject commit 8069cc893f5cef3b6cb0e989bbdf6514cc153d29 diff --git a/src/DataStreamSuite/DataStream/Misc/TCPConnectionTestStream.cs b/src/DataStreamSuite/DataStream/Misc/TCPConnectionTestStream.cs index b275558da..3b3dc1e49 100644 --- a/src/DataStreamSuite/DataStream/Misc/TCPConnectionTestStream.cs +++ b/src/DataStreamSuite/DataStream/Misc/TCPConnectionTestStream.cs @@ -39,8 +39,8 @@ namespace BCG { protected override void myOnFirstSubscriber() { MasterWorker.getInstance(false).addWorker(this, _send_period); - var server_address = new BlutoSubAddress(_ip, _port); - bts.AsyncTCPConnector_APM.connect_to(server_address, this); + var server_rci = new RemoteConnectionInfo(_ip, _port); + bts.AsyncTCPConnector_APM.connect_to(server_rci, this); } protected override void myOnLastSubscriber() { diff --git a/src/DataStreamSuite/DataStream/Primitives/Distinct/DistinctRowStream.cs b/src/DataStreamSuite/DataStream/Primitives/Distinct/DistinctRowStream.cs index 8184b378a..a8d76a948 100644 --- a/src/DataStreamSuite/DataStream/Primitives/Distinct/DistinctRowStream.cs +++ b/src/DataStreamSuite/DataStream/Primitives/Distinct/DistinctRowStream.cs @@ -1,23 +1,24 @@ +using bts; + using System; using System.Collections; -namespace BCG -{ +namespace BCG { /// /// Provides a stream that with distinct rows with respect to the columns /// the user specifies in the argument /// - [DataStreamUserRespresentation ("distinct")] - public class DistinctRowStream : ViewStream - { - public DistinctRowStream (ViewStream stream, params string[] cols) - { - ArrayList groupByCols = new ArrayList (); - foreach (string col in cols) - foreach (string c in col.Split (' ')) - groupByCols.Add (c); - mySetRealSource (new GroupByStream (stream, - new DistinctRowEvaluator (groupByCols.ToArray (typeof(string)) as string[]), false)); + [DataStreamUserRespresentation("distinct")] + public class DistinctRowStream : ViewStream { + public DistinctRowStream(ViewStream stream, params string[] cols) { + var g_by_eval = new DistinctRowEvaluator(cols); + ViewStream r = new GroupByStream(stream, g_by_eval); + var proj_exp = String.Empty; + foreach (var c in cols) + proj_exp += $"{c} "; + proj_exp = proj_exp.Trim(); + r = new NewProjectStream(r, proj_exp); + mySetRealSource(r); } } } diff --git a/src/DataStreamSuite/DataStream/Primitives/FileStreams/DumpLoaderStream.cs b/src/DataStreamSuite/DataStream/Primitives/FileStreams/DumpLoaderStream.cs deleted file mode 100644 index b9d7cea15..000000000 --- a/src/DataStreamSuite/DataStream/Primitives/FileStreams/DumpLoaderStream.cs +++ /dev/null @@ -1,49 +0,0 @@ -// using System; -// using System.Collections.Generic; -// using System.Text; -// using System.IO; - -// using System.Runtime.Serialization.Formatters.Binary; - -// namespace BCG -// { -// public class DumpLoaderStream : ViewStream, ISideEffectStream -// { -// //wtf -// //public class Exception : System.Exception -// //{public Exception(string msg) : base(msg) { }} - -// public DumpLoaderStream(string fileName, int secondsBetweenPolls) -// { -// mySetRealSource( -// new PollStream(() => new LoaderStream(fileName).rows, secondsBetweenPolls, -// ViewStreamDatabase.instance)); -// } - -// public DumpLoaderStream(string fileName) -// { -// if (fileName == null) -// throw new LoaderStream.Exception("File name cannot be null"); - -// for (int i = 0; i < 5; i++) -// try -// { -// using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) -// { -// IClientDeserializer deser = new ClientUniversalDeserializer(); -// byte[] the_ops; -// Array the_rows; -// deser.deserialize(new Stream[] { fs }, out the_ops, out the_rows); - -// mySetRealSource(new BlueRowCollectionStaticStream((IBlueRowCollection)the_rows.GetValue(0))); -// } -// break; -// } -// catch (IOException) -// { -// System.Threading.Thread.Sleep(50); -// } - -// } -// } -// } diff --git a/src/DataStreamSuite/DataStream/Primitives/FileStreams/LoaderStream.cs b/src/DataStreamSuite/DataStream/Primitives/FileStreams/LoaderStream.cs index 8cb3ebc1c..b79e1a885 100644 --- a/src/DataStreamSuite/DataStream/Primitives/FileStreams/LoaderStream.cs +++ b/src/DataStreamSuite/DataStream/Primitives/FileStreams/LoaderStream.cs @@ -1,6 +1,7 @@ using BCG; namespace bts { + // This is the other side of the SaverStream, its "loads" the stream and fires once [DataStreamUserRespresentation("loader")] public class LoaderStream : ViewStream { diff --git a/src/DataStreamSuite/DataStream/Primitives/FileStreams/PersistorStream.cs b/src/DataStreamSuite/DataStream/Primitives/FileStreams/PersistorStream.cs index fbb1022ff..1755bf76f 100644 --- a/src/DataStreamSuite/DataStream/Primitives/FileStreams/PersistorStream.cs +++ b/src/DataStreamSuite/DataStream/Primitives/FileStreams/PersistorStream.cs @@ -5,10 +5,11 @@ using System.Text; using System.IO; using Google.Protobuf; using System.Globalization; -using bts; +using BCG; -namespace BCG { - // Writes all the udpates to a stream in a file. +namespace bts { + // Writes all the udpates to a stream in a file or multiples files dependong on the rollover size (as opposed to Saver + // which just writes one update, as a create) // File naming: // token_epoch_yyyyMMdd_HHmmss // File location: directory(passed)\token\ @@ -94,10 +95,10 @@ namespace BCG { void _on_change(object new_value) { DataPacket dp = new_value as DataPacket; byte[] serialized_update = null; - bool _write_create = _serializer == null || _n_updates_in_current_file == 0; + bool first_write = _serializer == null || _n_updates_in_current_file == 0; _serializer = _serializer ?? new UniversalStreamIOSerializer(); - if (_write_create) { - // new files always starts with create + if (first_write) { + // first file always starts with create serialized_update = _serializer.serialize(new bts.StreamIOMessage(new bts.StreamIOMessage.CreateMessage(dp.newRows))); } else serialized_update = _serializer.serialize(new bts.StreamIOMessage(new bts.StreamIOMessage.MultipleRemoveAddMessage(dp.deletedRows, dp.addedRows))); @@ -105,8 +106,8 @@ namespace BCG { long utc_epoch = epoch_now(); //time, length of data, data - bw.Write(utc_epoch); - bw.Write(serialized_update.Length); + //bw.Write(utc_epoch); + //bw.Write(serialized_update.Length); bw.Write(serialized_update); _out_fs.Flush(); myFireEvent(dp); diff --git a/src/DataStreamSuite/DataStream/Primitives/FileStreams/PlaybackStream.cs b/src/DataStreamSuite/DataStream/Primitives/FileStreams/PlaybackStream.cs deleted file mode 100644 index 6e2674347..000000000 --- a/src/DataStreamSuite/DataStream/Primitives/FileStreams/PlaybackStream.cs +++ /dev/null @@ -1,190 +0,0 @@ -// using System; -// using System.Collections.Generic; -// using System.Linq; -// using System.Text; -// using System.IO; -// using System.Runtime.Serialization.Formatters.Binary; -// using BCG.Utilities.General; -// using bts.collections; -// using System.Reflection.Metadata; - - -// namespace BCG { - -// public class PlaybackStream : ViewStream, IWorker { -// private readonly PlaybackType _type; -// private BlueTable _current_table; -// private IClientDeserializer _deserilializer = new ClientUniversalDeserializer(); -// // these are the packets already downloaded from the current file -// private List _packets = new List(); -// //private IEnumerable _file_streams = new List(); -// private IEnumerable _file_names; -// private Tuple _current_fs = new Tuple(-1, null); -// private DateTime _playback_t0, _playback_t1; -// private bool _all_files_read = false; -// SnapshotData _snapshot_data = null; // only initialized when in snapshot mode - -// public PlaybackStream(string datetime_start, string datetime_end, string directory_name, string token) { -// _type = PlaybackType.Streaming; -// _playback_t0 = PersistorStream.parse_datetime(datetime_start); -// _playback_t1 = PersistorStream.parse_datetime(datetime_end); -// string token_directory_name = $"{directory_name}\\{token}"; -// bts.Log.Gen.info($"PlaybackStream t0: {_playback_t0} t1: {_playback_t1} dir: {token_directory_name}"); -// List files_in_range = new List(); -// if (Directory.Exists(token_directory_name)) { -// _file_names = -// Directory.GetFiles(token_directory_name).Where(f => { -// DateTime file_time = PersistorStream.parse_datetime_from_filename(f); -// return file_time > _playback_t0 && file_time < _playback_t1; -// }); -// } -// } - -// protected override void myOnFirstSubscriber() { -// FileStream fs = new FileStream(_snapshot_data.snapshot_file, FileMode.Open, FileAccess.Read); -// _snapshot_data.packets = StreamPersistorUtils.load_packets_from_file(fs); -// PlaybackPacket snapshot_packet = StreamPersistorUtils.find_packet_at_time(_snapshot_data.packets, _snapshot_data.snapshot_time); -// if (snapshot_packet != null) { -// foreach (PlaybackPacket p in _snapshot_data.packets) { -// byte[] ops; -// Array row_array; -// _deserilializer.deserialize(new Stream[] { new MemoryStream(p.data) }, out ops, out row_array); -// for (int i = 0; i < ops.Length; i++) { -// IBlueRowCollection[] rows_args = row_array.GetValue(i) as IBlueRowCollection[]; -// byte op = ops[i]; -// if (op == StreamOpCode.create) { -// IBlueRowCollection full_table = rows_args[0]; -// _current_table = new BlueTable(full_table); -// } else if (op == StreamOpCode.multipleRemoveAdd) { -// //IBlueRowCollection[] del_added = rows_args.GetValue(0) as IBlueRowCollection[]; -// IBlueRowCollection dels = rows_args.GetValue(0) as IBlueRowCollection; -// IBlueRowCollection adds = rows_args.GetValue(1) as IBlueRowCollection; -// BlueDataUtility.absorbChanges(_current_table, dels, adds); -// } else { -// bts.Log.assert(false, $"Oprator: {op} is not expected"); -// } -// if (p.idx == snapshot_packet.idx) { -// myFireEvent(new DataPacket(_current_table, _current_table, new BlueTable(_current_table.schema))); -// break; -// } -// } -// } -// } -// } - - -// private void _load_packets_from_current_file() { -// int curr_idx = _current_fs.Item1; -// FileStream curr_fs = _current_fs.Item2; -// _packets = new List(); -// _packets.AddRange(StreamPersistorUtils.load_packets_from_file(curr_fs)); -// } - -// private bool current_file_all_replayed { -// get { -// bool rv = true; -// _packets.ForEach(p => rv = rv && p.replayed); -// return rv; -// } -// } - -// protected override void myOnLastSubscriber() { -// var fs = _current_fs.Item2; -// if (fs != null) { -// fs.Close(); -// } -// ViewStreamDatabase.instance.removeWorker(this); -// } - -// // public event PlaybackStreamProgress onProgress; -// // public event Action onFileExhausted; -// private PlaybackPacket _locate_packet_to_replay() { -// foreach (var p in _packets) { -// // returns the first non replayed packet -// if (!p.replayed) -// return p; -// } -// //else -// { -// double secondsElapsed = new BinaryReader(myFileReader).ReadDouble(); -// myNextPacketTime = myPlaybackStart + new TimeSpan(0, 0, 0, 0, (int)(1000 * secondsElapsed / myPlaybackSpeed)); -// if (onProgress != null) -// onProgress(myFileReader.Position, myFileReader.Length); -// } -// } - -// #region IWorker Members - -// public void doWork() { -// if (_all_files_read) -// return; -// if (current_file_all_replayed) { -// _load_next_file(); -// } -// PlaybackPacket curr_packet = _locate_packet_to_replay(); -// if (curr_packet.idx == 0) { // first packet in the file, fire it rightaway -// byte[] ops; -// Array row_array; -// // what a stupid interface! -// _deserilializer.deserialize(new Stream[] { new MemoryStream(curr_packet.data) }, out ops, out row_array); -// _fire_packet(ops, row_array); -// curr_packet.replay_timestamp = PersistorStream.epoch_now(); -// } else { -// PlaybackPacket prev_packet = _get_previous_packet(curr_packet); -// // this is the time we need to fire (replay) this packet -// long time_to_fire = prev_packet.replay_timestamp + curr_packet.offset_from_previous; -// long now_epoch = PersistorStream.epoch_now(); -// // fire when we are past the -// if (now_epoch >= time_to_fire) { -// byte[] ops; -// Array row_array; -// _deserilializer.deserialize(new Stream[] { new MemoryStream(curr_packet.data) }, out ops, out row_array); -// _fire_packet(ops, row_array); -// curr_packet.replay_timestamp = PersistorStream.epoch_now(); -// } -// } -// } - -// private void _fire_packet(byte[] ops, Array row_array) { -// for (int i = 0; i < ops.Length; i++) { -// IBlueRowCollection[] rows_args = row_array.GetValue(i) as IBlueRowCollection[]; -// byte op = ops[i]; -// if (op == StreamOpCode.create) { -// IBlueRowCollection full_table = rows_args[0]; -// _current_table = new BlueTable(full_table); -// //_current_table.addRows(full_table); -// myFireEvent(new DataPacket(full_table, full_table, myLastValue == null ? new BlueTable(full_table.schema) : -// (myLastValue as DataPacket).newRows)); -// } else if (op == StreamOpCode.multipleRemoveAdd) { -// //IBlueRowCollection[] del_added = rows_args.GetValue(0) as IBlueRowCollection[]; -// IBlueRowCollection dels = rows_args.GetValue(0) as IBlueRowCollection; -// IBlueRowCollection adds = rows_args.GetValue(1) as IBlueRowCollection; -// BlueDataUtility.absorbChanges(_current_table, dels, adds); -// myFireEvent(new DataPacket(_current_table, adds, dels)); -// } else { -// bts.Log.assert(false, $"Oprator: {op} is not expected"); -// } - -// } -// } - -// private void _load_next_file() { -// var new_idx = _current_fs.Item1 + 1; -// if (new_idx >= _file_names.Count()) { -// _all_files_read = true; -// bts.Log.Gen.info("All files read"); -// return; -// } -// var prev_fs = _current_fs.Item2; -// if (prev_fs != null) -// prev_fs.Close(); -// var new_filename = _file_names.ElementAt(new_idx); -// bts.Log.Gen.info("PlaybackStream_load_next_file new_filename=: {new_filename}"); -// var new_fs = new FileStream(new_filename, FileMode.Open, FileAccess.Read); -// _current_fs = new Tuple(new_idx, new_fs); -// _load_packets_from_current_file(); -// } - -// #endregion -// } -// } diff --git a/src/DataStreamSuite/DataStream/Primitives/FileStreams/RecorderStream.cs b/src/DataStreamSuite/DataStream/Primitives/FileStreams/RecorderStream.cs deleted file mode 100644 index 1e7da4c49..000000000 --- a/src/DataStreamSuite/DataStream/Primitives/FileStreams/RecorderStream.cs +++ /dev/null @@ -1,68 +0,0 @@ -// using System; -// using System.Collections.Generic; -// using System.Linq; -// using System.Text; -// using System.IO; - -// namespace BCG -// { -// public class RecorderStream : ViewStream -// { -// private ViewStream mySource; -// private DateTime myStartTime; -// private FileStream myOutFile; -// private string myFileName; -// private IBlueDataSerializer mySerializer; - -// public RecorderStream(ViewStream src, string recordFile) -// { -// mySource = src; -// myFileName = recordFile; - -// myFileName = myFileName.Replace("%DATE%", DateTime.Now.ToString("yyyyMMdd_HHmmss")); -// } - -// protected override void myOnFirstSubscriber() -// { -// myStartTime = DateTime.Now; -// mySource.onChange += new ChangeDelegate(mySource_onChange); -// myOutFile = new FileStream(myFileName, FileMode.OpenOrCreate); -// } - -// protected override void myOnLastSubscriber() -// { -// mySource.onChange -= mySource_onChange; -// myOutFile.Close(); -// } - -// void mySource_onChange(object newValue) -// { -// DataPacket dp = (DataPacket)newValue; - -// BlueTable toWrite = new BlueTable(dp.schema); - -// if (mySerializer == null) -// { -// mySerializer = new UniversalSerializer(dp.schema); -// } -// foreach (IBlueRow r in dp.newRows) -// toWrite.addRow(r); - -// byte[] result; - -// if (myLastValue == null) -// mySerializer.serialize(StreamOpCode.create, new IBlueRowCollection[] { dp.newRows }, out result); -// else -// mySerializer.serialize(StreamOpCode.multipleRemoveAdd, new IBlueRowCollection[] { dp.deletedRows, dp.addedRows }, out result); - -// BinaryWriter bw = new BinaryWriter(myOutFile); -// //write down what time this happened -// bw.Write((DateTime.Now - myStartTime).TotalSeconds); -// bw.Write(result.Length); -// bw.Write(result); -// myOutFile.Flush(); - -// myFireEvent(dp); -// } -// } -// } diff --git a/src/DataStreamSuite/DataStream/Primitives/FileStreams/SaverStream.cs b/src/DataStreamSuite/DataStream/Primitives/FileStreams/SaverStream.cs index 1af59181b..922b4022b 100644 --- a/src/DataStreamSuite/DataStream/Primitives/FileStreams/SaverStream.cs +++ b/src/DataStreamSuite/DataStream/Primitives/FileStreams/SaverStream.cs @@ -5,7 +5,8 @@ using System.IO; using BCG; namespace bts { - // this saves the total state in the filr provided in the cons + // this saves the updates as a Create on the same file, each update calls -save, which + // reqrites the whole data to the packet. The other side of this stream is the Loader [DataStreamUserRespresentation("saver")] public class SaverStream : ViewStream { private ViewStream _stream; @@ -31,7 +32,6 @@ namespace bts { StreamIOMessage.CreateMessage cr_msg = new StreamIOMessage.CreateMessage(dp.newRows); byte[] str_bytes = _serializer.serialize(new StreamIOMessage(cr_msg)); StreamSerializationUtils.write_to_file(str_bytes, _filename); - } } } diff --git a/src/DataStreamSuite/DataStream/Primitives/FileStreams/StreamPersistorUtils.cs b/src/DataStreamSuite/DataStream/Primitives/FileStreams/StreamPersistorUtils.cs index 31f1bf186..0142acfa7 100644 --- a/src/DataStreamSuite/DataStream/Primitives/FileStreams/StreamPersistorUtils.cs +++ b/src/DataStreamSuite/DataStream/Primitives/FileStreams/StreamPersistorUtils.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Globalization; using System.IO; +using bts; namespace BCG { diff --git a/src/DataStreamSuite/DataStream/Primitives/Misc/PubSubTestStream.cs b/src/DataStreamSuite/DataStream/Primitives/Misc/PubSubTestStream.cs index 958ef6f40..0225ecb7b 100644 --- a/src/DataStreamSuite/DataStream/Primitives/Misc/PubSubTestStream.cs +++ b/src/DataStreamSuite/DataStream/Primitives/Misc/PubSubTestStream.cs @@ -8,26 +8,33 @@ using System; using System.IO; using System.Linq; -namespace bts { - public class PubSubTestingStream : ViewStream, IWorker { - public class PayloadMessage { +namespace bts +{ + public class PubSubTestingStream : ViewStream, IWorker + { + public class PayloadMessage + { public int msg_id = 0; public string guid; public Int64 travel_epoch_ms = 0; public byte[] payload = null; - public PayloadMessage(int msg_id_args, Int64 send_epoch_args, int payload_size, byte payload_byte) { + public PayloadMessage(int msg_id_args, Int64 send_epoch_args, int payload_size, byte payload_byte) + { msg_id = msg_id_args; travel_epoch_ms = send_epoch_args; payload = new byte[payload_size]; - for (int i = 0; i < payload_size; i++) { + for (int i = 0; i < payload_size; i++) + { payload[i] = payload_byte; } } private PayloadMessage() { } public PayloadMessage(int msg_id, int payload_size, byte payload_byte) : - this(msg_id, PubSubTestingStream.epoch_now(), payload_size, payload_byte) { } + this(msg_id, PubSubTestingStream.epoch_now(), payload_size, payload_byte) + { } - public byte[] serialize() { + public byte[] serialize() + { var str = new MemoryStream(); BinaryWriter bw = new BinaryWriter(str); bw.Write(msg_id); @@ -40,7 +47,8 @@ namespace bts { return bytes; } - public static PayloadMessage deserialize(byte[] ser_bytes) { + public static PayloadMessage deserialize(byte[] ser_bytes) + { var str = new MemoryStream(ser_bytes); BinaryReader br = new BinaryReader(str); int msg_id = br.ReadInt32(); @@ -48,7 +56,8 @@ namespace bts { Int64 epoch = br.ReadInt64(); int len = br.ReadInt32(); var payload = br.ReadBytes(len); - return new PayloadMessage() { + return new PayloadMessage() + { msg_id = msg_id, guid = guid, travel_epoch_ms = epoch, @@ -73,7 +82,8 @@ namespace bts { private readonly int _payload_sz; private const byte _payload_byte = (byte)'A'; private readonly string _tag_name; - public PubSubTestingStream(int publish_period_msecs, int max_pubs, int payload_size, string tag_name, ViewStreamDatabase vsd) { + public PubSubTestingStream(int publish_period_msecs, int max_pubs, int payload_size, string tag_name, ViewStreamDatabase vsd) + { _vsd = vsd; _payload_sz = payload_size; var schema = BlueDataUtility.form_schema("PubSubTest", @@ -96,43 +106,53 @@ namespace bts { public PubSubTestingStream(int publish_period_seconds, int max_pubs, int msg_size, string tag_name) : this(publish_period_seconds, max_pubs, msg_size, tag_name, ViewStreamDatabase.instance) { } - protected override void myOnFirstSubscriber() { + protected override void myOnFirstSubscriber() + { _vsd.addWorker(this); System.Threading.Thread th = new System.Threading.Thread(_subscribe_thread_func); th.IsBackground = true; th.Start(); } - protected override void myOnLastSubscriber() { + protected override void myOnLastSubscriber() + { _vsd.removeWorker(this); _continue_sub_thread = false; } - void _log_updates(IEnumerable updates) { + void _log_updates(IEnumerable updates) + { var idx = 0; - foreach (var msg in updates) { + foreach (var msg in updates) + { bts.Log.Gen.info($"PubSubTesStream._subscribe_thread_func idx: {idx} msg: {msg}"); idx++; } } - private void _subscribe_thread_func() { + private void _subscribe_thread_func() + { // subscription is done in another thread SubscriberCore sub_core = new SubscriberCore(); sub_core.subscribe(_tag_name); - while (_continue_sub_thread) { + while (_continue_sub_thread) + { // TODO recv_id var updates = sub_core.get_updates(TimeSpan.FromMilliseconds(250)); if (updates == null || updates.Count() == 0) continue; _log_updates(updates); _n_updates += updates.Count(); - if (updates.Count() > 0) { + if (updates.Count() > 0) + { var server_msg = updates.Last(); - if (server_msg.data != null && server_msg.data.Length > 0) { + if (server_msg.data != null && server_msg.data.Length > 0) + { _last_recvd_msg = PayloadMessage.deserialize(server_msg.data); _last_recvd_msg.travel_epoch_ms = epoch_now(); - } else { + } + else + { // why are we getting empty or null data ? (server is sending data regardless?) } _fire_dirty = true; @@ -140,28 +160,36 @@ namespace bts { } } - private void _publish_next_packet() { - if (_last_sent_msg == null) { - _last_sent_msg = new PayloadMessage(0, _payload_sz, _payload_byte) { + private void _publish_next_packet() + { + if (_last_sent_msg == null) + { + _last_sent_msg = new PayloadMessage(0, _payload_sz, _payload_byte) + { guid = Guid.NewGuid().ToString() }; - } else { + } + else + { _last_sent_msg.msg_id++; _last_sent_msg.guid = Guid.NewGuid().ToString(); _last_sent_msg.travel_epoch_ms = epoch_now(); } var ser_bytes = _last_sent_msg.serialize(); _n_pubs++; - _pub_core.publish(String.Empty, _tag_name, ser_bytes); + _pub_core.publish("Blob", _tag_name, ser_bytes); + _fire_dirty = true; } - private void _fire_dp() { + private void _fire_dp() + { object last_sent_id = _last_sent_msg == null ? (object)DBNull.Value : (object)_last_sent_msg.msg_id; object last_recv_id = _last_recvd_msg == null ? (object)DBNull.Value : (object)_last_recvd_msg.msg_id; object echo_time = DBNull.Value; object last_sent_guid = _last_sent_msg == null ? (object)DBNull.Value : (object)_last_sent_msg.guid; object last_recv_guid = _last_recvd_msg == null ? (object)DBNull.Value : (object)_last_recvd_msg.guid; - if (_last_sent_msg != null && _last_recvd_msg != null) { + if (_last_sent_msg != null && _last_recvd_msg != null) + { echo_time = _last_recvd_msg.travel_epoch_ms - _last_sent_msg.travel_epoch_ms; } var match = last_sent_id.Equals(last_recv_id) && last_sent_guid.Equals(last_recv_guid); @@ -173,21 +201,25 @@ namespace bts { myFireEvent(dp); } - public void doWork() { + public void doWork() + { if (DateTime.Now - _last_publish_time > _publish_period) - if (_n_pubs <= _max_pubs) { + if (_n_pubs <= _max_pubs) + { _publish_next_packet(); _last_publish_time = DateTime.Now; } // publish // TODO: send id - if (_fire_dirty) { + if (_fire_dirty) + { _fire_dirty = false; _fire_dp(); } } - public static long epoch_now() { + public static long epoch_now() + { return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); } diff --git a/src/DataStreamSuite/DataStream/Primitives/Misc/PubsubEchoTestStream.cs b/src/DataStreamSuite/DataStream/Primitives/Misc/PubsubEchoTestStream.cs new file mode 100644 index 000000000..b37570af9 --- /dev/null +++ b/src/DataStreamSuite/DataStream/Primitives/Misc/PubsubEchoTestStream.cs @@ -0,0 +1,223 @@ +using BCG; +using BCG.Utilities.General; +using System.Collections.Generic; + + +using System; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using bts.api; + +namespace bts +{ + [DataStreamUserRespresentation("pss_echo")] + public class PubsubEchoTestStream : ViewStream, IWorker + { + public class PayloadMessage + { + public readonly string msg_id; + public readonly Int64 timestamp = 0; + public readonly byte[] payload = null; + + public static byte[] create_data(int payload_size, byte payload_byte) + { + var rv = new byte[payload_size]; + for (int i = 0; i < payload_size; i++) + { + rv[i] = payload_byte; + } + return rv; + } + + // public PayloadMessage(string guid_, Int64 timestamp_, int payload_size, byte payload_byte) + // { + // guid = guid_; + // timestamp = timestamp_; + // payload = new byte[payload_size]; + // for (int i = 0; i < payload_size; i++) + // { + // payload[i] = payload_byte; + // } + // } + public PayloadMessage(string guid_, Int64 timestamp_, byte[] payload_) + { + msg_id = guid_; + timestamp = timestamp_; + payload = payload_; + } + + private PayloadMessage() { } + public byte[] serialize() + { + var str = new MemoryStream(); + BinaryWriter bw = new BinaryWriter(str); + bw.Write(msg_id); + bw.Write(timestamp); + bw.Write(payload.Length); + bw.Write(payload); + str.Position = 0; + var bytes = str.ToArray(); + return bytes; + } + + public static PayloadMessage deserialize(byte[] ser_bytes) + { + var str = new MemoryStream(ser_bytes); + BinaryReader br = new BinaryReader(str); + string guid = br.ReadString(); + Int64 timestamp_ = br.ReadInt64(); + int len = br.ReadInt32(); + var payload = br.ReadBytes(len); + return new PayloadMessage(guid, timestamp_, payload); + } + } + //public void + private readonly int _msg_size; + private readonly TimeSpan _publish_period; + private DateTime _last_publish_time = DateTime.MinValue; + private PublisherCore _pub_core; + private ISubscriberCore _sub_core; + private BlueTable _table; + private int _n_pubs = 0; + private readonly int _max_pubs; + private int _n_updates = 0; + private ViewStreamDatabase _vsd; + private PayloadMessage _last_sent_msg, _last_recvd_msg; + private const byte _payload_byte = (byte)'A'; + private readonly string _tag_name; + private readonly int _payload_sz; + private readonly IPubSubRouter _router; + private enum IOState + { + SEND = 0, + RECV = 1 + }; + IOState _state = IOState.SEND; + + public PubsubEchoTestStream(string server_url, TimeSpan publish_period, int payload_size, string tag_name, ViewStreamDatabase vsd) + { + var route = new PubSubRoute(server_url, ".*"); + _router = new PubSubRouter(route); + _vsd = vsd; + _payload_sz = payload_size; + var schema = BlueDataUtility.form_schema("PubSubTest", + Tuple.Create("id", TypeCode.Int32), + Tuple.Create("sent_id", TypeCode.String), + Tuple.Create("sent_time", TypeCode.Int64), + Tuple.Create("recv_id", TypeCode.String), + Tuple.Create("recv_time", TypeCode.Int64), + Tuple.Create("match", TypeCode.Boolean), + Tuple.Create("echo_time", TypeCode.Int32)); + _table = new BlueTable(schema); + _publish_period = publish_period; + _tag_name = tag_name; + } + + public PubsubEchoTestStream(string server_url, int publish_period_msecs, int payload_size, string tag_name) + : this(server_url, TimeSpan.FromMilliseconds(publish_period_msecs), payload_size, tag_name, ViewStreamDatabase.instance) { } + + protected override void myOnFirstSubscriber() + { + _pub_core = new PublisherCore(_router); + _sub_core = new SubscriberCore(_router); + _sub_core.subscribe(_tag_name); + _vsd.addWorker(this); + + } + + protected override void myOnLastSubscriber() + { + _vsd.removeWorker(this); + _sub_core.unsubscribe(_tag_name); + } + + private void _fire_dp_after_send() + { + // as soon as the data is published, its reflected in the stream state + Log.assert(_last_sent_msg != null); + BlueRow r = new BlueRow(_table.schema, _table.Count, _last_sent_msg.msg_id, _last_sent_msg.timestamp, DBNull.Value, DBNull.Value, + DBNull.Value, DBNull.Value); + _table.addRow(r); + var dp_out = BlueDataUtility.build_dp_inc(_table, myLastValue as DataPacket); + myFireEvent(dp_out); + } + + private void _fire_dp_after_recv() + { + Log.assert(_last_recvd_msg != null); + // update the last publish row + int id = _table.Count - 1; + IBlueRow last_row = _table[id]; + _table.deleteRow(last_row); + var recv_ts = epoch_now(); + BlueRow nr = new BlueRow(_table.schema, id, _last_sent_msg.msg_id, _last_sent_msg.timestamp, _last_recvd_msg.msg_id, recv_ts, + String.Compare(_last_recvd_msg.msg_id, _last_sent_msg.msg_id) == 0, recv_ts - _last_recvd_msg.timestamp); + _table.addRow(nr); + var dp_out = BlueDataUtility.build_dp_inc(_table, myLastValue as DataPacket); + myFireEvent(dp_out); + } + + private string _get_next_id() + { + return _table.Count.ToString(); + } + + private void _publish_next_packet() + { + var bytes = PayloadMessage.create_data(_payload_sz, _payload_byte); + _last_sent_msg = new PayloadMessage(_get_next_id(), epoch_now(), bytes); + var ser_bytes = _last_sent_msg.serialize(); + _n_pubs++; + _pub_core.publish("Blob", _tag_name, ser_bytes); + _last_publish_time = DateTime.Now; + } + + public void doWork() + { + Func, PayloadMessage> find_packet = (updates) => + { + foreach (var u in updates) + { + var recv_msg = PayloadMessage.deserialize(u.data); + if (recv_msg.msg_id == _last_sent_msg.msg_id) + { + return recv_msg; + } + } + return null; + }; + switch (_state) + { + case IOState.SEND: + if (DateTime.Now - _last_publish_time >= _publish_period) + { + _publish_next_packet(); + _last_publish_time = DateTime.Now; + _fire_dp_after_send(); + _state = IOState.RECV; + return; + } + break; + case IOState.RECV: + var updates = _sub_core.get_updates(TimeSpan.Zero); + updates = updates.Where(u => u.tag == _tag_name); + var recv_msg = find_packet(updates); + if (recv_msg != null) + { + _last_recvd_msg = recv_msg; + _fire_dp_after_recv(); + _state = IOState.SEND; + break; + } + break; + } + } + + public static long epoch_now() + { + return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + } + + } +} \ No newline at end of file diff --git a/src/DataStreamSuite/DataStream/Primitives/Misc/SimpleTCPEchoStream.cs b/src/DataStreamSuite/DataStream/Primitives/Misc/SimpleTCPEchoStream.cs index 555d9c471..4d25d5ca4 100644 --- a/src/DataStreamSuite/DataStream/Primitives/Misc/SimpleTCPEchoStream.cs +++ b/src/DataStreamSuite/DataStream/Primitives/Misc/SimpleTCPEchoStream.cs @@ -14,11 +14,14 @@ namespace bts { private BlueTable _table; private SyncQueue _action_queue = new SyncQueue(); - public SimpleTCPEchoStream(string ip, int port, int msg_sz, int send_wait_period_ms) { + public SimpleTCPEchoStream(string ip, int port, int msg_sz, int send_wait_period_ms) + : this(ip, port, msg_sz, send_wait_period_ms, Int32.MaxValue) { } + + public SimpleTCPEchoStream(string ip, int port, int msg_sz, int send_wait_period_ms, int max_n_msgs) { _ip = ip; _port = port; _table = new BlueTable(_schema); - _tcp_client = new SimpleTCPClient(_ip, _port, Convert.ToUInt32(msg_sz), send_wait_period_ms); + _tcp_client = new SimpleTCPClient(_ip, _port, Convert.ToUInt32(msg_sz), send_wait_period_ms, max_n_msgs); } protected override void myOnFirstSubscriber() { diff --git a/src/DataStreamSuite/DataStream/Primitives/Misc/TestStream.cs b/src/DataStreamSuite/DataStream/Primitives/Misc/TestStream.cs index f58a7b829..ebd1652ae 100644 --- a/src/DataStreamSuite/DataStream/Primitives/Misc/TestStream.cs +++ b/src/DataStreamSuite/DataStream/Primitives/Misc/TestStream.cs @@ -43,11 +43,11 @@ namespace BCG { Tuple.Create("exception", TypeCode.String) ); // register tests here - // _tests.Add(new Func(_run_sub_msg_test)); - // _tests.Add(new Func(_run_pub_msg_test)); - // _tests.Add(new Func(_run_pubsub_server_msg_test)); - // _tests.Add(new Func(_run_pubsub_client_msg_test)); - // _tests.Add(new Func(_run_columninfo_serialization_test)); + _tests.Add(new Func(_run_sub_msg_test)); + _tests.Add(new Func(_run_pub_msg_test)); + _tests.Add(new Func(_run_pubsub_server_msg_test)); + _tests.Add(new Func(_run_pubsub_client_msg_test)); + _tests.Add(new Func(_run_columninfo_serialization_test)); // _tests.Add(new Func(_run_schema_serialization_test)); // _tests.Add(new Func(_row_serialization_tests_no_dbnulls)); // _tests.Add(new Func(_row_serialization_tests_with_dbnulls)); diff --git a/src/DataStreamSuite/DataStream/Primitives/Misc/TickingTestStream.cs b/src/DataStreamSuite/DataStream/Primitives/Misc/TickingTestStream.cs new file mode 100644 index 000000000..b5ee8873b --- /dev/null +++ b/src/DataStreamSuite/DataStream/Primitives/Misc/TickingTestStream.cs @@ -0,0 +1,31 @@ +namespace BCG { + using System; + + public class TickingTestStream : ViewStream { + public TickingTestStream(int ticking_period_msecs) + : + this(ViewStreamDatabase.instance, TimeSpan.FromSeconds(ticking_period_msecs)) { } + + public TickingTestStream(ViewStreamDatabase vsd, TimeSpan ticking_period_msecs) { + ViewStream vs = new DisplayableMillisecondStream(Convert.ToInt32(ticking_period_msecs.TotalMilliseconds), 10); + vs = new MathStream(vs, "x=id*123 y=x*x"); + mySetRealSource(vs); + //vs.onChange += _on_str_update; + } + + // private void _on_str_update(object dp_obj) { + // DataPacket dp = dp_obj as DataPacket; + // IBlueTableSchema out_schema = BlueDataUtility.add_column(dp.schema, "time_txt", typeof(string)); + // BlueTable state = new BlueTable(out_schema); + // foreach (IBlueRow r in dp.newRows) { + // MutableBlueRow nr = new MutableBlueRow(out_schema, r); + // DateTime time = r.get_datetime("time"); + // var time_txt = time.ToString("yyyy-MM-dd HH:mm:ss.fff"); + // nr.setValue("time_txt", time_txt); + // state.addRow(nr); + // } + // var dp_out = BlueDataUtility.build_dp_inc(state, myLastValue == null ? null : myLastValue as DataPacket); + // myFireEvent(dp_out); + // } + } +} \ No newline at end of file diff --git a/src/DataStreamSuite/DataStream/Primitives/MongoDB/MongoDBStream.cs b/src/DataStreamSuite/DataStream/Primitives/MongoDB/MongoDBStream.cs index 00dcd567e..3c92f13de 100644 --- a/src/DataStreamSuite/DataStream/Primitives/MongoDB/MongoDBStream.cs +++ b/src/DataStreamSuite/DataStream/Primitives/MongoDB/MongoDBStream.cs @@ -7,122 +7,127 @@ using MongoDB.Driver; using System; using System.Collections.Generic; using System.Diagnostics; +using System.Threading.Tasks; +using System.Threading; namespace bts { - [DataStreamUserRespresentation("mongodb_sql")] - public class MongoDBSQLStream : ViewStream, IWorker { - private ViewStreamDatabase _vsd; - private readonly string _connection_string, _db_name, _collection_name; - private MongoClient _client; - // make this a sorted table - private BlueTable _table; + // [DataStreamUserRespresentation("mongodb_sql")] + // public class MongoDBSQLStream : ViewStream, IWorker { + // private ViewStreamDatabase _vsd; + // private readonly string _connection_string, _db_name, _collection_name; + // private MongoClient _client; + // // make this a sorted table + // private BlueTable _table; - // Access the database - private IMongoDatabase _database; - private IDictionary _id_map = new Dictionary(); - // mongodb://192.168.1.80:27017 + // // Access the database + // private IMongoDatabase _database; + // private IDictionary _id_map = new Dictionary(); + // // mongodb://192.168.1.80:27017 - public MongoDBSQLStream(string connection_string, string db_name, string collection_name) - : this(connection_string, db_name, collection_name, ViewStreamDatabase.instance) { + // public MongoDBSQLStream(string connection_string, string db_name, string collection_name) + // : this(connection_string, db_name, collection_name, ViewStreamDatabase.instance) { - } - public MongoDBSQLStream(string connection_string, string db_name, string collection_name, ViewStreamDatabase vsd) { - bts.Log.Gen.info($"MongoDBStream constructed connection_string: {connection_string} " + - $"db_name: {db_name}"); - _connection_string = connection_string; - _db_name = db_name; - _collection_name = collection_name; - _vsd = vsd; - _client = new MongoClient(_connection_string); - _database = _client.GetDatabase(_db_name); - } + // } + // public MongoDBSQLStream(string connection_string, string db_name, string collection_name, ViewStreamDatabase vsd) { + // bts.Log.Gen.info($"MongoDBStream constructed connection_string: {connection_string} " + + // $"db_name: {db_name}"); + // _connection_string = connection_string; + // _db_name = db_name; + // _collection_name = collection_name; + // _vsd = vsd; + // _client = new MongoClient(_connection_string); + // _database = _client.GetDatabase(_db_name); + // } - protected override void myOnFirstSubscriber() { - MasterWorker.getInstance(false).addWorker(this, TimeSpan.FromSeconds(10)); - } + // protected override void myOnFirstSubscriber() { + // MasterWorker.getInstance(false).addWorker(this, TimeSpan.FromSeconds(10)); + // } - protected override void myOnLastSubscriber() { - MasterWorker.getInstance(false).removeWorker(this); - } + // protected override void myOnLastSubscriber() { + // MasterWorker.getInstance(false).removeWorker(this); + // } - public void doWork() { - _read_mogodb(); - } + // public void doWork() { + // _read_mogodb(); + // } - private void _read_mogodb() { - var timer = Stopwatch.StartNew(); - // Access the collection - IMongoCollection collection = _database.GetCollection(name: _collection_name); + // private void _read_mogodb() { + // var timer = Stopwatch.StartNew(); + // // Access the collection + // IMongoCollection collection = _database.GetCollection(name: _collection_name); - // Fetch all documents from the collection - var documents = collection.Find(Builders.Filter.Empty).ToCursor(); - _table = _table == null ? null : new BlueTable(_table.schema); - // Iterate through the documents and print values - foreach (var document in documents.ToEnumerable()) { - bts.Log.Gen.info($"document: {document} json: {document.ToJson()}"); - if (_table == null) { - _init_table(document); - } - _add_row(document); - } - timer.Stop(); - Log.Gen.info($"MongoDBStream time to read {_collection_name} {timer.ElapsedMilliseconds}ms"); - timer.Restart(); - var dp = BlueDataUtility.build_dp_inc(_table, myLastValue == null ? null : myLastValue as DataPacket, true); - timer.Stop(); - Log.Gen.info($"MongoDBStream time to compare tables :{timer.ElapsedMilliseconds}ms"); - if (dp.addedRows.Count == 0 && dp.deletedRows.Count == 0) - return; - myFireEvent(dp); - } + // // Fetch all documents from the collection + // var documents = collection.Find(Builders.Filter.Empty).ToCursor(); + // _table = _table == null ? null : new BlueTable(_table.schema); + // // Iterate through the documents and print values + // foreach (var document in documents.ToEnumerable()) { + // bts.Log.Gen.info($"document: {document} json: {document.ToJson()}"); + // if (_table == null) { + // _init_table(document); + // } + // _add_row(document); + // } + // timer.Stop(); + // Log.Gen.info($"MongoDBStream time to read {_collection_name} {timer.ElapsedMilliseconds}ms"); + // timer.Restart(); + // var dp = BlueDataUtility.build_dp_inc(_table, myLastValue == null ? null : myLastValue as DataPacket, true); + // timer.Stop(); + // Log.Gen.info($"MongoDBStream time to compare tables :{timer.ElapsedMilliseconds}ms"); + // if (dp.addedRows.Count == 0 && dp.deletedRows.Count == 0) + // return; + // myFireEvent(dp); + // } - private void _init_table(BsonDocument doc_row) { - bts.Log.assert(_table == null); - List cis = new List(); - cis.Add((new ColumnInfo("id", 0, typeof(Int32)))); - foreach (var n in doc_row.Names) { - cis.Add(new ColumnInfo(n, cis.Count, typeof(string))); - } - IBlueTableSchema schema = new BlueTableSchema(cis.ToArray(), _collection_name); - _table = new BlueTable(schema); - } + // private void _init_table(BsonDocument doc_row) { + // bts.Log.assert(_table == null); + // List cis = new List(); + // cis.Add((new ColumnInfo("id", 0, typeof(Int32)))); + // foreach (var n in doc_row.Names) { + // cis.Add(new ColumnInfo(n, cis.Count, typeof(string))); + // } + // IBlueTableSchema schema = new BlueTableSchema(cis.ToArray(), _collection_name); + // _table = new BlueTable(schema); + // } - private void _add_row(BsonDocument doc) { - var key_val = doc["_id"]; - var key = key_val.ToString(); - int id; - if (!_id_map.TryGetValue(key, out id)) { - id = _id_map.Count; - _id_map.Add(key, id); - } - MutableBlueRow nr = new MutableBlueRow(_table.schema); - nr.setValue("id", id); - foreach (var n in doc.Names) { - var val = doc[n].ToString(); - nr.setValue(n, val); - } - _table.addRow(nr); - } - } + // private void _add_row(BsonDocument doc) { + // var key_val = doc["_id"]; + // var key = key_val.ToString(); + // int id; + // if (!_id_map.TryGetValue(key, out id)) { + // id = _id_map.Count; + // _id_map.Add(key, id); + // } + // MutableBlueRow nr = new MutableBlueRow(_table.schema); + // nr.setValue("id", id); + // foreach (var n in doc.Names) { + // var val = doc[n].ToString(); + // nr.setValue(n, val); + // } + // _table.addRow(nr); + // } + // } [DataStreamUserRespresentation("mongodb")] public class MongoDBStream : ViewStream, IWorker { private ViewStreamDatabase _vsd; private readonly string _connection_string, _db_name, _collection_name; + private readonly TimeSpan _poll_period; private MongoClient _client; private BlueTable _table; + private SyncQueue _table_queue = new SyncQueue(); + private BlockingQueue _work_queue = new BlockingQueue(); // Access the database private IMongoDatabase _database; private IDictionary _id_map = new Dictionary(); // mongodb://192.168.1.80:27017 - public MongoDBStream(string connection_string, string db_name, string collection_name) - : this(connection_string, db_name, collection_name, ViewStreamDatabase.instance) { + public MongoDBStream(string connection_string, string db_name, string collection_name, string poll_period) + : this(connection_string, db_name, collection_name, TimeBasedFilter.parse_duration(poll_period), ViewStreamDatabase.instance) { } - public MongoDBStream(string connection_string, string db_name, string collection_name, ViewStreamDatabase vsd) { + public MongoDBStream(string connection_string, string db_name, string collection_name, TimeSpan poll_period, ViewStreamDatabase vsd) { bts.Log.Gen.info($"MongoDBStream constructed connection_string: {connection_string} " + $"db_name: {db_name}"); _connection_string = connection_string; @@ -130,19 +135,30 @@ namespace bts { _collection_name = collection_name; _vsd = vsd; _client = new MongoClient(_connection_string); + _poll_period = poll_period; _database = _client.GetDatabase(_db_name); } protected override void myOnFirstSubscriber() { - MasterWorker.getInstance(false).addWorker(this, TimeSpan.FromSeconds(10)); + _vsd.addWorker(this); + //MasterWorker.getInstance(false).addWorker(this, _poll_period); } protected override void myOnLastSubscriber() { - MasterWorker.getInstance(false).removeWorker(this); + _vsd.removeWorker(this); + //MasterWorker.getInstance(false).removeWorker(this); } + private DateTime _last_poll_time = DateTime.MinValue; public void doWork() { - _read_mogodb(); + var now = DateTime.Now; + if (now - _last_poll_time > _poll_period) { + ThreadPool.QueueUserWorkItem(_ => _read_mogodb()); + _last_poll_time = DateTime.Now; + } + var dp = _table_queue.dequeue(0); + if (dp != null) + myFireEvent(dp); } private void _read_mogodb() { @@ -166,10 +182,11 @@ namespace bts { timer.Restart(); var dp = BlueDataUtility.build_dp_inc(_table, myLastValue == null ? null : myLastValue as DataPacket, true); timer.Stop(); - Log.Gen.info($"MongoDBStream time to compare tables: {timer.ElapsedMilliseconds}ms");; + Log.Gen.info($"MongoDBStream time to compare tables: {timer.ElapsedMilliseconds}ms"); ; if (dp.addedRows.Count == 0 && dp.deletedRows.Count == 0) return; - myFireEvent(dp); + _table_queue.enqueue(dp); + //myFireEvent(dp); } private void _init_table(BsonDocument doc_row) { @@ -208,46 +225,46 @@ namespace bts { } } - [DataStreamUserRespresentation("mongodb_flat")] - public class MongoDBFlatStream : ViewStream { - public MongoDBFlatStream(string connection_string, string db_name, string collection_name, string timestamp_col, string ttl_duration) - : - this(ViewStreamDatabase.instance, connection_string, db_name, collection_name, timestamp_col, TimeBasedFilter.parse_duration(ttl_duration)) { } + // [DataStreamUserRespresentation("mongodb_flat")] + // public class MongoDBFlatStream : ViewStream { + // public MongoDBFlatStream(string connection_string, string db_name, string collection_name, string timestamp_col, string ttl_duration) + // : + // this(ViewStreamDatabase.instance, connection_string, db_name, collection_name, timestamp_col, TimeBasedFilter.parse_duration(ttl_duration)) { } - public MongoDBFlatStream(ViewStreamDatabase vsd, string connection_string, string db_name, string collection_name, string timestamp_col, TimeSpan ttl_duration) { - ViewStream rs = new MongoDBStream(connection_string, db_name, collection_name, vsd); - rs = new KeyValueToRelationalStream(rs, "doc_id", "key", "val"); - rs = new DateStandardizationStream(rs, timestamp_col, DateConversion.ISO8601); - //rs = new TimeBasedFilterStream(vsd, rs, timestamp_col, ttl_duration); - mySetRealSource(rs); - } - } + // public MongoDBFlatStream(ViewStreamDatabase vsd, string connection_string, string db_name, string collection_name, string timestamp_col, TimeSpan ttl_duration) { + // ViewStream rs = new MongoDBStream(connection_string, db_name, collection_name, vsd); + // rs = new KeyValueToRelationalStream(rs, "doc_id", "key", "val"); + // rs = new DateStandardizationStream(rs, timestamp_col, DateConversion.ISO8601); + // //rs = new TimeBasedFilterStream(vsd, rs, timestamp_col, ttl_duration); + // mySetRealSource(rs); + // } + // } - [DataStreamUserRespresentation("newsreplay")] - public class NewsReplayStream : ViewStream { - public NewsReplayStream(string connection_string, string db_name, string collection_name, - int buffer_sz, string fire_period) : - this(ViewStreamDatabase.instance, connection_string, db_name, collection_name, buffer_sz, TimeBasedFilter.parse_duration(fire_period)) { } + // [DataStreamUserRespresentation("newsreplay")] + // public class NewsReplayStream : ViewStream { + // public NewsReplayStream(string connection_string, string db_name, string collection_name, + // int buffer_sz, string fire_period) : + // this(ViewStreamDatabase.instance, connection_string, db_name, collection_name, buffer_sz, TimeBasedFilter.parse_duration(fire_period)) { } - public NewsReplayStream(ViewStreamDatabase vsd, string connection_string, string db_name, string collection_name, - int buffer_sz, TimeSpan fire_period) { - ViewStream r; + // public NewsReplayStream(ViewStreamDatabase vsd, string connection_string, string db_name, string collection_name, + // int buffer_sz, TimeSpan fire_period) { + // ViewStream r; - r = new MongoDBStream(connection_string, db_name, collection_name, vsd); - r = new KeyValueToRelationalStream(r, - "doc_id", - "key", - "value"); - r = new DateStandardizationStream(r, - "created_at", - "ISO8601"); - r = new SnapshotReplayStream(vsd, r, "created_at", buffer_sz, fire_period); + // r = new MongoDBStream(connection_string, db_name, collection_name, vsd); + // r = new KeyValueToRelationalStream(r, + // "doc_id", + // "key", + // "value"); + // r = new DateStandardizationStream(r, + // "created_at", + // "ISO8601"); + // r = new SnapshotReplayStream(vsd, r, "created_at", buffer_sz, fire_period); - mySetRealSource(r); - } - } + // mySetRealSource(r); + // } + // } } diff --git a/src/DataStreamSuite/DataStream/Primitives/Project/New/NewProjectStream.cs b/src/DataStreamSuite/DataStream/Primitives/Project/New/NewProjectStream.cs index 299b05426..3b4e81539 100644 --- a/src/DataStreamSuite/DataStream/Primitives/Project/New/NewProjectStream.cs +++ b/src/DataStreamSuite/DataStream/Primitives/Project/New/NewProjectStream.cs @@ -6,6 +6,7 @@ namespace bts { using System; using System.Collections; using System.Collections.Generic; + using System.Linq; public class ProjectData { // schema from the base stream @@ -147,12 +148,23 @@ namespace bts { mapped_to_orig_map.Add(mapped_col, orig_col); orig_to_mapped.Add(orig_col, mapped_col); } else { - Log.Gen.error($"NewProjectStream unexpecetd token: {p_tok}"); + if (input_schema.columnNames.Contains(p_tok)) { + string orig_col = p_tok; + string mapped_col = orig_col; + orig_to_mapped.Add(orig_col, mapped_col); + } } } // make the new schema List new_cols = new List(); foreach (ColumnInfo ci in input_schema.columnInfo) { + if (ci.colName == "id") { + // if there's a hidden col, other columns will show by default, but if cols are being + // projected epxlicitely, than others wil be hidden + ColumnInfo nc = new ColumnInfo(ci.colName, new_cols.Count, ci.colType); + new_cols.Add(nc); + continue; + } if (removed_cols.Contains(ci.colName)) { continue; } else if (orig_to_mapped.ContainsKey(ci.colName)) { @@ -160,8 +172,12 @@ namespace bts { ColumnInfo nc = new ColumnInfo(mapped_name, new_cols.Count, ci.colType); new_cols.Add(nc); } else { - ColumnInfo nc = new ColumnInfo(ci.colName, new_cols.Count, ci.colType); - new_cols.Add(nc); + if (ci.colName == "id" || removed_cols.Count > 0) { + // if there's a hidden col, other columns will show by default, but if cols are being + // projected epxlicitely, than others wil be hidden + ColumnInfo nc = new ColumnInfo(ci.colName, new_cols.Count, ci.colType); + new_cols.Add(nc); + } } } IBlueTableSchema new_schema = new BlueTableSchema(input_schema.tableName, new_cols.ToArray()); diff --git a/src/DataStreamSuite/DataStream/Primitives/SideEffectStreams/SchemaGuesserStream.cs b/src/DataStreamSuite/DataStream/Primitives/SideEffectStreams/SchemaGuesserStream.cs index c92fcf72b..6f6ca4b26 100644 --- a/src/DataStreamSuite/DataStream/Primitives/SideEffectStreams/SchemaGuesserStream.cs +++ b/src/DataStreamSuite/DataStream/Primitives/SideEffectStreams/SchemaGuesserStream.cs @@ -24,7 +24,6 @@ namespace bts { var dp_out = BlueDataUtility.build_dp_inc(_rows, myLastValue as DataPacket); myFireEvent(dp_out); - } diff --git a/src/DataStreamSuite/DataStream/Primitives/Time/MillisecondStream.cs b/src/DataStreamSuite/DataStream/Primitives/Time/MillisecondStream.cs index 1dcb3d2e3..e03507ed7 100644 --- a/src/DataStreamSuite/DataStream/Primitives/Time/MillisecondStream.cs +++ b/src/DataStreamSuite/DataStream/Primitives/Time/MillisecondStream.cs @@ -1,29 +1,71 @@ using System; -namespace BCG -{ - public class MSecondStream : TimeUnitStream - { - public MSecondStream (int intervalInms, int size) - : base (DateTime.Now, new TimeSpan (0, 0, 0, 0, intervalInms), size, ViewStreamDatabase.instance) - {} +using BCG.Utilities.General; - protected override DateTime myRoundTime (DateTime dt) {return dt;} +using bts; + +namespace BCG { + [DataStreamUserRespresentation("milliseconds")] + public class MillisecondStream : ViewStream, IWorker { + private DateTime _last_fire_time = DateTime.MinValue; + private readonly TimeSpan _period; + private readonly int _size; + private readonly ViewStreamDatabase _vsd; + private IBlueTableSchema _schema; + private bts.CircularBufferTable _table; + + public MillisecondStream(int interval_msecs, int size) + : this(ViewStreamDatabase.instance, interval_msecs, size) { + } + + public MillisecondStream(ViewStreamDatabase vsd, int interval_msecs, int size) { + _vsd = vsd; + _period = TimeSpan.FromMilliseconds(interval_msecs); + _size = size; + _schema = BlueDataUtility.form_schema("Milliseconds", + Tuple.Create("id", TypeCode.Int32), + Tuple.Create("time", TypeCode.DateTime), + Tuple.Create("display_time", TypeCode.String)); + _table = new CircularBufferTable(_schema, _size); + } + + protected override void myOnFirstSubscriber() { + _vsd.addWorker(this); + } + + protected override void myOnLastSubscriber() { + _vsd.removeWorker(this); + } + + private int _id = 0; + public void doWork() { + if (DateTime.Now - _last_fire_time >= _period) { + _last_fire_time = DateTime.Now; + IBlueRow nr = new BlueRow(_schema, _id++, _last_fire_time, + _last_fire_time.ToString("yyyy-MM-dd HH:mm:ss.fff")); + _table.add_row(nr); + var dp = BlueDataUtility.build_dp_inc(_table, myLastValue as DataPacket); + myFireEvent(dp); + } + } + } + public class MSecondStream : TimeUnitStream { + public MSecondStream(int intervalInms, int size) + : base(DateTime.Now, new TimeSpan(0, 0, 0, 0, intervalInms), size, ViewStreamDatabase.instance) { } + + protected override DateTime myRoundTime(DateTime dt) { return dt; } } - public class DisplayableMillisecondStream : ViewStream, IStreamMapper - { - private IBlueTableSchema mySchema = new BlueTableSchema ("ms", - new ColumnInfo ("id", 0, typeof(int)), - new ColumnInfo ("time", 1, typeof(string))); - public DisplayableMillisecondStream (int intervalInMs, int sz) - { - mySetRealSource (new MapStream (new MSecondStream (intervalInMs, sz), this)); + public class DisplayableMillisecondStream : ViewStream, IStreamMapper { + private IBlueTableSchema mySchema = new BlueTableSchema("ms", + new ColumnInfo("id", 0, typeof(int)), + new ColumnInfo("time", 1, typeof(string))); + public DisplayableMillisecondStream(int intervalInMs, int sz) { + mySetRealSource(new MapStream(new MSecondStream(intervalInMs, sz), this)); } #region IStreamMapper Members - public IBlueTableSchema getOutputSchema(IBlueTableSchema inputSchema) - { + public IBlueTableSchema getOutputSchema(IBlueTableSchema inputSchema) { return mySchema; } @@ -31,15 +73,15 @@ namespace BCG #region IDynamicStreamMapper Members - public IBlueRow map (IBlueRow row) - { - return new BlueRow (mySchema, row["id"], myToString ((DateTime)row["time"])); + public IBlueRow map(IBlueRow row) { + DateTime time = row.get_datetime("time"); + var time_txt = time.ToString("yyyy-MM-dd HH:mm:ss.fff"); + return new BlueRow(mySchema, row["id"], time_txt); } #endregion - private string myToString (DateTime dt) - { + private string myToString(DateTime dt) { string sep = ":"; return dt.Hour + sep + dt.Minute + sep + dt.Second + sep + dt.Millisecond; } diff --git a/src/DataStreamSuite/DataStreamCore/BlueData/CircularBufferTable.cs b/src/DataStreamSuite/DataStreamCore/BlueData/CircularBufferTable.cs index ef67a2264..c1322be68 100644 --- a/src/DataStreamSuite/DataStreamCore/BlueData/CircularBufferTable.cs +++ b/src/DataStreamSuite/DataStreamCore/BlueData/CircularBufferTable.cs @@ -16,12 +16,6 @@ namespace bts { _buffer_sz = buffer_sz; } - // public OrderedBlueTable(List rows, int buffer_sz) { - // _buffer_sz = buffer_sz; - // foreach (IBlueRow r in rows) - // add_row(r); - // } - // returns the row that might need to be deleted to keep // the circular buffer intact public IBlueRow add_row(IBlueRow row) { diff --git a/src/DataStreamSuite/DataStreamCore/Messaging/Publish/PubTableBroker.cs b/src/DataStreamSuite/DataStreamCore/Messaging/Publish/PubTableBroker.cs index e7d20c6ca..3119202ba 100644 --- a/src/DataStreamSuite/DataStreamCore/Messaging/Publish/PubTableBroker.cs +++ b/src/DataStreamSuite/DataStreamCore/Messaging/Publish/PubTableBroker.cs @@ -51,13 +51,13 @@ namespace BCG { public virtual void make_batch_changes(IBlueRowCollection new_rows, IBlueRowCollection del_rows, IBlueRowCollection added_rows) { - string log_msg = $"PubTableBroker.make_batch_changes table: {new_rows.schema.tableName} del: {del_rows.Count} added: {added_rows.Count}"; - foreach (IBlueRow r in del_rows) - log_msg += $"id: {r["id"]} "; - log_msg += "addedRows: "; - foreach (IBlueRow r in added_rows) - log_msg += $"id: {r["id"]}"; - bts.Log.Gen.info(log_msg); + // string log_msg = $"PubTableBroker.make_batch_changes table: {new_rows.schema.tableName} del: {del_rows.Count} added: {added_rows.Count}"; + // foreach (IBlueRow r in del_rows) + // log_msg += $"id: {r["id"]} "; + // log_msg += "addedRows: "; + // foreach (IBlueRow r in added_rows) + // log_msg += $"id: {r["id"]}"; + // bts.Log.Gen.info(log_msg); SinglePubTableBroker table_publisher = null; var name_key = new_rows.schema.tableName.ToLower(); if (!_publisher_map.TryGetValue(name_key, out table_publisher)) diff --git a/src/DataStreamSuite/DataStreamCore/Messaging/Subscription/TableAccumulator2.cs b/src/DataStreamSuite/DataStreamCore/Messaging/Subscription/TableAccumulator2.cs index 0f44e6c00..d27353e79 100644 --- a/src/DataStreamSuite/DataStreamCore/Messaging/Subscription/TableAccumulator2.cs +++ b/src/DataStreamSuite/DataStreamCore/Messaging/Subscription/TableAccumulator2.cs @@ -5,18 +5,21 @@ using System.Linq; using bts; -namespace BCG { +namespace BCG +{ // This class is responsible for mantaining the state fo a table. It gets the // bytes from the pubsubserver via the handle_updates call (called by VSD), deserializes // updates the state of the table, and fires the TableUpdateDelegate. - public class TableAccumulator2 : ITableAccumulator { + public class TableAccumulator2 : ITableAccumulator + { private readonly string _tag; private readonly ISubscriberCore _subscriber_core; IStreamMsgDeserilizer _deser = new StreamIODeserializationController(); private BlueTable _table; private TableUpdateDelegate _on_update_delegate; - public TableAccumulator2(string tag, ISubscriberCore sub_core) { + public TableAccumulator2(string tag, ISubscriberCore sub_core) + { _tag = tag; _subscriber_core = sub_core; } @@ -25,10 +28,13 @@ namespace BCG { //public bool is_active() { return _on_update_delegate != null; } - public event TableUpdateDelegate on_update { - add { + public event TableUpdateDelegate on_update + { + add + { Log.Gen.info("TableAccumulator2.on_update.add {_tag} subscribed"); - if (_on_update_delegate == null) { + if (_on_update_delegate == null) + { //ie first subscription Log.Gen.info("TableAccumulator2.on_update {_tag} subscribed for the first time"); _subscriber_core.subscribe(_tag); @@ -38,14 +44,17 @@ namespace BCG { if (_table != null) value(_table, _table, new BlueTable(_table.schema)); } - remove { + remove + { Log.Gen.info("TableAccumulator2.on_update.remove {_tag} unsubscribed"); - if (_on_update_delegate != null) { + if (_on_update_delegate != null) + { _on_update_delegate = Delegate.Remove(_on_update_delegate, value) as TableUpdateDelegate; int n_subs = _on_update_delegate == null ? 0 : _on_update_delegate.GetInvocationList().Length; Log.Gen.info("TableAccumulator2.on_update.remove {_tag} unsubscribed n_subs: {n_subs}"); - if (_on_update_delegate == null) { + if (_on_update_delegate == null) + { _subscriber_core.unsubscribe(_tag); // TODO //_table = null; @@ -54,17 +63,20 @@ namespace BCG { } } - - public void handle_updates(IEnumerable msgs) { + private int _update_no = 0; + public void handle_updates(IEnumerable msgs) + { if (msgs == null || msgs.Count() == 0) return; - Log.Gen.info($"TableAccumulator2.handle_updates msgs: {msgs.Count()} msg_0: {msgs.ElementAt(0).Length}"); + Log.Gen.info($"TableAccumulator2.handle_updates _update_no: {_update_no++} msgs: {msgs.Count()} msg_0: {msgs.ElementAt(0).Length}"); IBlueRowCollection table_0 = _table == null ? null : new BlueTable(_table); - foreach (var msg in msgs) { + foreach (var msg in msgs) + { bts.StreamIOMessage str_msg = _deser.deserialize(msg); - var state_txt = _table == null ? "NULL" : _table.Count.ToString(); + var state_txt = _table == null ? "NULL" : _table.Count.ToString();// BlueDataUtility.id_string(_table); Log.Gen.info($"TableAccumulator2.handle_update tag: {_tag} sz: {msg.Length} str_msg: {str_msg} _state: {state_txt}"); - switch (str_msg.op) { + switch (str_msg.op) + { case bts.StreamIOMessage.StreamOp.CREATE: _table = new BlueTable(str_msg.create_message.rows); break; @@ -77,11 +89,13 @@ namespace BCG { // this could be made faster if we just do this on the CREATE message, and pass-through // what we get on the MULTIPLE_REMOVE_ADD IBlueRowCollection d_rows, a_rows; - BlueDataUtility.compute_differences_id_based(_table, table_0, out d_rows, out a_rows); + //BlueDataUtility.compute_differences_id_based(_table, table_0, out d_rows, out a_rows); + BlueDataUtility.compute_differences_fast(_table, table_0, out d_rows, out a_rows); _on_update_delegate(_table, a_rows, d_rows); } - public void update(Stream[] streams) { + public void update(Stream[] streams) + { } #endregion diff --git a/src/DataStreamSuite/DataStreamCore/Messaging/v2/Publish/Serialization/StreamSerializationUtils.cs b/src/DataStreamSuite/DataStreamCore/Messaging/v2/Publish/Serialization/StreamSerializationUtils.cs index 7e97f13e3..8d4727f03 100644 --- a/src/DataStreamSuite/DataStreamCore/Messaging/v2/Publish/Serialization/StreamSerializationUtils.cs +++ b/src/DataStreamSuite/DataStreamCore/Messaging/v2/Publish/Serialization/StreamSerializationUtils.cs @@ -95,8 +95,8 @@ namespace bts { } public static IBlueTableSchema deserialize_schema(ref BinaryReader br) { - var hex_txt = to_hex(br.BaseStream); - bts.Log.Gen.info($"StreamSerializationUtils.deserialize_schema bytes: {hex_txt}"); + // var hex_txt = to_hex(br.BaseStream); + // bts.Log.Gen.info($"StreamSerializationUtils.deserialize_schema bytes: {hex_txt}"); string table_name = br.read_string_cpp(); int n_cols = br.ReadInt32(); // doing a br.Read was only advancing the data 1 byte!! List cis = new List(); @@ -137,8 +137,8 @@ namespace bts { public static ColumnInfo deserialize_column_info(ref BinaryReader br) { //col_no, name, type> - var hex_txt = to_hex(br.BaseStream); - bts.Log.Gen.info($"StreamSerializationUtils.deserialize_column_info bytes: {hex_txt}"); + // var hex_txt = to_hex(br.BaseStream); + // bts.Log.Gen.info($"StreamSerializationUtils.deserialize_column_info bytes: {hex_txt}"); int col_no = br.ReadInt32(); string col_name = br.read_string_cpp(); int tc_int = br.ReadInt32(); @@ -212,5 +212,18 @@ namespace bts { return rv; } + public static string to_hex(byte[] byte_arr, int start_pos, int end_pos) { + var len = end_pos - start_pos; + StringBuilder hex_builder = new StringBuilder(len * 2); + int i = 0; + + foreach (byte b in byte_arr) { + if (i >= start_pos && i < end_pos) + hex_builder.Append($"{b:X2} "); + i++; + } + return hex_builder.ToString().Trim(); + } + } } \ No newline at end of file diff --git a/src/DataStreamSuite/DataStreamCore/Messaging/v2/Receive/PubSubServer/PubsubServerStreamTagHandler.cs b/src/DataStreamSuite/DataStreamCore/Messaging/v2/Receive/PubSubServer/PubsubServerStreamTagHandler.cs index 825b7506e..16873194d 100644 --- a/src/DataStreamSuite/DataStreamCore/Messaging/v2/Receive/PubSubServer/PubsubServerStreamTagHandler.cs +++ b/src/DataStreamSuite/DataStreamCore/Messaging/v2/Receive/PubSubServer/PubsubServerStreamTagHandler.cs @@ -7,12 +7,23 @@ namespace bts { // for non stream tags public class PubsubServerGenericDataHandler : IPubSubServerTagHandler { - byte[] _state = null; - public void update(string tag, byte[] msg) { - _state = msg; + //byte[] _state = null; + private MemoryStream _str = new MemoryStream(); + private BinaryWriter _bw; + public PubsubServerGenericDataHandler() { + _bw = new BinaryWriter(_str); } + public void update(string tag, byte[] msg) { + _str.Position = 0; + _bw.Write(msg); + Log.Gen.info($"PubsubServerGenericDataHandler.update tag: {tag} msg_len: {msg.Length}"); + } + + public byte[] get_content(string tag) { - return _state; + var rv = _str.ToArray(); + Log.Gen.info($"PubsubServerGenericDataHandler.get_content tag: {tag} rv: {rv.Length}"); + return rv; } public string[] supportedTagTypes { get; } public void register(InternalPublishDelegate callback) { } @@ -33,7 +44,7 @@ namespace bts { public void update(string tag, byte[] msg) { StreamIOMessage str_msg = _deser.deserialize(msg); var state_txt = _state == null ? "NULL" : _state.Count.ToString(); - Log.Gen.info($"PubsubServerSingleStreamTagHandler.update (pre.1) tag: {tag} sz: {msg.Length} str_msg: {str_msg} _state: {state_txt}"); + Log.Gen.info($"PubsubServerSingleStreamTagHandler.update (pre.1) tag: {tag} sz: {msg.Length} _state: {state_txt}"); switch (str_msg.op) { case StreamIOMessage.StreamOp.CREATE: //Log.assert(_state == null); @@ -45,7 +56,7 @@ namespace bts { _state.addRows(str_msg.multiple_remove_add_message.added_rows); break; } - Log.Gen.info($"PubsubServerSingleStreamTagHandler.update (post) tag: {tag} sz: {msg.Length} str_msg: {str_msg} state: {_state.Count}"); + Log.Gen.info($"PubsubServerSingleStreamTagHandler.update (post) tag: {tag} sz: {msg.Length} state: {_state.Count}"); } public byte[] get_content(string tag) { @@ -60,7 +71,7 @@ namespace bts { }; var rv = get_content_(); var rv_txt = rv == null ? "null" : rv.Length.ToString(); - Log.Gen.info($"PubsubServerStreamTagHandler.get_content rv: {rv_txt}"); + Log.Gen.info($"PubsubServerSingleStreamTagHandler.get_content rv: {rv_txt}"); return rv; } public string[] supportedTagTypes { diff --git a/src/DataStreamSuite/DataStreamExpressions/DataStreamExpressionTokens.lex b/src/DataStreamSuite/DataStreamExpressions/DataStreamExpressionTokens.lex index 8aae15ea0..a8a360f3f 100644 --- a/src/DataStreamSuite/DataStreamExpressions/DataStreamExpressionTokens.lex +++ b/src/DataStreamSuite/DataStreamExpressions/DataStreamExpressionTokens.lex @@ -9,7 +9,15 @@ Letter [a-zA-Z] BooleanConstant 'true'|'false' CSStringConstant \"([^\"\\]*|\\.)*\" -DateTimeConstant ([1-9]|'10'|'11'|'12')\/([1-9]|([1-2][0-9])|'30'|'31')\/[0-9][0-9][0-9]* +YearInt [0-9]{4} +MonthInt [0-9]{1,2} +DayInt [0-9]{1,2} +/** + * DateTimeConstant supports American (mm/dd/yyyy) and European (yyyy/mm/dd) + * formats. Month and day can be 1 or 2 digits. It does not validate that the + * numbers represent an actual date. + */ +DateTimeConstant ({MonthInt}\/{DayInt}\/{YearInt}|{YearInt}\/{MonthInt}\/{DayInt}) IntegerConstant -?[0-9]+ NullConstant 'null' RealConstant -?[0-9]+\.[0-9]+ diff --git a/src/DataStreamSuite/DataStreamPublisher/Configurations/MarketDataPublisher.json b/src/DataStreamSuite/DataStreamPublisher/Configurations/MarketDataPublisher.json index 1a8449f08..2f7a35544 100644 --- a/src/DataStreamSuite/DataStreamPublisher/Configurations/MarketDataPublisher.json +++ b/src/DataStreamSuite/DataStreamPublisher/Configurations/MarketDataPublisher.json @@ -1,6 +1,6 @@ { "user": "bts", - "sparkd": "http://localhost:8000/config", + "sparkd": "http://192.168.1.80:8000/config", "pubsub": { "milliseconds_between_sub_info_updates": 1000, "milliseconds_between_time_slice_updates": 5000, @@ -18,14 +18,14 @@ "publisher_routes": [ { "name": "default", - "server_address": "bluto://localhost:12345", + "server_address": "bts-cloud://127.0.0.1:12345", "tag": ".*" } ], "subscriber_routes": [ { "name": "default", - "server_address": "bluto://localhost:12345", + "server_address": "bts-cloud://127.0.0.1:12345", "tag": ".*" } ], @@ -89,8 +89,8 @@ "name": "test_data", "streams": [ { - "name": "seconds_1_10", - "expression": "second(1,10)", + "name": "milliseconds_1000_100", + "expression": "milliseconds(1000,100)", "is_on_websocket": true }, { @@ -105,5 +105,25 @@ } ] } + // { + // "name": "news_data", + // "streams": [ + // { + // "name": "benzinga_news", + // "expression": "benzingaNews(\"mongodb://localhost:27017\",\"local\",\"news_headlines\", \"30s\", \"5d\")", + // "is_on_websocket": true + // }, + // { + // "name": "benzinga_news_symbols", + // "expression": "benzingaNewsSymbols(benzinga_news)", + // "is_on_websocket": true + // }, + // { + // "name": "benzinga_news_symbol_state", + // "expression": "benzingaNewsSymbolState(benzinga_news)", + // "is_on_websocket": true + // } + // ] + // } ] -} +} \ No newline at end of file diff --git a/src/DataStreamSuite/DataStreamPublisher/Configurations/TestDataPublisher.json b/src/DataStreamSuite/DataStreamPublisher/Configurations/TestDataPublisher.json index 04ebfef32..736a893e0 100644 --- a/src/DataStreamSuite/DataStreamPublisher/Configurations/TestDataPublisher.json +++ b/src/DataStreamSuite/DataStreamPublisher/Configurations/TestDataPublisher.json @@ -6,7 +6,22 @@ "streams": [ { "name": "seconds_1_10", - "expression": "second(1,10)", + "expression": "milliseconds(1000,10)", + "is_on_websocket": true + }, + { + "name": "benzinga_news", + "expression": "benzingaNews(\"mongodb://localhost:27017\",\"local\",\"news_headlines\", \"30s\", \"5d\")", + "is_on_websocket": true + }, + { + "name": "benzinga_news_symbols", + "expression": "benzingaNewsSymbols(benzinga_news)", + "is_on_websocket": true + }, + { + "name": "benzinga_news_symbol_state", + "expression": "benzingaNewsSymbolState(benzinga_news)", "is_on_websocket": true }, { @@ -22,4 +37,4 @@ ] } ] -} +} \ No newline at end of file diff --git a/src/DataStreamSuite/DataStreamPublisher/DataStreamPublisherConfig.cs b/src/DataStreamSuite/DataStreamPublisher/DataStreamPublisherConfig.cs index 1367d0ab6..5e6dba0e3 100644 --- a/src/DataStreamSuite/DataStreamPublisher/DataStreamPublisherConfig.cs +++ b/src/DataStreamSuite/DataStreamPublisher/DataStreamPublisherConfig.cs @@ -10,7 +10,8 @@ using System.IO; using System.Text.Json; using System.Text.Json.Serialization; -public class DataStreamPublisherConfig { +public class DataStreamPublisherConfig +{ /// /// The login user for sparkd /// @@ -38,9 +39,17 @@ public class DataStreamPublisherConfig { [JsonPropertyName("publishers")] public List? Publishers { get; set; } - [JsonPropertyName("simple_echo_client")] - [Option("simple-echo-client", HelpText = "Run a simple echo client (won't publish tables or connect to sparkd)")] - public bool? SimpleEchoClient { get; set; } + [JsonPropertyName("mongodb_url")] + public string MONGO_DB_URL { get; set; } + + [JsonPropertyName("mongodb_db_name")] + public string MONGO_DB_NAME { get; set; } + + [JsonPropertyName("mongodb_db_collection")] + public string MONGO_DB_COLLECTION { get; set; } + + [JsonPropertyName("benzinga_news_ttl")] + public string BENZINGA_NEWS_TTL { get; set; } [JsonPropertyName("pubsub")] public PubSubConfig? PubSub { get; set; } @@ -53,18 +62,18 @@ public class DataStreamPublisherConfig { public string? ConfigFile { get; set; } public static DataStreamPublisherConfig Default() => - new() { - SimpleEchoClient = false, + new() + { PubSub = PubSubConfig.Default(), }; - public void MergeWith(DataStreamPublisherConfig other) { + public void MergeWith(DataStreamPublisherConfig other) + { User ??= other.User; Password ??= other.Password; Sparkd ??= other.Sparkd; Publishers ??= other.Publishers; PubSub ??= other.PubSub; - SimpleEchoClient ??= other.SimpleEchoClient; ConfigFile ??= other.ConfigFile; } @@ -75,8 +84,10 @@ public class DataStreamPublisherConfig { /// /// JsonSerializer.Deserialize returns null /// - public void MergeWithConfigFile() { - if (ConfigFile is null) { + public void MergeWithConfigFile() + { + if (ConfigFile is null) + { return; } var cfgString = File.ReadAllText(ConfigFile); diff --git a/src/DataStreamSuite/DataStreamPublisher/Program.cs b/src/DataStreamSuite/DataStreamPublisher/Program.cs index 930bc1ec2..82f117b5c 100644 --- a/src/DataStreamSuite/DataStreamPublisher/Program.cs +++ b/src/DataStreamSuite/DataStreamPublisher/Program.cs @@ -23,8 +23,10 @@ using System.Threading.Tasks; await Parser.Default.ParseArguments(args) .MapResult(RunAsync, errs => Task.FromResult(1)); -async Task RunAsync(DataStreamPublisherConfig cfg) { - try { +async Task RunAsync(DataStreamPublisherConfig cfg) +{ + try + { cfg.MergeWithConfigFile(); cfg.MergeWith(DataStreamPublisherConfig.Default()); PubSubConfig.SetGlobalConfig(Log.notnull(cfg.PubSub)); @@ -32,12 +34,10 @@ async Task RunAsync(DataStreamPublisherConfig cfg) { Log.Gen.info("Starting DataStreamPublisher"); var service_ctx = ServiceContext.create(cfg.Sparkd); await service_ctx.login(cfg.User ?? "bts", cfg.Password ?? string.Empty); - if (cfg.SimpleEchoClient ?? false) { - start_echo_client(); - } else { - _publish_streams(cfg.Publishers ?? new(0)); - } - } catch (Exception ex) { + _publish_streams(cfg.Publishers ?? new(0)); + } + catch (Exception ex) + { // Write the error to console first, in case the logging system is compromised. var error_msg = $"DataStreamPublisher threw exception:\n{ex}"; Console.Error.WriteLine(error_msg); @@ -48,41 +48,39 @@ async Task RunAsync(DataStreamPublisherConfig cfg) { return 0; } -static ViewStream? build_stream(string? stream_expression) { - if (stream_expression is null) { +static ViewStream? build_stream(string? stream_expression) +{ + // Console.WriteLine("Hit key to continue"); + // Console.ReadLine(); + if (stream_expression is null) + { return null; } - try { + try + { bts.Log.Gen.info($"build_stream stream_expression: {stream_expression}"); var exp = DataStreamExpressionsInterpreter.Evaluate(stream_expression); var rv = exp.getView(new Dictionary(0)); return rv; - } catch (Exception ex) { + } + catch (Exception ex) + { bts.Log.assert(false, $"Could not build stream: {stream_expression} ex: {ex}"); return null; } } -static void start_echo_client() { - Console.WriteLine("Starting DSPublisher in TCP client echo mode, Hit key to continue"); - Console.ReadLine(); - SimpleTCPClient client = new SimpleTCPClient("127.0.0.1", 12345, 1000, 1000); - client.start(); - while (true) { - System.Threading.Thread.Sleep(1000); - } - // await SimpleTCPClient.start("127.0.0.1", 12345); - // Task.Delay(1000000000).Wait(); -} - -void _publish_streams(IEnumerable publishers) { +void _publish_streams(IEnumerable publishers) +{ PubTableBroker pb_broker = new PubTableBroker(); RemoteQueryManager csm = new RemoteQueryManager(); var csvPublishers = new List(); - foreach (var publisher in publishers) { - if (Directory.Exists(publisher.CsvDir)) { + foreach (var publisher in publishers) + { + if (Directory.Exists(publisher.CsvDir)) + { csvPublishers.Add(new(publisher.CsvDir, pb_broker)); } } @@ -91,7 +89,8 @@ void _publish_streams(IEnumerable publishers) { .SelectMany(p => p.Streams.empty_if_null().Select(createViewPublisher)) .ToList(); - while (true) { + while (true) + { System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1)); ViewStreamDatabase.instance.doWork(); csm.doWork(); @@ -99,16 +98,19 @@ void _publish_streams(IEnumerable publishers) { ManagedSubscriber.instance.doWork(); } - ViewPublisher? createViewPublisher(PublishedStream ps) { + ViewPublisher? createViewPublisher(PublishedStream ps) + { Log.Gen.info( $"Instantiating ViewPublisher for: {JsonSerializer.Serialize(ps)}"); - if (string.IsNullOrEmpty(ps.Name)) { + if (string.IsNullOrEmpty(ps.Name)) + { Log.Gen.warn( $"Failed to instantiate ViewPublisher. Null/empty 'name': {JsonSerializer.Serialize(ps)}"); return null; } var vs = build_stream(ps.Expression); - if (vs is null) { + if (vs is null) + { Log.Gen.warn( $"Failed to instantiate ViewPublisher. Invalid 'expression': {JsonSerializer.Serialize(ps)}"); return null; @@ -119,31 +121,39 @@ void _publish_streams(IEnumerable publishers) { } } -void on_change(object obj) { +void on_change(object obj) +{ bts.Log.Gen.info($"DSPublisher on_change dp: {obj}"); } -public class CSVPublisher : IWorker { +public class CSVPublisher : IWorker +{ private IDictionary _pubs = new Dictionary(); private readonly string _csv_directory; private PubTableBroker _pub_table_broker; - public CSVPublisher(string csv_directory, PubTableBroker pub_table_broker) { + public CSVPublisher(string csv_directory, PubTableBroker pub_table_broker) + { _csv_directory = csv_directory; _pub_table_broker = pub_table_broker; MasterWorker.getInstance(false).addWorker(this, TimeSpan.FromSeconds(1)); } - public void doWork() { + public void doWork() + { var file_names = Directory.GetFiles(_csv_directory); - foreach (var fn in file_names) { - if (!_pubs.ContainsKey(fn)) { + foreach (var fn in file_names) + { + if (!_pubs.ContainsKey(fn)) + { _handle_new_file(fn); } } } - private void _handle_new_file(string file_name) { - if (file_name.EndsWith(".csv")) { + private void _handle_new_file(string file_name) + { + if (file_name.EndsWith(".csv")) + { ViewStream vs = new CSVReaderStream(file_name); vs = new SchemaGuesserStream(vs); var toks = file_name.Split('\\'); diff --git a/src/DataStreamSuite/DataStreamQueryAnalyzer/Configurations/DataStreamQueryAnalyzer.json b/src/DataStreamSuite/DataStreamQueryAnalyzer/Configurations/DataStreamQueryAnalyzer.json index 42ea6ce19..7154e2423 100644 --- a/src/DataStreamSuite/DataStreamQueryAnalyzer/Configurations/DataStreamQueryAnalyzer.json +++ b/src/DataStreamSuite/DataStreamQueryAnalyzer/Configurations/DataStreamQueryAnalyzer.json @@ -1,61 +1,60 @@ -{ - "user": "bts", - "pubsub": { - "milliseconds_between_sub_info_updates": 1000, - "milliseconds_between_time_slice_updates": 5000, - "milliseconds_between_no_buffer_space_retries": 100, - "retries_on_no_buffer_space": 1, - "do_it_all_seconds_between_logs": 0, - "heartbeat_interval": 15000, - "missing_heartbeats_before_gc": 50, - "use_managed_sockets": true, - "state_update_period": 5000, - "statistics_update_period": 5000, - "disposed_connection_check_period": 1000, - "message_processing_warning_threshold": 1000, - "server_port": 12345, - "publisher_routes": [ - { - "name": "default", - "server_address": "bluto://localhost:12345", - "tag": ".*" - } - ], - "subscriber_routes": [ - { - "name": "default", - "server_address": "bluto://localhost:12345", - "tag": ".*" - } - ], - "max_packet_size": 500000000, - "blue_comm_must_die": true, - "crushable_tags": [], - "tag_type_to_assembly_map": [ - { - "handler_class": "BCG.PubSubServerTagHandler", - "assembly": "DataStreamCore.dll" - } - ], - "server_queue": "PubSubQueue", - "port_range": { - "first": 30400, - "last": 31700 - }, - "bind_to_random_port": false, - "debug_tags": "^NOTAGS$", - "latency_report_threshold_ms": 1500, - "use_substations": false, - "use_dynamic_clients": false, - "is_substation": false, - "internally_publish_sub_info": true, - "use_managed_clients_in_native_code": false, - "compressed_tags": "^NOTAGS$", - "tags_to_report_compression_ratio": "^NOTAGS$", - "disable_msmq": false, - "use_prepublished_server_state": false, - "ip_translation": null, - "gc_activation_threshold": 0, - "wait_period_after_gc": 1000 - } +"user": "bts", +"pubsub": { + "milliseconds_between_sub_info_updates": 1000, + "milliseconds_between_time_slice_updates": 5000, + "milliseconds_between_no_buffer_space_retries": 100, + "retries_on_no_buffer_space": 1, + "do_it_all_seconds_between_logs": 0, + "heartbeat_interval": 15000, + "missing_heartbeats_before_gc": 50, + "use_managed_sockets": true, + "state_update_period": 5000, + "statistics_update_period": 5000, + "disposed_connection_check_period": 1000, + "message_processing_warning_threshold": 1000, + "server_port": 12345, + "publisher_routes": [ + { + "name": "default", + "server_address": "bts-cloud://192.168.1.80:12345", + "tag": ".*" + } + ], + "subscriber_routes": [ + { + "name": "default", + "server_address": "bts-cloud://192.168.1.80:12345", + "tag": ".*" + } + ], + "max_packet_size": 500000000, + "blue_comm_must_die": true, + "crushable_tags": [], + "tag_type_to_assembly_map": [ + { + "handler_class": "BCG.PubSubServerTagHandler", + "assembly": "DataStreamCore.dll" + } + ], + "server_queue": "PubSubQueue", + "port_range": { + "first": 30400, + "last": 31700 + }, + "bind_to_random_port": false, + "debug_tags": "^NOTAGS$", + "latency_report_threshold_ms": 1500, + "use_substations": false, + "use_dynamic_clients": false, + "is_substation": false, + "internally_publish_sub_info": true, + "use_managed_clients_in_native_code": false, + "compressed_tags": "^NOTAGS$", + "tags_to_report_compression_ratio": "^NOTAGS$", + "disable_msmq": false, + "use_prepublished_server_state": false, + "ip_translation": null, + "gc_activation_threshold": 0, + "wait_period_after_gc": 1000 } +} \ No newline at end of file diff --git a/src/DataStreamSuite/DataStreamQueryAnalyzer/MainForm.cs b/src/DataStreamSuite/DataStreamQueryAnalyzer/MainForm.cs index a279a3fd4..6c1f58e3c 100644 --- a/src/DataStreamSuite/DataStreamQueryAnalyzer/MainForm.cs +++ b/src/DataStreamSuite/DataStreamQueryAnalyzer/MainForm.cs @@ -25,8 +25,10 @@ using System.Threading.Tasks; -namespace BCG { - public partial class MainForm : System.Windows.Forms.Form { +namespace BCG +{ + public partial class MainForm : System.Windows.Forms.Form + { // static async Task _run() { // var login = "bts"; // var passwd = String.Empty; @@ -48,7 +50,8 @@ namespace BCG { private string myKQ; private TextWriter? myConsoleOutput; - public MainForm() { + public MainForm() + { //Task.Run(async () => await _run()); InitializeComponent(); // myKQ = ConfigurationRequester.getApplicationQualifier(); @@ -61,25 +64,40 @@ namespace BCG { this.Load += new EventHandler(myLoad); this.Closing += new CancelEventHandler(myClosing); - myQueryTextBox.TextChanged += (o, e) => { + myQueryTextBox.TextChanged += (o, e) => + { myQueryTextBox.ForeColor = Color.White; }; } - public string query_text { + public string query_text + { get { return myQueryTextBox.Text; } set { myQueryTextBox.Text = value; } } - private ViewStream myGetAllTagsStream() { + private ViewStream myGetAllTagsStream() + { // TODO: Port PublishedTagsStream from edge (then we can uncomment impl below) //ViewStream vs = new PubSubServerStateStream(); ViewStream vs = new PubSubServerStateStream(); return new FilterStream(vs, "tag~='DS_'"); - //return new LiteralStream("tag/String", "DS_Comedians;DS_Baldies"); + //return new LiteralStream("tag/String", "DS_table1;DS_table2"); } - private void mySetText() { - this.Text = "Data Stream Query Analyzer | Site: " + mySite + (string.IsNullOrEmpty(myKQ) ? string.Empty : " | Key Qualifier: " + myKQ); + private void mySetText() + { + ViewStream routes = new PubsubRoutesStream(); + routes.onChange += (o) => { }; + var rows = routes.rows; + string route_txt = String.Empty; + foreach (IBlueRow r in rows) + { + var tag_regexp = r.get("tag_regexp"); + var server_url = r.get("server_url"); + route_txt += $"{tag_regexp} : {server_url},"; + } + + this.Text = $"Data Stream Query Analyzer | routes: {route_txt}"; myToolStripStatusLabelTime.Text = "Ready"; myToolStripStatusLabelRows.Text = string.Empty; } @@ -88,10 +106,12 @@ namespace BCG { /// Gets the data in the form of a multilevel IDictionary /// /// - private IDictionary myGetLibraryData() { + private IDictionary myGetLibraryData() + { SortedList retVal = new SortedList(); string[] primitiveNames = PrimitiveManager.instance.getPrimitiveNames(); - foreach (string pName in primitiveNames) { + foreach (string pName in primitiveNames) + { string aName = PrimitiveManager.instance.getAssemblyName(pName); ICollection cNames = PrimitiveManager.instance.getConstructorSigns(pName); if (!retVal.Contains(aName)) @@ -106,12 +126,15 @@ namespace BCG { } - private void myLoadAssemblies() { + private void myLoadAssemblies() + { myTreeView.Nodes.Clear(); IDictionary libraryData = myGetLibraryData(); - foreach (DictionaryEntry de in libraryData) { + foreach (DictionaryEntry de in libraryData) + { TreeNode assemblyNode = new TreeNode(de.Key as String); - foreach (DictionaryEntry innerDe in (de.Value as IDictionary)) { + foreach (DictionaryEntry innerDe in (de.Value as IDictionary)) + { TreeNode primitiveNode = new TreeNode(innerDe.Key as string); foreach (string con in (innerDe.Value as ICollection)) primitiveNode.Nodes.Add(con); @@ -131,23 +154,27 @@ namespace BCG { }*/ } - private void myHandleTableListChange(object o) { + private void myHandleTableListChange(object o) + { IBlueRowCollection rows = (o as DataPacket).newRows; myUpdateTableList(); } #region Persistence Keys - public int textBoxHeight { + public int textBoxHeight + { get { return myQueryTextBox.Height; } set { myQueryTextBox.Height = value; } } #endregion - private void myTryExpression(string expStr) { + private void myTryExpression(string expStr) + { myFreezeView(false); // force unfreeze the view DataStreamExpression oldExp = myExp; - try { + try + { var exp = DataStreamExpressionsInterpreter.Evaluate(expStr); if (exp == null) @@ -173,7 +200,9 @@ namespace BCG { oldExp.getView(new Hashtable()).onChange -= new DataStream.ChangeDelegate(myCallback); */ //myQueryTextBox.Text = expStr; - } catch (Exception exc) { + } + catch (Exception exc) + { Log.Ui.warn(exc.ToString()); myDataGrid.DataSource = null; @@ -187,7 +216,8 @@ namespace BCG { } } - private string myExtractFromClass(TextReader r) { + private string myExtractFromClass(TextReader r) + { string line = r.ReadLine(); while (line != null && line.IndexOf("*Expression*") == -1) line = r.ReadLine(); @@ -200,7 +230,8 @@ namespace BCG { string result = ""; line = r.ReadLine(); - while (line != null && line.IndexOf("----------------------------------------------------------------------") == -1) { + while (line != null && line.IndexOf("----------------------------------------------------------------------") == -1) + { if (line != "") result += line.Substring(" ".Length) + "\n"; line = r.ReadLine(); @@ -211,17 +242,24 @@ namespace BCG { return result; } - public void loadFile(string fileName) { - try { + public void loadFile(string fileName) + { + try + { TextReader r = new StreamReader(fileName); - try { + try + { myQueryTextBox.Text = myExtractFromClass(r); - } finally { + } + finally + { r.Close(); } myLastFileName = fileName; this.Text = fileName; - } catch (Exception exc) { + } + catch (Exception exc) + { Log.Ui.warn(exc.ToString()); myDataGrid.DataSource = null; @@ -232,7 +270,8 @@ namespace BCG { } - private void myPrintCode(IBlueTableSchema schema, ICollection vars, string code) { + private void myPrintCode(IBlueTableSchema schema, ICollection vars, string code) + { myCSharpText.Text = "using System;\n\nnamespace BCG\n{"; @@ -252,7 +291,8 @@ namespace BCG { string lastVar = null; string variableDeclarations = ""; - foreach (string var in vars) { + foreach (string var in vars) + { variableDeclarations += " ViewStream " + var + ";\n"; lastVar = var; } @@ -282,13 +322,16 @@ namespace BCG { myCSharpText.Text += "}"; } - static DataGridViewColumn _column_factory(ColumnInfo ci) { - return new DataGridViewTextBoxColumn { + static DataGridViewColumn _column_factory(ColumnInfo ci) + { + return new DataGridViewTextBoxColumn + { HeaderText = ci.colName, Width = get_col_width(ci) }; - static int get_col_width(ColumnInfo ci) { + static int get_col_width(ColumnInfo ci) + { const int CHAR_WIDTH = 10; const int MIN_WIDTH = 50; const int MIN_DATE_WIDTH = 200; @@ -299,12 +342,14 @@ namespace BCG { } // this is the stream callback - private void myCallback(object o) { + private void myCallback(object o) + { var timer = Stopwatch.StartNew(); DataPacket dp = o as DataPacket; myCrono.Stop(); Log.Ui.diag($"Received callback for {dp.schema.tableName}"); - if (o == null) { + if (o == null) + { System.Windows.Forms.MessageBox.Show(this, "Received a Null Data packet", "Invalid Data", MessageBoxButtons.OK, MessageBoxIcon.Error); return; @@ -321,7 +366,8 @@ namespace BCG { myDataGrid.DataSource = new SimpleBindableCollection(dp.newRows.schema, dp.newRows); var force = false; - if (myChangeStyle && force) { + if (myChangeStyle && force) + { myChangeStyle = false; myDataGrid.Columns.Clear(); myDataGrid.Columns.AddRange(Array.ConvertAll(dp.schema.columnInfo, _column_factory)); @@ -348,7 +394,8 @@ namespace BCG { private DataStreamExpression? myExp; - private void myTimer_Tick(object sender, System.EventArgs e) { + private void myTimer_Tick(object sender, System.EventArgs e) + { // try // { ViewStreamDatabase.instance.doWork(); @@ -365,22 +412,27 @@ namespace BCG { // } } - class StringWrapper { - public StringWrapper(string s) { + class StringWrapper + { + public StringWrapper(string s) + { myTableName = s; } - public string tableName { + public string tableName + { get { return myTableName; } } private string myTableName; } - private void MainForm_Closed(object sender, System.EventArgs e) { + private void MainForm_Closed(object sender, System.EventArgs e) + { if (myExp != null) myExp.getView(new Dictionary(0)).onChange -= new DataStream.ChangeDelegate(myCallback); } - private void myMenuItemExecuteQueryClick(object sender, System.EventArgs e) { + private void myMenuItemExecuteQueryClick(object sender, System.EventArgs e) + { myQueryTextBox.SelectionStart = myQueryTextBox.Text.Length; myQueryTextBox.SelectionLength = myQueryTextBox.Text.Length; myQueryTextBox.SelectionColor = Color.White; @@ -388,7 +440,8 @@ namespace BCG { myTryExpression(myQueryTextBox.Text); } - private void myToolStripMenuItemExecSel_Click(object sender, EventArgs e) { + private void myToolStripMenuItemExecSel_Click(object sender, EventArgs e) + { // int selstart = myQueryTextBox.SelectionStart; // int sellength = myQueryTextBox.SelectionLength; // myQueryTextBox.SelectionStart = 0; @@ -403,7 +456,8 @@ namespace BCG { // myQueryTextBox.SelectionColor = Color.White; } - private void myMenuItemOpenClick(object sender, System.EventArgs e) { + private void myMenuItemOpenClick(object sender, System.EventArgs e) + { OpenFileDialog od = new OpenFileDialog(); od.Filter = "C# class (*.cs)|*.cs"; @@ -411,21 +465,24 @@ namespace BCG { loadFile(od.FileName); } - private void mySave(string fileName) { + private void mySave(string fileName) + { using (TextWriter w = new StreamWriter(fileName)) w.Write(myCSharpText.Text); myLastFileName = fileName; this.Text = fileName; } - private void myMenuItemSaveClick(object sender, System.EventArgs e) { + private void myMenuItemSaveClick(object sender, System.EventArgs e) + { if (myLastFileName == null) myMenuItemSaveAsClick(sender, e); else mySave(myLastFileName); } - private void myMenuItemSaveAsClick(object sender, System.EventArgs e) { + private void myMenuItemSaveAsClick(object sender, System.EventArgs e) + { SaveFileDialog sd = new SaveFileDialog(); if (myLastFileName != null) sd.FileName = myLastFileName; @@ -436,47 +493,56 @@ namespace BCG { mySave(sd.FileName); } - private void myTableListBox_DoubleClick(object sender, System.EventArgs e) { - if (myTableListBox.SelectedItem != null) { + private void myTableListBox_DoubleClick(object sender, System.EventArgs e) + { + if (myTableListBox.SelectedItem != null) + { string tableName = myTableListBox.SelectedItem.ToString(); myQueryTextBox.Text = myQueryTextBox.Text == "" ? tableName : myQueryTextBox.Text + "\n" + tableName; myTryExpression(myQueryTextBox.Text); } } - private void myDataGrid_MouseEnter(object sender, System.EventArgs e) { + private void myDataGrid_MouseEnter(object sender, System.EventArgs e) + { //myDataGrid.TableStyles[0].GridLineColor = Color.LightSteelBlue; // if (myDataGrid.TableStyles.Count > 0) // myDataGrid.TableStyles[0].HeaderBackColor = Color.LightSteelBlue; } - private void myDataGrid_MouseLeave(object sender, System.EventArgs e) { + private void myDataGrid_MouseLeave(object sender, System.EventArgs e) + { //myDataGrid.TableStyles[0].GridLineColor = Color.Gainsboro; // if (myDataGrid.TableStyles.Count > 0) // myDataGrid.TableStyles[0].HeaderBackColor = Color.Gainsboro; } - private void myCSharpText_MouseEnter(object sender, System.EventArgs e) { + private void myCSharpText_MouseEnter(object sender, System.EventArgs e) + { //myCSharpText.BackColor = Color.Gainsboro; myCSharpText.Font = new Font(myCSharpText.Font.Name, myCSharpText.Font.Size, FontStyle.Bold); } - private void myCSharpText_MouseLeave(object sender, System.EventArgs e) { + private void myCSharpText_MouseLeave(object sender, System.EventArgs e) + { //myCSharpText.BackColor = Color.White; myCSharpText.Font = new Font(myCSharpText.Font.Name, myCSharpText.Font.Size, FontStyle.Regular); } - private void myTableListBox_MouseEnter(object sender, System.EventArgs e) { + private void myTableListBox_MouseEnter(object sender, System.EventArgs e) + { //myTableListBox.BackColor = Color.Gainsboro; myTableListBox.Font = new Font(myTableListBox.Font.Name, myTableListBox.Font.Size, FontStyle.Bold); } - private void myTableListBox_MouseLeave(object sender, System.EventArgs e) { + private void myTableListBox_MouseLeave(object sender, System.EventArgs e) + { //myTableListBox.BackColor = Color.White; myTableListBox.Font = new Font(myTableListBox.Font.Name, myTableListBox.Font.Size, FontStyle.Regular); } - private void myLoad(object sender, EventArgs e) { + private void myLoad(object sender, EventArgs e) + { myFreezeView(false); myToolStripMenuItemSite.DropDownItems.Clear(); @@ -500,7 +566,9 @@ namespace BCG { { var ex = new Win32Exception(); // same as new Win32Exception(Marshal.GetLastWin32Error()) Console.WriteLine(ex.Message); - } else { + } + else + { Console.WriteLine("Set stdout worked."); } @@ -508,7 +576,9 @@ namespace BCG { { var ex = new Win32Exception(); // same as new Win32Exception(Marshal.GetLastWin32Error()) Console.WriteLine(ex.Message); - } else { + } + else + { Console.WriteLine("Set stderr worked."); } Console.WriteLine("Redirecting console ouput to this window..."); @@ -524,10 +594,12 @@ namespace BCG { //_library = new LibraryForm(this); } - private void myMenuItemSiteClick(object sender, System.EventArgs e) { + private void myMenuItemSiteClick(object sender, System.EventArgs e) + { ToolStripMenuItem mi = (ToolStripMenuItem)sender; - if (mi.Text != mySite) { + if (mi.Text != mySite) + { mySite = mi.Text; foreach (var m in mySiteItems) m.Checked = false; @@ -548,63 +620,78 @@ namespace BCG { } } - private void myClosing(object sender, CancelEventArgs e) { + private void myClosing(object sender, CancelEventArgs e) + { } - private void myHandleTreeNodeSelect(object sender, TreeViewEventArgs e) { - if (myTreeView.SelectedNode != null) { - if (myTreeView.SelectedNode.LastNode == null) { + private void myHandleTreeNodeSelect(object sender, TreeViewEventArgs e) + { + if (myTreeView.SelectedNode != null) + { + if (myTreeView.SelectedNode.LastNode == null) + { string sn = myTreeView.SelectedNode.Parent.Text + "()"; myQueryTextBox.Text = myQueryTextBox.Text == "" ? sn : myQueryTextBox.Text + "\n" + sn; } } } - private void myToolStripMenuItemExit_Click(object sender, EventArgs e) { + private void myToolStripMenuItemExit_Click(object sender, EventArgs e) + { Close(); } - private void myToolStripMenuItemFreeze_Click(object sender, EventArgs e) { + private void myToolStripMenuItemFreeze_Click(object sender, EventArgs e) + { myFreezeView(myTimer.Enabled); } - private void myFreezeView(bool freeze) { + private void myFreezeView(bool freeze) + { myTimer.Enabled = !freeze; myToolStripMenuItemFreeze.Checked = freeze; myToolStripMenuItemStep.Enabled = freeze; } - private void myToolStripMenuItemStep_Click(object sender, EventArgs e) { + private void myToolStripMenuItemStep_Click(object sender, EventArgs e) + { ViewStreamDatabase.instance.doWork(); } - private void myToolStripMenuItemLoadAss_Click(object sender, EventArgs e) { + private void myToolStripMenuItemLoadAss_Click(object sender, EventArgs e) + { OpenFileDialog ofd = new OpenFileDialog(); ofd.ShowReadOnly = true; DialogResult dr = ofd.ShowDialog(this); - if (ofd.CheckFileExists && ofd.CheckPathExists && dr == DialogResult.OK) { + if (ofd.CheckFileExists && ofd.CheckPathExists && dr == DialogResult.OK) + { PrimitiveManager.instance.loadAssembly(ofd.FileName); myLoadAssemblies(); } } - private void myToolStripMenuItemTest_Click(object sender, EventArgs e) { - if (myCurrentStream != null) { + private void myToolStripMenuItemTest_Click(object sender, EventArgs e) + { + if (myCurrentStream != null) + { myCurrentStream.onChange -= new DataStream.ChangeDelegate(myCallback); myCurrentStream.onChange += new DataStream.ChangeDelegate(myCallback); } } - private void myToolStripMenuItemClearConsole_Click(object sender, EventArgs e) { + private void myToolStripMenuItemClearConsole_Click(object sender, EventArgs e) + { myConsoleRichTextBox.Clear(); Console.WriteLine("Redirecting console ouput to this window..."); } - private void myTableFilterBox_TextChanged(object sender, EventArgs e) { + private void myTableFilterBox_TextChanged(object sender, EventArgs e) + { myUpdateTableList(); } - private void myUpdateTableList() { + private void myUpdateTableList() + { IBlueRowCollection rows = myAllTagsStream.rows; if (rows == null) return; @@ -619,12 +706,15 @@ namespace BCG { myTableListBox.Items.Clear(); SortedList sl = new SortedList(); if (string.IsNullOrEmpty(myTableFilterBox.Text)) - foreach (IBlueRow r in rows) { + foreach (IBlueRow r in rows) + { sl[r["tag"].ToString().Substring(DSTagManager.get_stream_tag("").Length)] = true; } - else { + else + { Regex tableRegex = new Regex(myTableFilterBox.Text); - foreach (IBlueRow r in rows) { + foreach (IBlueRow r in rows) + { string thisTable = r["tag"].ToString().Substring(DSTagManager.get_stream_tag("").Length); if (tableRegex.IsMatch(thisTable)) sl[thisTable] = true; @@ -642,7 +732,8 @@ namespace BCG { myTableListBox.EndUpdate(); } - private void testGridToolStripMenuItem_Click(object sender, EventArgs e) { + private void testGridToolStripMenuItem_Click(object sender, EventArgs e) + { var timer = new Stopwatch(); //while (true) //{ @@ -664,9 +755,11 @@ namespace BCG { foreach (IBlueRow r in s.rows) rows.Add(r); - for (int i = 0; i < 100; i++) { + for (int i = 0; i < 100; i++) + { timer.Restart(); - rows.Sort(delegate (IBlueRow r1, IBlueRow r2) { + rows.Sort(delegate (IBlueRow r1, IBlueRow r2) + { return _sort_dicts_index(r1, r2, 5, true); }); timer.Stop(); @@ -674,19 +767,22 @@ namespace BCG { } } - private static int mySortDictionaries(IBlueRow r1, IBlueRow r2, string column, bool low_to_high) { + private static int mySortDictionaries(IBlueRow r1, IBlueRow r2, string column, bool low_to_high) + { if (r1.Contains(column) && r2.Contains(column)) return compare_send_dontcare_to_last(r1[column], r2[column], low_to_high); else return 0; } - private static int _sort_dicts_index(IBlueRow r1, IBlueRow r2, int col_no, bool low_to_high) { + private static int _sort_dicts_index(IBlueRow r1, IBlueRow r2, int col_no, bool low_to_high) + { //return compare_send_dontcare_to_last(r1[col_no], r2[col_no], low_to_high); return ((IComparable)r1[col_no]).CompareTo(r2[col_no]); } - internal static int compare_send_dontcare_to_last(object o1, object o2, bool low_to_high) { + internal static int compare_send_dontcare_to_last(object o1, object o2, bool low_to_high) + { if (myIsDontCare(o1)) return myIsDontCare(o2) ? 0 : 1; else @@ -694,14 +790,16 @@ namespace BCG { : ((IComparable)o2).CompareTo(o1)); } - private static bool myIsDontCare(object o) { + private static bool myIsDontCare(object o) + { return o == null || o == DBNull.Value || o is string && String.IsNullOrEmpty((string)o) || o is double && (Double.IsInfinity((double)o) || Double.IsNaN((double)o)) || o is float && (Single.IsInfinity((float)o) || Single.IsNaN((float)o)); } - private void _new_grid_form(object args) { + private void _new_grid_form(object args) + { //System.Timers.Timer t = new System.Timers.Timer(); ////t.SynchronizingObject //BCG.Utilities.BlueEventLog.logEvent(String.Format("New BTSTabularGridTestForm created on thread {0}", System.Threading.Thread.CurrentThread.ManagedThreadId), @@ -713,11 +811,13 @@ namespace BCG { private void libraryToolStripMenuItem_Click(object sender, EventArgs e) { } - private void myTableFilterLabel_Click(object sender, EventArgs e) { + private void myTableFilterLabel_Click(object sender, EventArgs e) + { } - private void MainForm_Load(object sender, EventArgs e) { + private void MainForm_Load(object sender, EventArgs e) + { } } diff --git a/src/DataStreamSuite/PubSub/Client/Communication/BlutoTCP/BlutoSubAddress.cs b/src/DataStreamSuite/PubSub/Client/Communication/BlutoTCP/BlutoSubAddress.cs index 71b0ca803..5ed637877 100644 --- a/src/DataStreamSuite/PubSub/Client/Communication/BlutoTCP/BlutoSubAddress.cs +++ b/src/DataStreamSuite/PubSub/Client/Communication/BlutoTCP/BlutoSubAddress.cs @@ -1,77 +1,77 @@ -using System; -using System.Collections.Generic; -using System.Text; -//using BCG.Utilities; -using System.Net; +// using System; +// using System.Collections.Generic; +// using System.Text; +// //using BCG.Utilities; +// using System.Net; -namespace BCG -{ - public class BlutoSubAddress : SubAddress - { - private string myIp; - private int myPort; +// namespace BCG +// { +// public class BlutoSubAddress : SubAddress +// { +// private string myIp; +// private int myPort; - public static string prefix = "bluto"; +// public static string prefix = "bluto"; - public BlutoSubAddress(string ip, int port) - { - myIp = ip; - myPort = port; - } +// public BlutoSubAddress(string ip, int port) +// { +// myIp = ip; +// myPort = port; +// } - public BlutoSubAddress(string serverAddress) - { - string[] toks = serverAddress.Split(':'); - // TODO - // BlueEventLog.logAssert(toks.Length == 3); - // BlueEventLog.logAssert(toks[0].ToLower().StartsWith(prefix)); +// public BlutoSubAddress(string serverAddress) +// { +// string[] toks = serverAddress.Split(':'); +// // TODO +// // BlueEventLog.logAssert(toks.Length == 3); +// // BlueEventLog.logAssert(toks[0].ToLower().StartsWith(prefix)); - string machineNameOrIP = toks[1].Remove(0, 2); +// string machineNameOrIP = toks[1].Remove(0, 2); - if (machineNameOrIP.Split('.').Length == 4) - myIp = toks[1].Remove(0, 2); - else - { - //get the IP address from DNS - IPAddress[] theAddressList = Dns.GetHostEntry(machineNameOrIP).AddressList; - //BlueEventLog.logAssert(theAddressList.Length == 1, "Error: machine has multiple ip addresses."); - //if we get multiple addresses, we want the one that is of the corret dotted notation - bool oneWorked = false; - foreach (IPAddress addr in theAddressList) - { - if (addr.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6) - { - myIp = addr.ToString(); - oneWorked = true; - - } - } +// if (machineNameOrIP.Split('.').Length == 4) +// myIp = toks[1].Remove(0, 2); +// else +// { +// //get the IP address from DNS +// IPAddress[] theAddressList = Dns.GetHostEntry(machineNameOrIP).AddressList; +// //BlueEventLog.logAssert(theAddressList.Length == 1, "Error: machine has multiple ip addresses."); +// //if we get multiple addresses, we want the one that is of the corret dotted notation +// bool oneWorked = false; +// foreach (IPAddress addr in theAddressList) +// { +// if (addr.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6) +// { +// myIp = addr.ToString(); +// oneWorked = true; - if (!oneWorked) - { - throw new ArgumentException("Couldn't form server address from string " + serverAddress); - } - +// } +// } - } - myPort = Convert.ToInt32(toks[2]); - } +// if (!oneWorked) +// { +// throw new ArgumentException("Couldn't form server address from string " + serverAddress); +// } - - public string ip - { - get { return myIp; } - } +// } +// myPort = Convert.ToInt32(toks[2]); +// } - public int port - { - get { return myPort; } - } - public override string ToString() - { - return prefix + "://" + ip + ":" + port; - } - } -} + +// public string ip +// { +// get { return myIp; } +// } + +// public int port +// { +// get { return myPort; } +// } + +// public override string ToString() +// { +// return prefix + "://" + ip + ":" + port; +// } +// } +// } diff --git a/src/DataStreamSuite/PubSub/Client/Communication/BlutoTCP/SmartConnectionManagedWrapper.cs b/src/DataStreamSuite/PubSub/Client/Communication/BlutoTCP/SmartConnectionManagedWrapper.cs index ce9c62280..ad207743b 100644 --- a/src/DataStreamSuite/PubSub/Client/Communication/BlutoTCP/SmartConnectionManagedWrapper.cs +++ b/src/DataStreamSuite/PubSub/Client/Communication/BlutoTCP/SmartConnectionManagedWrapper.cs @@ -1,88 +1,89 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Runtime.InteropServices; +// using System; +// using System.Collections.Generic; +// using System.Text; +// using System.Threading; +// using System.Runtime.InteropServices; -namespace BCG -{ - public class SmartConnectionManagedWrapper - { - public delegate void MessageDelegate(int msgType, byte[] msg); - private Dictionary myServerToDel = new Dictionary(); +// TODO: remove +// namespace BCG +// { +// public class SmartConnectionManagedWrapper +// { +// public delegate void MessageDelegate(int msgType, byte[] msg); +// private Dictionary myServerToDel = new Dictionary(); - public SmartConnectionManagedWrapper () - { - ClientToServerConnectionWrapper.init(); - Thread readThr = new Thread(new ThreadStart(myReceiveData)); - readThr.Start(); - } +// public SmartConnectionManagedWrapper () +// { +// ClientToServerConnectionWrapper.init(); +// Thread readThr = new Thread(new ThreadStart(myReceiveData)); +// readThr.Start(); +// } - public void initConnection(BlutoSubAddress subAddress) - { - ClientToServerConnectionWrapper.initServerConnection(ClientToServerConnectionWrapper.stringToBytes(subAddress.ip), - subAddress.port); - } +// public void initConnection(BlutoSubAddress subAddress) +// { +// ClientToServerConnectionWrapper.initServerConnection(ClientToServerConnectionWrapper.stringToBytes(subAddress.ip), +// subAddress.port); +// } - public void send(BlutoSubAddress address, byte[] data) - { - byte[] ip = ClientToServerConnectionWrapper.stringToBytes (address.ip); - ClientToServerConnectionWrapper.sendDataToServer(ip, address.port, data, data.Length); - } - +// public void send(BlutoSubAddress address, byte[] data) +// { +// byte[] ip = ClientToServerConnectionWrapper.stringToBytes (address.ip); +// ClientToServerConnectionWrapper.sendDataToServer(ip, address.port, data, data.Length); +// } - public void resgisterDataCallback(BlutoSubAddress address, MessageDelegate del) - { - lock (this) - { - myServerToDel.Add(address.ToString(), del); - } - } - public void unregisterDataCallback(BlutoSubAddress address, MessageDelegate del) - { - lock (this) - { - myServerToDel.Remove(address.ip); - } - } +// public void resgisterDataCallback(BlutoSubAddress address, MessageDelegate del) +// { +// lock (this) +// { +// myServerToDel.Add(address.ToString(), del); +// } +// } - public string getClientAsSeenByServer(string serverURL) - { - return ""; - } +// public void unregisterDataCallback(BlutoSubAddress address, MessageDelegate del) +// { +// lock (this) +// { +// myServerToDel.Remove(address.ip); +// } +// } - private unsafe void myReceiveData() - { - while (true) - { - BlutoTCPClientMessage** psClientPackets = null; - int npts = 0; - ///returns as soon as it gets the first element - ClientToServerConnectionWrapper.getServerData(1000, 1, &psClientPackets, out npts); - for (int i = 0; i < npts; i++) - { - string ip = Marshal.PtrToStringAnsi(psClientPackets[i]->ip); - int port = psClientPackets[i]->port; - string serverURL = new BlutoSubAddress(ip, port).ToString(); +// public string getClientAsSeenByServer(string serverURL) +// { +// return ""; +// } - byte[] msg = null; - if (psClientPackets[i]->msgType == 1) - { - msg = new byte[psClientPackets[i]->size]; - Marshal.Copy(psClientPackets[i]->msg, msg, 0, msg.Length); - } +// private unsafe void myReceiveData() +// { +// while (true) +// { +// BlutoTCPClientMessage** psClientPackets = null; +// int npts = 0; +// ///returns as soon as it gets the first element +// ClientToServerConnectionWrapper.getServerData(1000, 1, &psClientPackets, out npts); +// for (int i = 0; i < npts; i++) +// { +// string ip = Marshal.PtrToStringAnsi(psClientPackets[i]->ip); +// int port = psClientPackets[i]->port; +// string serverURL = new BlutoSubAddress(ip, port).ToString(); - MessageDelegate cb = null; - lock (this) - { - myServerToDel.TryGetValue(serverURL, out cb); - } - if (cb != null) - cb(psClientPackets[i]->msgType, msg); - } - } - } +// byte[] msg = null; +// if (psClientPackets[i]->msgType == 1) +// { +// msg = new byte[psClientPackets[i]->size]; +// Marshal.Copy(psClientPackets[i]->msg, msg, 0, msg.Length); +// } - } -} +// MessageDelegate cb = null; +// lock (this) +// { +// myServerToDel.TryGetValue(serverURL, out cb); +// } +// if (cb != null) +// cb(psClientPackets[i]->msgType, msg); +// } +// } +// } + +// } +// } diff --git a/src/DataStreamSuite/PubSub/Client/Communication/IPubSubServerConnection.cs b/src/DataStreamSuite/PubSub/Client/Communication/IPubSubServerConnection.cs index ccff39522..7235b4c13 100644 --- a/src/DataStreamSuite/PubSub/Client/Communication/IPubSubServerConnection.cs +++ b/src/DataStreamSuite/PubSub/Client/Communication/IPubSubServerConnection.cs @@ -72,6 +72,6 @@ namespace BCG { /// void register_data_callback(PubSubServerDataDelegate del); - void register_send_confirmation_callback(SendConfirmationDelegate del); + //void register_send_confirmation_callback(SendConfirmationDelegate del); } } diff --git a/src/DataStreamSuite/PubSub/Client/Communication/MSMQ/MSMQSubAddress.cs b/src/DataStreamSuite/PubSub/Client/Communication/MSMQ/MSMQSubAddress.cs index 9d271bbdc..c265bf16c 100644 --- a/src/DataStreamSuite/PubSub/Client/Communication/MSMQ/MSMQSubAddress.cs +++ b/src/DataStreamSuite/PubSub/Client/Communication/MSMQ/MSMQSubAddress.cs @@ -1,52 +1,52 @@ -using System; -//using System.Messaging; +// using System; +// //using System.Messaging; -using BCG; -//using BCG.Utilities; +// using BCG; +// //using BCG.Utilities; -namespace BCG -{ - public class MSMQSubAddress : SubAddress - { - private string myIP, myQ; - public static readonly string prefix = "msmq"; +// namespace BCG +// { +// public class MSMQSubAddress : SubAddress +// { +// private string myIP, myQ; +// public static readonly string prefix = "msmq"; - public MSMQSubAddress (string adr) - { - try - { - // throw away prefix - string s = adr; - s = s.Substring(prefix.Length + "://".Length); - // grab IP - myIP = s.Substring(0,s.IndexOf("/")); - // throw away ip - s = s.Substring(myIP.Length + 1); - myQ = s; - - } - catch (Exception) - { - throw (new InvalidSubAddress(adr + " is not a valid queue address")); - } - } +// public MSMQSubAddress (string adr) +// { +// try +// { +// // throw away prefix +// string s = adr; +// s = s.Substring(prefix.Length + "://".Length); +// // grab IP +// myIP = s.Substring(0,s.IndexOf("/")); +// // throw away ip +// s = s.Substring(myIP.Length + 1); +// myQ = s; - public MSMQSubAddress (string ip, string simpleQName) - { - myIP = ip; - myQ = simpleQName; - } +// } +// catch (Exception) +// { +// throw (new InvalidSubAddress(adr + " is not a valid queue address")); +// } +// } - public string ip {get {return myIP;}} +// public MSMQSubAddress (string ip, string simpleQName) +// { +// myIP = ip; +// myQ = simpleQName; +// } - public string simpleQueueName {get {return myQ;}} +// public string ip {get {return myIP;}} - public override string ToString() { return prefix + "://" + myIP + "/" + myQ; } +// public string simpleQueueName {get {return myQ;}} - public string formatName - { - get{return "FormatName:DIRECT=TCP:" + myIP + "\\private$\\" + myQ;} - } - - } -} +// public override string ToString() { return prefix + "://" + myIP + "/" + myQ; } + +// public string formatName +// { +// get{return "FormatName:DIRECT=TCP:" + myIP + "\\private$\\" + myQ;} +// } + +// } +// } diff --git a/src/DataStreamSuite/PubSub/Client/Communication/ManagedTCP/PubSubServerManagedTCPConnection.cs b/src/DataStreamSuite/PubSub/Client/Communication/ManagedTCP/PubSubServerManagedTCPConnection.cs index 406a258ed..34c7d0d4f 100644 --- a/src/DataStreamSuite/PubSub/Client/Communication/ManagedTCP/PubSubServerManagedTCPConnection.cs +++ b/src/DataStreamSuite/PubSub/Client/Communication/ManagedTCP/PubSubServerManagedTCPConnection.cs @@ -1,296 +1,262 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Net; -using System.Net.Sockets; -using System.IO; -//using BCG.Utilities; -//using BCG.Utilities.General; -using System.Threading; -using mbts; -using bts; -using System.Linq; -using System.Reflection.Metadata.Ecma335; -using Bts.PubSub; - -namespace BCG { - /// - /// Keeps an ITCPConnection for talking to the server. It also monitors heartbeats - /// from the server, and in case of missing hbs, informs its clients, and tries to - /// restablish the connection. - /// Threads : - /// its assumed that IPubSubServerConnection functions (including doWork) will - /// be called from the same thread. ITCPMessageHandler.onData and - /// ITCPConnectionHandler.onConnection will be called on any arbitrary thread - /// - /// - public class PubSubServerManagedTCPConnection : IPubSubServerConnection,// external facing interface to communicate msgs to Pubsubserver - ITCPMessageHandler, // to get messages from ITCPCOnnection - ITCPConnectionHandler { // to get connections from AsyncTCPConnector_APM - private ITCPConnection _connection, _new_connection; - private readonly BlutoSubAddress _server_address; - // if a message(with confirm) can not be sent , its id is queued here, - // on reconnection, _on_send_onfirm_callback is fired with a negative on these ids, so the user - //can re-send it. The re-send mechanism is not in implemented in this class, but by the user of this class - private ThreadSafeQueue _negative_unsent_confs = new ThreadSafeQueue(); - // in onData, data is queued here, for polling - private SyncQueue _in_data_queue = new SyncQueue(); - private DateTime _last_hb = DateTime.Now; - private PubSubServerConnectionStatusChange _conn_callback; - private PubSubServerDataDelegate _data_callback; - private SendConfirmationDelegate _on_send_confirm_callback; - private readonly TimeSpan _connection_drop_threshold = PubSubConfig.Instance.ConnectionDropThreshold(); - - public PubSubServerManagedTCPConnection(string server_url) - : this(new BlutoSubAddress(server_url)) { } - - public PubSubServerManagedTCPConnection(BlutoSubAddress server_address) { - _server_address = server_address; - _connect_to_ps_server(); - } - - private void _connect_to_ps_server() { - bts.Log.Gen.info($"PubSubServerManagedTCPConnection._connect_to_ps_server server: {_server_address}"); - AsyncTCPConnector_APM.connect_to(_server_address, this); - } - - #region IPubSubServerConnection Members - - public void send_with_confirmation(byte[] data, ref string conf_id) { - bts.Log.Gen.info($"PubSubServerManagedTCPConnection.sendWithConfirmation server: {_server_address} data: {data.Length} _connection : {_connection != null}"); - if (_connection != null) { - _connection.sendWithConfirmation(data, ref conf_id, (msg_id, confirmed) => { - if (_on_send_confirm_callback != null) - _on_send_confirm_callback(msg_id, confirmed); - }); - } else { - bts.Log.Gen.warn($"PubSubServerManagedTCPConnection.sendWithConfirmation server: {_server_address} no connection, buffering send"); - conf_id = Guid.NewGuid().ToString(); - _negative_unsent_confs.enqueue(conf_id); - } - } - - private void _send(byte[] data) { - bts.Log.Gen.info($"PubSubServerManagedTCPConnection._send server: {_server_address} data: {data.Length} _connection : {_connection != null}"); - if (_connection != null) { - bts.Log.Gen.info("PubSubServerManagedTCPConnection.send server: " + _server_address + "data: " + data.Length); - _connection.send(data); - } - } - - public void send(bts.PubSubClientMessage ps_msg) { - bts.Log.Gen.info($"PubSubServerManagedTCPConnection.send server: {_server_address} ps_msg: {ps_msg}"); - var msg_bytes = ps_msg.serialize_into_bytes(); - PubSubClientMessage msg_retrv = new PubSubClientMessage(); - msg_retrv.consruct_deserialize(msg_bytes); - bts.Log.Gen.info($"PubSubServerManagedTCPConnection.send server: {_server_address} msg_retrv: {msg_retrv}"); - _send(msg_bytes); - } - - // private void send(Stream str) { - // BinaryReader br = new BinaryReader(str); - // _send(br.ReadBytes(Convert.ToInt32(str.Length - str.Position))); - // } - - // private void send(PubSubMessage msg) { - // send(msg.to_stream()); - // } - - // public void send_with_confirmation(PubSubMessage msg, ref string conf_id) { - // var bytes = msg.to_bytes(); - // send_with_confirmation(bytes, ref conf_id); - // } - - public void send_with_confirmation(bts.PubSubClientMessage msg, ref string conf_id, SendConfirmationDelegate del) { - if (_connection == null) { - // quq - } - MemoryStream str = new MemoryStream(); - msg.serialize_into_str(str); - var bytes = StreamUtilityMethods.getBytesFromStream(str); - _connection.sendWithConfirmation(bytes, ref conf_id, del); - } - - public IEnumerable get_updates(TimeSpan timeout, int maxElements) { - List rv_raw = _in_data_queue.dequeueMultipleElements(Convert.ToInt32(timeout.TotalMilliseconds), maxElements); - List rv = new List(); - var i = 0; - foreach (var b in rv_raw) { - PubSubServerMessage ps_msg = new PubSubServerMessage(); - ps_msg.consruct_deserialize(b); - bts.Log.Gen.info($"PubSubServerManagedTCPConnection.get_updates downloaded: {ps_msg} msg_no: {i} / {rv_raw.Count}"); - rv.Add(ps_msg); - i++; - } - return rv; - } - - public string server_url { - get { return _server_address.ToString(); } - } - - public string client_url { - get { - string rv = ""; - lock (this) { - if (_connection == null) { - rv = ""; - } else { - if (PubSubConfig.Instance.IpTranslation.is_null_or_empty()) { - string ip; - int port; - _connection.getSelfAddress(out ip, out port); - rv = new BlutoSubAddress(ip, port).ToString(); - } else { - rv = ""; - } - } - } - return rv; - } - } - - public void register_connection_callback(PubSubServerConnectionStatusChange del) { - _conn_callback = del; - } - - public void register_data_callback(PubSubServerDataDelegate del) { - _data_callback = del; - } - - public void register_send_confirmation_callback(SendConfirmationDelegate del) { - _on_send_confirm_callback = del; - } - - #endregion - - #region IDisposable Members - - private bool _is_disposed = false; - public void Dispose() { - bts.Log.Gen.info("PubSubServerManagedTCPConnection.Dispose"); - //throw new Exception("The method or operation is not implemented."); - if (_connection != null) { - _connection.Dispose(); - - } - _is_disposed = true; - } - public bool isDisposed { - get { - return _is_disposed; - } - - } - - #endregion - - #region ITCPMessageHandler Members - - /// - /// This method is executed on an arbitrary CLR thread. To avoid blocking it - /// data is written to the queue and method returns. myLastHB being a primitive - /// (long) is safe for multi threaded operations - /// - /// - public void onData(RemoteMessage message) { - bts.Log.Gen.info($"PubSubServerManagedTCPConnection.onData message: {message}"); - // TODO check for disconenction - switch (message.messageType) { - case RemoteMessageType.Data: - if (_data_callback != null) - _data_callback(message.remoteConnectionInfo.ToString(), message.message); - else - _in_data_queue.enqueue(message.message); - break; - case RemoteMessageType.Heartbeat: - _last_hb = DateTime.Now; - break; - case RemoteMessageType.Connection: - _conn_callback(_server_address.ToString(), true); - break; - case RemoteMessageType.Disconnection: - if (_conn_callback != null) - _conn_callback(_server_address.ToString(), false); - _connection.Dispose(); - _connect_to_ps_server(); - break; - - } - } - - #endregion - - #region ITCPConnectionHandler Members - - /// will be called on on an rbitrary .Net thread - public void onConnection(ITCPConnection connection) { - string ip; - int port; - connection.getPeerAddress(out ip, out port); - BlutoSubAddress add = new BlutoSubAddress(ip, port); - bts.Log.Gen.info($"PubSubServerManagedTCPConnection.onConnection add: {add.ToString()} connection type: {connection.GetType()}"); - if (add.ToString() == _server_address.ToString()) { - _last_hb = DateTime.Now; - _new_connection = connection; - } - } - - #endregion - - void _dispose_and_reconnect_if_missing_hb() { - if (!_connection.isDisposed) { - TimeSpan hb_interval = DateTime.Now - _last_hb; - bool hb_missed = hb_interval > _connection_drop_threshold; - if (hb_missed) { - if (_conn_callback != null) - _conn_callback(_server_address.ToString(), false); - bts.Log.Gen.info("PubSubServerManagedTCPConnection._dispose_and_reconnect_if_missing_hb disposing connecion: {myServerAddress}"); - _connection.Dispose(); - _connect_to_ps_server(); - } - } else { - // already disposed, nothing to do - } - } - - void _check_for_new_connection() { - if (_new_connection != null) { - _connection = _new_connection; - _new_connection = null; // since we are using its presence as a marker of nw connections - bts.Log.Gen.info("PubSubServerManagedTCPConnection._check_for_new_connection assigning new connection"); - _connection.register(this); - if (_conn_callback != null) - _conn_callback(_server_address.ToString(), true); - if (_on_send_confirm_callback != null) { - var msg_ids = _negative_unsent_confs.dequeueAll(); - foreach (var id in msg_ids) - _on_send_confirm_callback(id, false); - } - } - } - - #region IWorker Members - - /// - /// should be called on the same thread as the other user functions. - /// the design only allows for onConnection to be on a different - /// thread. - /// - public void doWork() { - //_dispose_and_reconnect_if_missing_hb(); - //try { - _check_for_new_connection(); - // } catch (Exception ex) { - // bts.Log.Gen.warn($"PubsSubServerManagedTCPConnection.doWork ex: {ex}"); - // } - } - - #endregion - - // private void myOnSendConfirm(string messageId, bool confirmed) { - // _negative_confs.enqueue(new Pair(messageId, confirmed)); - // } - - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Net; +using System.Net.Sockets; +using System.IO; +//using BCG.Utilities; +//using BCG.Utilities.General; +using System.Threading; +using mbts; +using bts; +using System.Linq; +using System.Reflection.Metadata.Ecma335; +using Bts.PubSub; +using Microsoft.Win32; +using System.ComponentModel; + +namespace BCG { + /// + /// Keeps an ITCPConnection for talking to the server. It also monitors heartbeats + /// from the server, and in case of missing hbs, informs its clients, and tries to + /// restablish the connection. + /// Threads : + /// its assumed that IPubSubServerConnection functions (including doWork) will + /// be called from the same thread. ITCPMessageHandler.onData and + /// ITCPConnectionHandler.onConnection are called on an arbitrary thread. + /// _conn_callback is called from within doWork, and _data_callback is called grom + // an arbitrary data thread + /// + public class PubSubServerManagedTCPConnection : IPubSubServerConnection,// external facing interface to communicate msgs to Pubsubserver + ITCPMessageHandler, // to get messages from ITCPCOnnection + ITCPConnectionHandler { // to get connections from AsyncTCPConnector_APM + private ITCPConnection _connection; + private readonly RemoteConnectionInfo _server_rc_info; + private readonly bool _is_sub; + // if _data_callback is not subscribed to , the user of this class can poll updates, + // in which case this queue will be used + private SyncQueue _in_data_queue = new SyncQueue(); + private DateTime _last_hb = DateTime.Now; + private PubSubServerConnectionStatusChange _conn_callback; + private PubSubServerDataDelegate _data_callback; + private readonly TimeSpan _connection_drop_threshold = PubSubConfig.Instance.ConnectionDropThreshold(); + private ThreadSafeQueue _conn_cb_queue = new ThreadSafeQueue(); + + // the callbacks for connection, comes from the ITCPConnection, when a connection is broken, + // and from AsyncTCPConnector whne a connection is established. ALl that info is assembled here and + // enqueued, deuqued oin the doWork and acted on + private class ConnectionStatusChange { + public enum Status { + CONNECTED, + DISCONNECTED + } + public readonly Status connection_satus; + public readonly ITCPConnection new_connection = null; + public ConnectionStatusChange(Status connection_satus_, ITCPConnection new_connection_) { + connection_satus = connection_satus_; + new_connection = new_connection_; + } + public override string ToString() { + return connection_satus.ToString(); + } + } + + public PubSubServerManagedTCPConnection(RemoteConnectionInfo server_address, bool is_sub) { + Log.Gen.info("PubSubServerManagedTCPConnection.cons server_address: {server_address} is_sub: {is_sub}"); + _server_rc_info = server_address; + _is_sub = is_sub; + // this is where it tries to connect to the pubsub server, and gets a callback on onConnection + _connect_to_ps_server(); + } + + private void _connect_to_ps_server() { + bts.Log.Gen.info($"PubSubServerManagedTCPConnection._connect_to_ps_server server _server_rc_info: {_server_rc_info} is_sub: {_is_sub}"); + // onConnection will be called on an arbitrary thread + AsyncTCPConnector_AsyncWrapper.connect_to(_server_rc_info, this); + } + + #region IPubSubServerConnection Members + + private void _send(byte[] data) { + bts.Log.Gen.info($"PubSubServerManagedTCPConnection._send client: {client_url} server: {_server_rc_info} data: {data.Length} is_sub: {_is_sub} _connection : {_connection != null}"); + if (_connection != null) { + _connection.send(data); + bts.Log.Gen.info("PubSubServerManagedTCPConnection.send, data is sent, server: " + _server_rc_info + "data: " + data.Length); + } else { + bts.Log.Gen.warn($"PubSubServerManagedTCPConnection._send, could not send data, server: {_server_rc_info} data: {data.Length} is_sub: {_is_sub} _connection : {_connection != null} "); + } + } + + public void send(bts.PubSubClientMessage ps_msg) { + bts.Log.Gen.info($"PubSubServerManagedTCPConnection.send server: {_server_rc_info} ps_msg: {ps_msg}"); + // whys it constructed again? + var msg_bytes = ps_msg.serialize_into_bytes(); + //bts.Log.Gen.info($"PubSubServerManagedTCPConnection.send server: {_server_rc_info} msg_retrv: {msg_retrv}"); + _send(msg_bytes); + } + + public IEnumerable get_updates(TimeSpan timeout, int maxElements) { + List rv_raw = _in_data_queue.dequeueMultipleElements(Convert.ToInt32(timeout.TotalMilliseconds), maxElements); + List rv = new List(); + var i = 0; + foreach (var b in rv_raw) { + PubSubServerMessage ps_msg = new PubSubServerMessage(); + ps_msg.consruct_deserialize(b); + bts.Log.Gen.info($"PubSubServerManagedTCPConnection.get_updates downloaded: {ps_msg} msg_no: {i} / {rv_raw.Count}"); + rv.Add(ps_msg); + i++; + } + return rv; + } + + public string server_url { + get { return _server_rc_info.ToString(); } + } + + public string client_url { + get { + if (_connection == null) + return RemoteConnectionInfo.null_instance.ToString(); + return _connection.get_self_address().ToString(); + } + } + + public void register_connection_callback(PubSubServerConnectionStatusChange del) { + _conn_callback = del; + } + + public void register_data_callback(PubSubServerDataDelegate del) { + _data_callback = del; + } + + #endregion + + #region IDisposable Members + + private bool _is_disposed = false; + public void Dispose() { + if (isDisposed) + return; + bts.Log.Gen.info("PubSubServerManagedTCPConnection.Dispose"); + if (_connection != null) { + _connection.Dispose(); + } + _is_disposed = true; + } + public bool isDisposed { + get { + return _is_disposed; + } + } + + #endregion + + #region ITCPMessageHandler Members + + /// + /// This method is executed on an arbitrary CLR thread. + /// + /// + public void onData(RemoteMessage message) { + bts.Log.Gen.info($"PubSubServerManagedTCPConnection.onData connection: {_connection} message: {message}"); + // TODO check for disconenction + switch (message.messageType) { + case RemoteMessageType.Data: + if (_data_callback != null) + _data_callback(message.remoteConnectionInfo.ToString(), message.message); + else + _in_data_queue.enqueue(message.message); + break; + case RemoteMessageType.Heartbeat: + _last_hb = DateTime.Now; + break; + case RemoteMessageType.Connection: + // since this is called from the connection, this condition will never hit, ssince + //new connections are detected only by AsyncTCPConnector + Log.assert(false); + break; + case RemoteMessageType.Disconnection: + bts.Log.Gen.info($"PubSubServerManagedTCPConnection.onData case RemoteMessageType.Disconnection: message: {message}"); + _conn_cb_queue.enqueue(new ConnectionStatusChange(ConnectionStatusChange.Status.DISCONNECTED, null)); + break; + + } + } + + #endregion + + #region ITCPConnectionHandler Members + + /// will be called on on an arbitrary .Net thread + public void onConnection(ITCPConnection connection) { + var server_rci = connection.get_peer_address(); + bts.Log.Gen.info($"PubSubServerManagedTCPConnection.onConnection connection: {_connection_txt(connection)}"); + if (_server_rc_info.Equals(server_rci)) { + _conn_cb_queue.enqueue(new ConnectionStatusChange(ConnectionStatusChange.Status.CONNECTED, connection)); + // _last_hb = DateTime.Now; + // _new_connection = connection; + } + } + + #endregion + + void _check_missing_hb() { + if (!_connection.isDisposed) { + TimeSpan hb_interval = DateTime.Now - _last_hb; + bool hb_missed = hb_interval > _connection_drop_threshold; + if (hb_missed) { + bts.Log.Gen.warn("PubSubServerManagedTCPConnection._dispose_and_reconnect_if_missing_hb disposing connecion: {myServerAddress}"); + ConnectionStatusChange ci = new ConnectionStatusChange(ConnectionStatusChange.Status.DISCONNECTED, null); + _conn_cb_queue.enqueue(ci); + } + } else { + // already disposed, nothing to do + } + } + + private static string _connection_txt(ITCPConnection conn) { + if (conn != null) { + return $"conn_type: {conn.GetType()} server: {conn.get_peer_address()} self: {conn.get_self_address()}"; + } + return "NULL"; + } + + #region IWorker Members + + /// + /// should be called on the same thread as the other user functions. + /// the design only allows for onConnection to be on a different + /// thread. + /// + public void doWork() { + //_dispose_and_reconnect_if_missing_hb(); + if (_conn_cb_queue.getCount() > 0) { + var css = _conn_cb_queue.dequeueAll(); + foreach (var c in css) { + Log.Gen.info($"PubSubServerManagedTCPConnection.doWork c: {c}"); + switch (c.connection_satus) { + case ConnectionStatusChange.Status.CONNECTED: { + Log.assert(c.new_connection != null); + c.new_connection.register(this); + _connection = c.new_connection; + _last_hb = DateTime.Now; + if (_conn_callback != null) + _conn_callback(_server_rc_info.ToString(), true); + break; + } + case ConnectionStatusChange.Status.DISCONNECTED: { + _connection.Dispose(); + _connect_to_ps_server(); + if (_conn_callback != null) + _conn_callback(_server_rc_info.ToString(), false); + break; + } + } + } + } + } + + #endregion + + } +} diff --git a/src/DataStreamSuite/PubSub/Client/Communication/PubSubServerConnectionFactory.cs b/src/DataStreamSuite/PubSub/Client/Communication/PubSubServerConnectionFactory.cs index 313683bb4..ef030af16 100644 --- a/src/DataStreamSuite/PubSub/Client/Communication/PubSubServerConnectionFactory.cs +++ b/src/DataStreamSuite/PubSub/Client/Communication/PubSubServerConnectionFactory.cs @@ -3,55 +3,38 @@ using System.Collections.Generic; using System.Text; //using BCG.Utilities; -namespace BCG -{ +namespace BCG { /// /// Every instance of PublisherCore and SubscriberCore will have its /// factory. Rather than have once singelton factory, this approach /// is preffered since multiple pub/sub core can connect to the same /// connection and make it difficultt o manage connections. /// - public class PubSubServerConnectionFactory : IDisposable - { - private bool myIsSub; - private Dictionary myConnections = new Dictionary(); + public class PubSubServerConnectionFactory : IDisposable { + private Dictionary _conn_map = + new Dictionary(); + private readonly bool _is_sub; - internal PubSubServerConnectionFactory (bool isSub) - { - myIsSub = isSub; + internal PubSubServerConnectionFactory(bool is_sub) { + _is_sub = is_sub; } - public IPubSubServerConnection getConnection(string url) - { - if (!myConnections.ContainsKey(url)) - myConnections.Add(url, myBuildConnection(url)); - return myConnections[url]; + public IPubSubServerConnection get_connection(RemoteConnectionInfo server_rci) { + IPubSubServerConnection rv = null; + if (!_conn_map.TryGetValue(server_rci, out rv)) { + rv = _build_connection(server_rci); + _conn_map.Add(server_rci, rv); + } + return rv; } - private IPubSubServerConnection myBuildConnection(string url) - { - if (url.StartsWith(MSMQSubAddress.prefix)) - { - // TODO, no more MSMQ - //Diagnostics.assert(false); - return null; - // MSMQSubAddress serverAdd = new MSMQSubAddress(url); - // return new PubSubServerMSMQConnection(serverAdd.ToString(), myIsSub); - } - else if (url.StartsWith(BlutoSubAddress.prefix)) - { - return new PubSubServerManagedTCPConnection(url); - } - else - { - // BlueEventLog.logAssert(false, "Unknown transport, only msmq and blutoTcp allowed"); - return null; - } + private IPubSubServerConnection _build_connection(RemoteConnectionInfo server_rci) { + return new PubSubServerManagedTCPConnection(server_rci, _is_sub); } #region IDisposable Members - public void Dispose() {} + public void Dispose() { } #endregion } diff --git a/src/DataStreamSuite/PubSub/Client/MetaData/PubSubClientMessage.cs b/src/DataStreamSuite/PubSub/Client/MetaData/PubSubClientMessage.cs index 0aa0c6a02..9f26588c5 100644 --- a/src/DataStreamSuite/PubSub/Client/MetaData/PubSubClientMessage.cs +++ b/src/DataStreamSuite/PubSub/Client/MetaData/PubSubClientMessage.cs @@ -124,7 +124,14 @@ namespace bts { public long publish_time_epoch_ms = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); public byte[] data_to_publish; + public void sanity_check() { + Log.assert(!String.IsNullOrEmpty(tag_type)); + Log.assert(!String.IsNullOrEmpty(tag)); + Log.assert(!String.IsNullOrEmpty(connection)); + } + public void serialize_into_str(Stream str) { + sanity_check(); BinaryWriter bw = new BinaryWriter(str); bw.write_string_cpp(connection); bw.write_string_cpp(publishing_app); diff --git a/src/DataStreamSuite/PubSub/Client/PubsubTagHandlerFactory.cs b/src/DataStreamSuite/PubSub/Client/PubsubTagHandlerFactory.cs index 901810923..bdfdd41ab 100644 --- a/src/DataStreamSuite/PubSub/Client/PubsubTagHandlerFactory.cs +++ b/src/DataStreamSuite/PubSub/Client/PubsubTagHandlerFactory.cs @@ -24,6 +24,7 @@ namespace bts { } private static Dictionary _config_map = new Dictionary() { + {String.Empty, new TagHandlerEntry(DSTagManager.DataStreamTagType , "DataStreamCore", "bts.PubsubServerStreamTagHandler")}, {DSTagManager.DataStreamTagType, new TagHandlerEntry(DSTagManager.DataStreamTagType , "DataStreamCore", "bts.PubsubServerStreamTagHandler")}, {"System_Sub", new TagHandlerEntry("System_Sub", "PubSub", "BCG.SystemSubscriptionMapPublisher")}, {"System_Stats", new TagHandlerEntry("System_Stats", "PubSub", "BCG.SystemStatsPublisher")} diff --git a/src/DataStreamSuite/PubSub/Client/Routing/IPubSubRouter.cs b/src/DataStreamSuite/PubSub/Client/Routing/IPubSubRouter.cs index ae11a0a0d..2d26d22ba 100644 --- a/src/DataStreamSuite/PubSub/Client/Routing/IPubSubRouter.cs +++ b/src/DataStreamSuite/PubSub/Client/Routing/IPubSubRouter.cs @@ -8,11 +8,11 @@ namespace BCG { public interface IPubSubRouter { - event PubSubTagURLChangeDelegate onSubURLTagRouteChange; - event PubSubTagURLChangeDelegate onPubURLTagRouteChange; - List get_all_pubsub_sub_urls(); - List get_all_pubsub_pub_urlss(); - string get_sub_url_for_tag(string tag); - string get_pub_url_for_tag(string tag); + // event PubSubTagURLChangeDelegate onSubURLTagRouteChange; + // event PubSubTagURLChangeDelegate onPubURLTagRouteChange; + IEnumerable sub_routes(); + + RemoteConnectionInfo get_sub_route_for_tag(string tag); + RemoteConnectionInfo get_pub_route_for_tag(string tag); } } diff --git a/src/DataStreamSuite/PubSub/Client/Routing/PubSubRoute.cs b/src/DataStreamSuite/PubSub/Client/Routing/PubSubRoute.cs index d3057dd81..f7d860617 100644 --- a/src/DataStreamSuite/PubSub/Client/Routing/PubSubRoute.cs +++ b/src/DataStreamSuite/PubSub/Client/Routing/PubSubRoute.cs @@ -5,43 +5,38 @@ using System.Text.RegularExpressions; using System.Text.Json.Serialization; using System.Text.Json; using System.Text.Json.Nodes; +using System.Runtime.InteropServices; namespace BCG { [JsonConverter(typeof(PubSubRouteJsonConverter))] public class PubSubRoute : IComparable { - public string serverAddress; - public string tagRegExp; + public string server_address; + public string tag_reg_exp; //route names are used in intermediary code (i.e. while substations are being deployed) //so that MC Hammer can advertise them. public string name; - private Regex myRegex = null; + private Regex _regex = null; public PubSubRoute() { } - public PubSubRoute(string theServerAddress, string theTagRegExp) { - serverAddress = theServerAddress; - tagRegExp = theTagRegExp; + public PubSubRoute(string the_server_address, string the_tag_reg_exp) { + server_address = the_server_address; + tag_reg_exp = the_tag_reg_exp; } - // public PubSubRoute() - // { - // // serverAddress = string.Format("bluto://{0}:{1}", cfg.serverAddress, cfg.serverPort); - // // tagRegExp = cfg.tagsRegex; - // } - public string[] getAllPubSubs() { - return serverAddress.Split(';'); + return server_address.Split(';'); } - public Regex getRegex() { - return myRegex ?? new Regex(tagRegExp); + public Regex get_regex() { + return _regex ?? new Regex(tag_reg_exp); } #region IComparable Members public int CompareTo(PubSubRoute other) { - return serverAddress == other.serverAddress ? tagRegExp.CompareTo(other.tagRegExp) - : serverAddress.CompareTo(other.serverAddress); + return server_address == other.server_address ? tag_reg_exp.CompareTo(other.tag_reg_exp) + : server_address.CompareTo(other.server_address); } #endregion @@ -51,8 +46,8 @@ namespace BCG { return false; else { PubSubRoute other = obj as PubSubRoute; - return serverAddress.Equals(other.serverAddress) && - tagRegExp.Equals(other.tagRegExp); + return server_address.Equals(other.server_address) && + tag_reg_exp.Equals(other.tag_reg_exp); } } @@ -63,27 +58,31 @@ namespace BCG { public static PubSubRoute get_default_route() { return new PubSubRoute("bluto://127.0.0.1:12345", ".*"); } + + public override string ToString() { + return $"tag_reg_exp: {tag_reg_exp} server_address: {server_address}"; + } } public static class PubSubRouteExtensions { public static bool IsMatch(this PubSubRoute route, string tag) => - route.getRegex().IsMatch(tag); + route.get_regex().IsMatch(tag); } public class PubSubRouteJsonConverter : JsonConverter { public override PubSubRoute? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - var jsonObj = JsonSerializer.Deserialize(ref reader); - if (jsonObj is null) { + var json_obj = JsonSerializer.Deserialize(ref reader); + if (json_obj is null) { return null; } var rv = new PubSubRoute(); ReadString("name", ref rv.name); - ReadString("server_address", ref rv.serverAddress); - ReadString("tag", ref rv.tagRegExp); + ReadString("server_address", ref rv.server_address); + ReadString("tag", ref rv.tag_reg_exp); return rv; void ReadString(string key, ref string valueOut) { - if (jsonObj.TryGetPropertyValue(key, out var valueJson)) { + if (json_obj.TryGetPropertyValue(key, out var valueJson)) { var valueStr = valueJson?.GetValue(); // Only (over)write valueOut if non-null if (valueStr is not null) { @@ -96,8 +95,8 @@ namespace BCG { public override void Write(Utf8JsonWriter writer, PubSubRoute value, JsonSerializerOptions options) { var jsonObj = new JsonObject { ["name"] = value.name, - ["server_address"] = value.serverAddress, - ["tag"] = value.tagRegExp, + ["server_address"] = value.server_address, + ["tag"] = value.tag_reg_exp, }; JsonSerializer.Serialize(writer, jsonObj); } diff --git a/src/DataStreamSuite/PubSub/Client/Routing/PubSubRouter.cs b/src/DataStreamSuite/PubSub/Client/Routing/PubSubRouter.cs index 1eb647d3f..1f0c34bf9 100644 --- a/src/DataStreamSuite/PubSub/Client/Routing/PubSubRouter.cs +++ b/src/DataStreamSuite/PubSub/Client/Routing/PubSubRouter.cs @@ -1,97 +1,83 @@ -using System; -using System.Text.RegularExpressions; -using System.Collections; -using System.Collections.Generic; - -using BCG; -using Bts.PubSub; -using bts; -using System.Linq; -//using BCG.Utilities; -//using bts; - -namespace BCG { - public class PubSubRouter : IPubSubRouter { - private Regex[] myPubRouteRegExps; - private Regex[] mySubRouteRegExps; - private PubSubRoute[] myPubRoutes; - private PubSubRoute[] mySubRoutes; - - public PubSubRouter() : this( - PubSubConfig.Instance.SubscriberRoutes?.ToArray() - ?? throw new InvalidOperationException("Subscriber routes are not configured"), - PubSubConfig.Instance.PublisherRoutes?.ToArray() - ?? throw new InvalidOperationException("Publisher routes are not configured")) { } - - public PubSubRouter(params PubSubRoute[] routes) : this(routes, routes) { } - - public PubSubRouter(PubSubRoute[] subRoutes, PubSubRoute[] pubRoutes) { - mySubRouteRegExps = new Regex[subRoutes.Length]; - myPubRouteRegExps = new Regex[pubRoutes.Length]; - - mySubRoutes = subRoutes; - myPubRoutes = pubRoutes; - - for (int i = 0; i < subRoutes.Length; ++i) - mySubRouteRegExps[i] = new Regex(subRoutes[i].tagRegExp); - for (int i = 0; i < pubRoutes.Length; ++i) - myPubRouteRegExps[i] = new Regex(pubRoutes[i].tagRegExp); - } - - private int myGetRouteIndex(string forTag, PubSubRoute[] routes, Regex[] regexes) { - for (int i = 0; i < routes.Length; i++) - if (regexes[i].IsMatch(forTag)) - return i; - - throw new PubSubRouteNotFound(String.Format("No route found for {0}", forTag)); - } - - #region IPubSubRouter methods - - private string myPickAServer(string tag, string[] urls) { - if (urls.Length == 1) - return urls[0]; - else { - uint hc = (uint)tag.GetHashCode(); - return urls[hc % urls.Length]; - } - } - - public string get_pub_url_for_tag(string tag) { - if (!myPubRoutes.TryGetFirst(r => r?.IsMatch(tag) ?? false, out var route)) { - throw new ArgumentException($"Failed to find route for tag '{tag}'", nameof(tag)); - } - Log.Gen.info($"PubSubRouter.get_sub_url_for_tag. tag: {tag} route: {route}"); - return route.serverAddress; - } - - public string get_sub_url_for_tag(string tag) { - if (!mySubRoutes.TryGetFirst(r => r?.IsMatch(tag) ?? false, out var route)) { - throw new ArgumentException($"Failed to find route for tag '{tag}'", nameof(tag)); - } - Log.Gen.info($"PubSubRouter.get_sub_url_for_tag. tag: {tag} route: {route}"); - return route.serverAddress; - } - - public List get_all_pubsub_sub_urls() => - mySubRoutes.Select(r => r.serverAddress).ToList(); - - public List get_all_pubsub_pub_urlss() => - myPubRoutes.Select(r => r.serverAddress).ToList(); - - public event PubSubTagURLChangeDelegate onSubURLTagRouteChange; - public event PubSubTagURLChangeDelegate onPubURLTagRouteChange; - - #endregion - - //this function is put here so that the events are used, in order to prevent build errors. - private void myNeverCallThisFunction() { - if (onPubURLTagRouteChange == null || onSubURLTagRouteChange == null) { - int aVar = 2; - aVar = aVar + 2; - } - } - - - } -} +using System; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; + +using BCG; +using Bts.PubSub; +using bts; +using System.Linq; +//using BCG.Utilities; +//using bts; + +namespace BCG { + public class PubSubRouter : IPubSubRouter { + // private Regex[] mySubRouteRegExps; + private PubSubRoute[] _pub_routes; + private PubSubRoute[] _sub_routes; + + public PubSubRouter() : this( + PubSubConfig.Instance.SubscriberRoutes?.ToArray() + ?? throw new InvalidOperationException("Subscriber routes are not configured"), + PubSubConfig.Instance.PublisherRoutes?.ToArray() + ?? throw new InvalidOperationException("Publisher routes are not configured")) { } + + public PubSubRouter(params PubSubRoute[] routes) : this(routes, routes) { } + + public PubSubRouter(PubSubRoute[] sub_routes, PubSubRoute[] pub_routes) { + string log_msg = String.Empty; + foreach (var route in sub_routes) { + log_msg += $" sub_route: {route}"; + } + foreach (var route in pub_routes) { + log_msg += $" pub_route: {route}"; + } + Log.Gen.info($"PubSubRouter routes: {log_msg}"); + _sub_routes = sub_routes; + _pub_routes = pub_routes; + } + + #region IPubSubRouter methods + + public IEnumerable sub_routes() { + return _sub_routes; + } + + public RemoteConnectionInfo get_pub_route_for_tag(string tag) { + if (!_pub_routes.TryGetFirst(r => r?.IsMatch(tag) ?? false, out var route)) { + throw new ArgumentException($"Failed to find route for tag '{tag}'", nameof(tag)); + } + Log.Gen.info($"PubSubRouter.get_sub_url_for_tag tag: {tag} route: {route}"); + return RemoteConnectionInfo.parse_url(route.server_address); + } + + public RemoteConnectionInfo get_sub_route_for_tag(string tag) { + if (!_sub_routes.TryGetFirst(r => r?.IsMatch(tag) ?? false, out var route)) { + throw new ArgumentException($"Failed to find route for tag '{tag}'", nameof(tag)); + } + Log.Gen.info($"PubSubRouter.get_sub_url_for_tag tag: {tag} route: {route}"); + return RemoteConnectionInfo.parse_url(route.server_address); + } + + public List get_all_pubsub_sub_urls() => + _sub_routes.Select(r => r.server_address).ToList(); + + public List get_all_pubsub_pub_urlss() => + _pub_routes.Select(r => r.server_address).ToList(); + + public event PubSubTagURLChangeDelegate onSubURLTagRouteChange; + public event PubSubTagURLChangeDelegate onPubURLTagRouteChange; + + #endregion + + //this function is put here so that the events are used, in order to prevent build errors. + private void myNeverCallThisFunction() { + if (onPubURLTagRouteChange == null || onSubURLTagRouteChange == null) { + int aVar = 2; + aVar = aVar + 2; + } + } + + + } +} diff --git a/src/DataStreamSuite/PubSub/Client/SubAddress.cs b/src/DataStreamSuite/PubSub/Client/SubAddress.cs index 7f83d1a0f..2dc937881 100644 --- a/src/DataStreamSuite/PubSub/Client/SubAddress.cs +++ b/src/DataStreamSuite/PubSub/Client/SubAddress.cs @@ -1,31 +1,31 @@ -using System; -using BCG; -//using BCG.Utilities; +// using System; +// using BCG; +// //using BCG.Utilities; -namespace BCG -{ - public class InvalidSubAddress : Exception - { - public InvalidSubAddress(string msg) : base (msg){} - } +// namespace BCG +// { +// public class InvalidSubAddress : Exception +// { +// public InvalidSubAddress(string msg) : base (msg){} +// } - public abstract class SubAddress - { - public static SubAddress decode (string s) - { - //if (s.StartsWith(TcpSubAddress.prefix)) - // return new TcpSubAddress(s); - //else if (s.StartsWith(SuperSocketAddress.prefix)) - // return new SuperSocketAddress(s); - if (s.StartsWith(MSMQSubAddress.prefix)) - return new MSMQSubAddress(s); - else if (s.StartsWith(BlutoSubAddress.prefix)) - return new BlutoSubAddress(s); - else - { - //BlueEventLog.logAssert(false, "Unknown pubsub transport for : " + s); - return null; - } - } - } -} +// public abstract class SubAddress +// { +// public static SubAddress decode (string s) +// { +// //if (s.StartsWith(TcpSubAddress.prefix)) +// // return new TcpSubAddress(s); +// //else if (s.StartsWith(SuperSocketAddress.prefix)) +// // return new SuperSocketAddress(s); +// if (s.StartsWith(MSMQSubAddress.prefix)) +// return new MSMQSubAddress(s); +// else if (s.StartsWith(BlutoSubAddress.prefix)) +// return new BlutoSubAddress(s); +// else +// { +// //BlueEventLog.logAssert(false, "Unknown pubsub transport for : " + s); +// return null; +// } +// } +// } +// } diff --git a/src/DataStreamSuite/PubSub/Config/PubSubConfig.cs b/src/DataStreamSuite/PubSub/Config/PubSubConfig.cs index 300e0d1ce..c3ca57111 100644 --- a/src/DataStreamSuite/PubSub/Config/PubSubConfig.cs +++ b/src/DataStreamSuite/PubSub/Config/PubSubConfig.cs @@ -27,35 +27,39 @@ public class PubSubConfig { [JsonPropertyName("simple_echo_server")] public bool? SimpleEchoServer { get; set; } + // unused [JsonPropertyName("milliseconds_between_sub_info_updates")] public int? MillisecondsBetweenSubInfoUpdates { get; set; } = 1000; + // unused [JsonPropertyName("milliseconds_between_time_slice_updates")] public int? MillisecondsBetweenTimeSliceUpdates { get; set; } = 5000; + // unused [JsonPropertyName("milliseconds_between_no_buffer_space_retries")] public int? MillisecondsBetweenNoBufferRetries { get; set; } = 100; + // unused [JsonPropertyName("retries_on_no_buffer_space")] public int? RetriesOnNoBufferSpace { get; set; } = 1; + // unused [JsonPropertyName("do_it_all_seconds_between_log")] public int? DoItAllSecondsBetweenLog { get; set; } = 0; - // Milliseconds + // Used by the PubSubMessageReactor to pass to the ManagedTCPMessageHb (but unsed within it) [JsonPropertyName("heartbeat_interval")] public int? HeartbeatInterval { get; set; } = 15000; [JsonPropertyName("missing_heartbeats_before_gc")] public int? MissingHeartbeatsBeforeGc { get; set; } = 50; - [JsonPropertyName("use_managed_sockets")] - public bool? UseManagedSockets { get; set; } = true; - + // unused // Milliseconds [JsonPropertyName("state_update_period")] public int? StateUpdatePeriod { get; set; } = 5000; + // unused // Milliseconds [JsonPropertyName("statistics_update_period")] public int? StatisticsUpdatePeriod { get; set; } = 5000; @@ -64,67 +68,20 @@ public class PubSubConfig { [JsonPropertyName("disposed_connection_check_period")] public int? DisposedConnectionCheckPeriod { get; set; } = 1000; - // Milliseconds - [JsonPropertyName("message_processing_warning_threshold")] - public int? MessageProcessingWarningThreshold { get; set; } = 1000; - - [JsonPropertyName("max_packet_size")] - public int? MaxPacketSize { get; set; } = 500000000; - - [JsonPropertyName("blue_comm_must_die")] - public bool? BlueCommMustDie { get; set; } = true; - - [JsonPropertyName("crushable_tags")] - public List? CrushableTags { get; set; } - [JsonPropertyName("tag_type_to_assembly_map")] public TagTypeToAssembly? TagTypeToAssemblyMap { get; set; } - [JsonPropertyName("server_queue")] - public string? ServerQueue { get; set; } = "PubSubQueue"; - - [JsonPropertyName("port_range")] - public PubSubPortRange? PortRange { get; set; } - - [JsonPropertyName("bind_to_random_port")] - public bool? BindToRandomPort { get; set; } = false; - - [JsonPropertyName("debug_tags")] - public string? DebugTags { get; set; } - + // unused [JsonPropertyName("latency_report_threshold_ms")] public int? LatencyReportThresholdMs { get; set; } - [JsonPropertyName("use_substations")] - public bool? UseSubstations { get; set; } - - [JsonPropertyName("use_dynamic_clients")] - public bool? UseDynamicClients { get; set; } - - [JsonPropertyName("is_substation")] - public bool? IsSubstation { get; set; } - + // unused [JsonPropertyName("internally_publish_sub_info")] public bool? InternallyPublishSubInfo { get; set; } - [JsonPropertyName("use_managed_clients_in_native_code")] - public bool? UseManagedClientsInNativeCode { get; set; } - [JsonPropertyName("compressed_tags")] public string? CompressedTags { get; set; } - [JsonPropertyName("tags_to_report_compression_ratio")] - public string? TagsToReportCompressionRatio { get; set; } - - [JsonPropertyName("disable_msmq")] - public bool? DisableMsmq { get; set; } - - [JsonPropertyName("use_prepublished_server_state")] - public bool? UsePrepublishedServerState { get; set; } - - [JsonPropertyName("ip_translation")] - public string? IpTranslation { get; set; } - [JsonPropertyName("gc_activation_threshold")] public int? GcActivationThreshold { get; set; } @@ -148,30 +105,14 @@ public class PubSubConfig { DoItAllSecondsBetweenLog = 0, HeartbeatInterval = 15000, MissingHeartbeatsBeforeGc = 50, - UseManagedSockets = true, StateUpdatePeriod = 5000, StatisticsUpdatePeriod = 5000, DisposedConnectionCheckPeriod = 1000, - MessageProcessingWarningThreshold = 1000, ServerPort = 12345, - MaxPacketSize = 500000000, - BlueCommMustDie = true, - CrushableTags = new(0), TagTypeToAssemblyMap = new(), - ServerQueue = "PubSubQueue", - PortRange = new(30400, 31700), - BindToRandomPort = false, - DebugTags = NOTAGS, LatencyReportThresholdMs = 1500, - UseSubstations = false, - IsSubstation = false, InternallyPublishSubInfo = true, - UseManagedClientsInNativeCode = false, CompressedTags = NOTAGS, - TagsToReportCompressionRatio = NOTAGS, - DisableMsmq = false, - UsePrepublishedServerState = false, - IpTranslation = null, GcActivationThreshold = 0, WaitPeriodAfterGc = 1000, SimpleEchoServer = false, @@ -193,30 +134,14 @@ public class PubSubConfig { DoItAllSecondsBetweenLog ??= other.DoItAllSecondsBetweenLog; HeartbeatInterval ??= other.HeartbeatInterval; MissingHeartbeatsBeforeGc ??= other.MissingHeartbeatsBeforeGc; - UseManagedSockets ??= other.UseManagedSockets; StateUpdatePeriod ??= other.StateUpdatePeriod; StatisticsUpdatePeriod ??= other.StatisticsUpdatePeriod; DisposedConnectionCheckPeriod ??= other.DisposedConnectionCheckPeriod; - MessageProcessingWarningThreshold ??= other.MessageProcessingWarningThreshold; ServerPort ??= other.ServerPort; - MaxPacketSize ??= other.MaxPacketSize; - BlueCommMustDie ??= other.BlueCommMustDie; - CrushableTags ??= other.CrushableTags; TagTypeToAssemblyMap ??= other.TagTypeToAssemblyMap; - ServerQueue ??= other.ServerQueue; - PortRange ??= other.PortRange; - BindToRandomPort ??= other.BindToRandomPort; - DebugTags ??= other.DebugTags; LatencyReportThresholdMs ??= other.LatencyReportThresholdMs; - UseSubstations ??= other.UseSubstations; - IsSubstation ??= other.IsSubstation; InternallyPublishSubInfo ??= other.InternallyPublishSubInfo; - UseManagedClientsInNativeCode ??= other.UseManagedClientsInNativeCode; CompressedTags ??= other.CompressedTags; - TagsToReportCompressionRatio ??= other.TagsToReportCompressionRatio; - DisableMsmq ??= other.DisableMsmq; - UsePrepublishedServerState ??= other.UsePrepublishedServerState; - IpTranslation ??= other.IpTranslation; GcActivationThreshold ??= other.GcActivationThreshold; WaitPeriodAfterGc ??= other.WaitPeriodAfterGc; SimpleEchoServer ??= other.SimpleEchoServer; diff --git a/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnection.cs b/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnection.cs new file mode 100644 index 000000000..0d5fbf05f --- /dev/null +++ b/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnection.cs @@ -0,0 +1,542 @@ +// using System; +// using System.Collections.Generic; +// using System.Text; +// using System.Net; +// using System.Net.Sockets; +// using System.IO; +// //using BCG.Utilities; +// using BCG.Utilities.General; +// using System.Runtime.InteropServices; + +// namespace BCG +// { +// /// +// /// This class, mantains a connection to a peer socket, using +// /// the .Net async TCP library. It sends heartbeats at regular +// /// intervals (config). It is in active states when messages +// /// are sent and received without an error state. It assumed +// /// dead state when either of the following happens +// /// BeginReceive returns a SocketError +// /// BeginSend returns a SocketError +// /// EndReceive returns a SocketError +// /// EndSend returns a SocketError +// /// As soon as it assumes dead state it stops sending or +// /// receiving any messages (including heartbeats). +// /// The user of this class can either detect that by +// /// missing heartbeats or checking the isConnected property. +// /// Missing should be the more general way, since if the +// /// peer dies in a 'silent' way, where none of the above +// /// methods indicate an error, missing heartbeats is guaranteed +// /// to detect it. +// /// +// public class AsyncTCPConnection : ITCPConnection, IWorker, IDisposable +// { +// /// +// /// This is used as a state for the Async send. Reason being +// /// that if onSend indicates that it could not send the full +// /// data (ie EndSend does not return the full size), the offset +// /// is used to resend the data +// /// +// public class AsyncMessage +// { +// public byte[] buffer; +// public int offset; +// public string messageId; +// public SendConfirmationDelegate onSendDel; + +// public AsyncMessage(byte[] theBuffer, int theOffset) +// : this(theBuffer, theOffset, String.Empty, null) { } + +// public AsyncMessage(byte[] theBuffer, int theOffset, string theMessageId, SendConfirmationDelegate theOnSendDel) +// { +// buffer = theBuffer; +// offset = theOffset; +// messageId = theMessageId; +// onSendDel = theOnSendDel; +// } + + +// public int length +// { +// get +// { +// return buffer.Length - offset; +// } +// } +// } + +// enum ReadState +// { +// readingSize, +// readingData +// }; + +// #region work around for .Net socket's LocalEndPoint bug + +// [StructLayout(LayoutKind.Sequential)] +// private struct in_addr +// { +// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] +// public byte[] sin_addr; +// } + +// [StructLayout(LayoutKind.Sequential)] +// private struct sockaddr +// { +// public short sin_family; +// public ushort sin_port; +// public in_addr sin_addr; +// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] +// public byte[] sin_zero; +// } + +// [DllImport("wsock32.dll")] +// private static extern int getsockname(IntPtr s, ref sockaddr name, ref int namelen); + +// [DllImport("wsock32.dll")] +// private static extern int getpeername(IntPtr s, ref sockaddr name, ref int namelen); + +// #endregion + +// private readonly int myMaxMessageSize = PubSub3Config.instance.PS3_MaxPacketSize; +// private RemoteConnectionInfo myPeer, mySelf; +// private Socket mySock; +// private ITCPMessageHandler myMessageHandler; + +// private byte[] myCurrentReadBuffer; +// private int myCurrentReadBufferOffset; +// private ReadState myCurrentReadState; + +// private bool myAlive = true; + +// private byte[] myHBMessage; +// private TimeSpan myHBTimeSpan; +// private MasterWorker myMasterWorker = MasterWorker.getInstance(true); +// private bool myHBReceived = false, myDataReceived = false, myHBSent = false; +// private DateTime myLastHBReceivedTime = new DateTime(1900, 1, 1); + +// public AsyncTCPConnection(Socket sock, TimeSpan heartBeatTimeSpan) +// { +// myHBTimeSpan = heartBeatTimeSpan; +// mySock = sock; +// mySock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontRoute, true); +// string ip; +// int port; +// getPeerAddress(out ip, out port); +// myPeer = new RemoteConnectionInfo(ip, port); +// getSelfAddress(out ip, out port); +// mySelf = new RemoteConnectionInfo(ip, port); +// // BlueEventLog.logEvent(String.Format("AsyncTCPConnection created : self = {0} , peer = {1}", +// // mySelf.ToString(), myPeer.ToString()), PS3LogLevels.connection); +// } + +// public override string ToString() +// { +// return String.Format("peer = {0}, self = {1}", myPeer.ToString(), mySelf.ToString()); +// } + +// #region ITCPConnection Members + +// public void sendWithConfirmation(byte[] data, ref string confId, SendConfirmationDelegate del) +// { +// confId = Guid.NewGuid().ToString(); +// byte[] msg = myBuildDataMessage(data); +// myBeginOrResumeSending(new AsyncMessage(msg, 0, confId, del)); +// } + +// public void send(byte[] data) +// { +// byte[] msg = myBuildDataMessage(data); +// myBeginOrResumeSending(new AsyncMessage(msg, 0)); +// } + +// public void register(ITCPMessageHandler messageHandler) +// { +// // BlueEventLog.logAssert(myMessageHandler == null, "Message Handler is already assigned"); +// // BlueEventLog.logEvent(String.Format("AsyncTCPConnection for peer = {0} being registered", myPeer.ToString()), +// // PS3LogLevels.connection); +// myMessageHandler = messageHandler; +// myMasterWorker.addWorker(this, myHBTimeSpan); +// myReadSize(); +// } + +// public void getPeerAddress(out string ip, out int port) +// { +// ip = ""; +// port = 0; +// if (myAlive) +// { +// IPEndPoint ipEp = mySock.RemoteEndPoint as IPEndPoint; +// ip = ipEp.Address.ToString(); +// port = ipEp.Port; +// } +// ///.Net has some problems getting the port, so using +// ///native code for that +// //sockaddr addr = new sockaddr(); +// //int namelen = 16; +// //getsockname(mySock.Handle, ref addr, ref namelen); +// //port = addr.sin_port; +// } + +// public void getSelfAddress(out string ip, out int port) +// { +// ip = ""; +// port = 0; +// if (myAlive) +// { +// IPEndPoint ipEp = mySock.LocalEndPoint as IPEndPoint; +// ip = ipEp.Address.ToString(); +// port = ipEp.Port; +// } +// ///due to this bug in .Net socket, we have to resort to +// ///native code +// //sockaddr addr = new sockaddr(); +// //int namelen = 16; +// //getsockname(mySock.Handle, ref addr, ref namelen); +// //port = addr.sin_port; +// } + +// public bool isDisposed +// { +// get { return !myAlive; } +// } + +// #endregion + +// #region IWorker Members + +// bool _last_connected = false; +// public void doWork() +// { +// if (mySock != null) +// //if (mySock.Connected != _last_connected) +// { +// Console.WriteLine($"AsyncTCPConnection.doWork connected: {mySock.Connected}"); +// _last_connected = mySock.Connected; +// } +// if (!myHBSent) +// { +// // BlueEventLog.logEvent(String.Format("Sending heartbeat to peer {0} for the first time", myPeer.ToString()), +// // PS3LogLevels.connection); +// myHBSent = true; +// } +// myBeginOrResumeSending(new AsyncMessage(myBuildHeartbeatMessage(), 0)); +// } + +// #endregion + +// #region sending data + +// private void myBeginOrResumeSending(AsyncMessage message) +// { +// if (myAlive) +// { +// try +// { +// //Console.WriteLine($"AsyncTCPConnection.myBeginOrResumeSending len: {message.length} connected: {mySock.Connected}"); +// SocketError beginSendErr; +// mySock.BeginSend(message.buffer, message.offset, message.length, SocketFlags.None, +// out beginSendErr, new AsyncCallback(myOnSend), message); +// Console.WriteLine($"AsyncTCPConnection.myBeginOrResumeSending len: {message.length} socker_error: {beginSendErr} connected: {mySock.Connected}"); +// if (beginSendErr != SocketError.Success) +// myHandleError(beginSendErr); +// } +// catch (Exception ex) +// { +// myHandleError(ex); +// } +// } +// } + +// private void myOnSend(IAsyncResult res) +// { +// if (myAlive) +// { +// try +// { +// SocketError writeErr; +// int bytesSent = mySock.EndSend(res, out writeErr); +// Console.WriteLine($"AsyncTCPConnection.myOnSend bytes: {bytesSent} writeErr: {writeErr} connected: {mySock.Connected}"); +// AsyncMessage message = res.AsyncState as AsyncMessage; +// message.offset += bytesSent; +// if (writeErr == SocketError.Success) +// { +// if (message.offset == message.buffer.Length) +// { +// // if confirmation needs to be sent +// if (String.Empty != message.messageId) +// { +// message.onSendDel(message.messageId, true); +// } +// } +// else +// { +// ///resume writing rest of the message +// // BlueEventLog.logEvent("could not send the whole message all at once , messageSize = " + +// // message.buffer.Length + " offset = " + message.offset, PS3LogLevels.info); +// myBeginOrResumeSending(message); +// } +// } +// else +// { +// myHandleError(writeErr); +// } +// } +// catch (Exception ex) +// { +// myHandleError(ex); +// } +// } +// } + +// /// +// /// Assembles the heartbeat message, and uses it for +// /// future references +// /// +// /// +// private byte[] myBuildHeartbeatMessage() +// { +// if (myHBMessage == null) +// { +// BinaryWriter bw = new BinaryWriter(new MemoryStream()); +// int sz = 4; +// int msgType = 1; +// bw.Write(sz); +// bw.Write(msgType); +// myHBMessage = (bw.BaseStream as MemoryStream).ToArray(); +// } +// return myHBMessage; +// } + +// /// +// /// Assembles the data message. This is necessary +// /// for the other side to understand the message. This can also +// /// be achieved by not forming the message and use the +// /// BeginSend (List<>) function rather than BeginSend (byte[]) +// /// +// /// +// /// +// private byte[] myBuildDataMessage(byte[] data) +// { +// BinaryWriter bw = new BinaryWriter(new MemoryStream()); +// bw.Write(data.Length + 8); +// bw.Write(0); +// bw.Write(0); ///mid for backward compatibility +// bw.Write(data); +// return (bw.BaseStream as MemoryStream).ToArray(); +// } + +// #endregion + +// #region receiving data + +// private void myReadSize() +// { +// myCurrentReadBuffer = new byte[4]; +// myCurrentReadBufferOffset = 0; +// myCurrentReadState = ReadState.readingSize; +// myBeginOrResumeReading(); +// } + +// private void myReadData(int dataSize) +// { +// myCurrentReadBuffer = new byte[dataSize]; +// myCurrentReadBufferOffset = 0; +// myCurrentReadState = ReadState.readingData; +// myBeginOrResumeReading(); +// } + +// private void myBeginOrResumeReading() +// { +// if (myAlive) +// { +// try +// { +// int beginReceiveAttempts = 0; +// while (true) +// { +// beginReceiveAttempts++; +// SocketError readSockErr; +// mySock.BeginReceive(myCurrentReadBuffer, myCurrentReadBufferOffset, +// myCurrentReadBuffer.Length - myCurrentReadBufferOffset, +// SocketFlags.None, out readSockErr, +// new AsyncCallback(myOnRead), +// myCurrentReadBuffer); +// Console.WriteLine($"AsyncTCPConnection.myBeginOrResumeReading socket_error: {readSockErr} connected: {mySock.Connected}"); +// if (readSockErr == SocketError.NoBufferSpaceAvailable) +// { +// string msg = String.Format("Not enough buffer space to receive {0} bytes. Attempt: {1} of {2}.", +// myCurrentReadBuffer.Length - myCurrentReadBufferOffset, +// beginReceiveAttempts, PubSub3Config.instance.PS3_retriesOnNoBufferSpace + 1); +// //BlueEventLog.logEvent(msg, PS3LogLevels.disconnection); + +// if (beginReceiveAttempts < (PubSub3Config.instance.PS3_retriesOnNoBufferSpace + 1)) +// System.Threading.Thread.Sleep(PubSub3Config.instance.PS3_millisecondsBetweenNoBufferSpaceRetries); +// else +// { +// //BlueEventLog.logEvent("Could not recover from NoBufferSpace condition. Breaking connection.", PS3LogLevels.disconnection); +// myHandleError(readSockErr); +// } +// } +// else if (readSockErr == SocketError.Success) +// { +// if (beginReceiveAttempts > 1) +// // BlueEventLog.logEvent(String.Format("Recovered from NoBufferSpace after {0} tries",beginReceiveAttempts-1) , +// // PS3LogLevels.disconnection); +// break; +// } +// else +// myHandleError(readSockErr); +// } +// } +// catch (Exception ex) +// { +// myHandleError(ex); +// } +// } +// } + +// private void myOnRead(IAsyncResult res) +// { +// if (myAlive) +// { +// try +// { +// SocketError readErr; +// Console.WriteLine($"AsyncTCPConnection.myOnRead pre connected: {mySock.Connected}"); +// int bytesRead = mySock.EndReceive(res, out readErr); +// Console.WriteLine($"AsyncTCPConnection.myOnRead bytes: {bytesRead} readErr: {readErr} connected: {mySock.Connected}"); +// myCurrentReadBufferOffset += bytesRead; +// if (readErr == SocketError.Success) +// { +// if (myCurrentReadBufferOffset == myCurrentReadBuffer.Length) +// { +// ///read the whole of the buffer +// if (myCurrentReadState == ReadState.readingSize) +// { +// ///the size has already been read, now convert +// ///it into an int, and start reading the data +// int dataSize = new BinaryReader(new MemoryStream(myCurrentReadBuffer)).ReadInt32(); +// if (dataSize > myMaxMessageSize) +// { +// string errMessage = "Encountered malformed message, size indicated = " + dataSize; +// //BlueEventLog.logEvent(errMessage, "Error"); +// myHandleError(new ApplicationException(errMessage)); +// } +// else +// myReadData(dataSize); +// } +// else +// { +// ///the whole data has been finally read, time to +// ///tell the subscriber about it +// BinaryReader br = new BinaryReader(new MemoryStream(myCurrentReadBuffer)); +// int msgType = br.ReadInt32(); +// if (msgType == 0) +// { +// ///skips the message ID +// br.ReadInt32(); +// byte[] data = br.ReadBytes(myCurrentReadBuffer.Length - 8); +// ///callbacks can be made through thread pool to avoid this +// ///thread from being blocked, by this callback +// if (!myDataReceived) +// { +// myDataReceived = true; +// Console.WriteLine($"AsyncTCPConnection Data received for the first time from peer {myPeer.ToString()}"); +// } +// myMessageHandler.onData(new RemoteMessage(data, RemoteMessageType.Data, myPeer)); + +// } +// else if (msgType == 1) +// { +// if (!myHBReceived) +// { +// myHBReceived = true; +// Console.WriteLine($"AsyncTCPConnection HB received for the first time from peer {myPeer.ToString()}"); +// } +// myLastHBReceivedTime = DateTime.Now; +// myMessageHandler.onData(new RemoteMessage(null, RemoteMessageType.Heartbeat, myPeer)); +// } +// myReadSize(); +// } +// } +// else +// { +// ///still part of the buffer left to read +// ///continue reading +// myBeginOrResumeReading(); +// } +// } +// else +// { +// myHandleError(readErr); +// } +// } +// catch (Exception ex) +// { +// myHandleError(ex); +// } +// } +// } + +// #endregion + +// #region IDisposable Members + +// public void Dispose() +// { +// Console.WriteLine("AsyncTCPConnection.Dispose()"); +// lock (this) +// { +// if (myAlive) +// { +// myMasterWorker.removeWorker(this); +// myAlive = false; +// // BlueEventLog.logEvent(String.Format("AsycnTCPConnection with peer {0} being disposed, last HB was received at {1}" , +// // myPeer.ToString(), myLastHBReceivedTime.ToLongTimeString()), +// // PS3LogLevels.disconnection); +// try +// { +// mySock.Close(); +// } +// catch (Exception ex) +// { +// String.Format("Exception of type {0} thrown while trying to close socket connected to {1} , with" + +// " the following exception msg {2}", ex.GetType().ToString(), myPeer.ToString(), ex.Message); +// //BlueEventLog.logEvent(ex); +// if (ex is OutOfMemoryException) +// throw ex; +// } +// } +// } +// } + +// #endregion + +// private void myHandleError(object err) +// { +// lock (this) +// { +// string errMsg = ""; +// if (err is Exception) +// { +// errMsg = String.Format("AsyncTCPConnection.Dispose Encountered an exception of type '{0}' on the socket connected to ip = {1} , port = {2} ; " + +// "Exception message = {3} , if the socket has not been disposed, it will be disposed now", err.GetType(), myPeer.ip, myPeer.port, (err as Exception).Message); +// if (err is OutOfMemoryException) +// throw (err as OutOfMemoryException); +// } +// else if (err is SocketError) +// { +// errMsg = String.Format("AsyncTCPConnection.Dispose Encountered a SocketError of type '{0}' on the socket connected to ip = {1} , port = {2} ; " + +// "if the socket has not been disposed, it will be disposed now", err.ToString(), myPeer.ip, myPeer.port); +// Console.WriteLine($"AsyncTCPConnection.myHandleError errMsg: {errMsg}"); +// } +// //BlueEventLog.logEvent(errMsg, PS3LogLevels.disconnection); +// if (myAlive) +// { +// Dispose(); +// } +// } +// } +// } +// } \ No newline at end of file diff --git a/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnection2.cs b/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnection2.cs new file mode 100644 index 000000000..48e5d7d96 --- /dev/null +++ b/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnection2.cs @@ -0,0 +1,248 @@ +// using BCG; + +// using Google.Protobuf; + +// using System; +// using System.IO; +// using System.Linq; +// using System.Net; +// using System.Net.Sockets; +// using System.Runtime.CompilerServices; +// using System.Text; +// using System.Threading.Tasks; +// using BCG; +// using System.Xml.Serialization; +// using System.Reflection; +// using BCG.Utilities.General; +// using System.Net.WebSockets; + +// namespace BCG { + +// public class AsyncTCPConnection2 : ITCPConnection, IWorker, IDisposable { +// private Socket _socket; +// // tied to the socket above +// private NetworkStream _nw_stream; +// private readonly ConnectionSide _side; +// ITCPMessageHandler _message_handler; +// private int _msg_id = 0; +// RemoteConnectionInfo _peer_address; +// RemoteConnectionInfo _self_address; +// private TimeSpan _hb_period = TimeSpan.FromSeconds(1); +// private DateTime _last_hb_sent = DateTime.MinValue; +// private DateTime _last_hb_received = DateTime.MaxValue; +// private static byte _msg_type_data = 1; +// private static byte _msg_type_hb = 0; +// private bool _is_disposed = false; +// SyncQueue _data_send_queue = new SyncQueue(); + +// public class QueuedMessage { +// public string id; +// public SendConfirmationDelegate del; +// public byte[] data; + +// public QueuedMessage(string id, SendConfirmationDelegate del, byte[] data) { +// id = id; +// del = del; +// data = data; +// } + +// public QueuedMessage(byte[] data) +// : this(String.Empty, null, data) { } + +// } + +// public enum ConnectionSide { +// Client, +// Server +// } + +// public AsyncTCPConnection2(Socket socket, ConnectionSide side) { +// _socket = socket; +// _nw_stream = new NetworkStream(socket); +// _side = side; +// IPEndPoint r_ep = socket.RemoteEndPoint as IPEndPoint; +// _peer_address = new RemoteConnectionInfo(r_ep.Address.ToString(), r_ep.Port); + +// var loc_ep = socket.LocalEndPoint as IPEndPoint; +// _self_address = new RemoteConnectionInfo(loc_ep.Address.ToString(), loc_ep.Port); +// } + +// public void register(ITCPMessageHandler message_handler) { +// _message_handler = message_handler; +// Task.Run(async () => _keep_reading()); +// Task.Run(async () => await _keep_sending()); +// //_keep_reading(); +// // if add a _keep_sending threadis added then we can maek send a non async +// // methid making it much easier to integrate with the rest +// } + +// // this thread pulls +// private async Task _keep_sending() { +// bts.Log.Gen.info($"TCPConnection._keep_sending starting"); +// while (!_is_disposed) { +// try { +// QueuedMessage m = _data_send_queue.dequeue(100); +// if (m == null) { +// continue; +// } +// await send_async(m.data); +// if (String.IsNullOrEmpty(m.id)) { +// m.del(m.id, true); +// } +// } catch (Exception ex) { +// bts.Log.Gen.error($"TCPConnection._keep_sending ex: {ex.Message}"); +// await Task.Delay(100); +// _handle_error(ex); +// } +// } +// } + +// private async Task _keep_reading() { +// bts.Log.Gen.info($"TCPConnection._keep_reading starting"); +// while (!_is_disposed) { +// try { +// byte[] msg = await TCPSocketUtils.read_bytes_async(_nw_stream); +// bts.Log.Gen.info($"AsyncTCPConnection2._keep_reading side: {_side} self: {get_self_address()} peer: {get_peer_address()} msg len: {msg.Length}"); +// await _handle_msg(msg); +// } catch (Exception ex) { +// bts.Log.Gen.error($"TCPConnection._keep_reading ex: {ex.Message}"); +// await Task.Delay(100); +// _handle_error(ex); +// } +// } +// } + +// private async Task _handle_msg(byte[] msg) { +// // read the first byte to read the msg type and deal with it accordingly +// BinaryReader br = new BinaryReader(new MemoryStream(msg)); +// byte msg_type = br.ReadByte(); +// if (msg_type == _msg_type_data) { +// byte[] data = br.ReadBytes(msg.Length - 1); +// RemoteMessage m = new RemoteMessage(data, RemoteMessageType.Data, _peer_address); +// _message_handler.onData(m); +// } else { +// RemoteMessage m = new RemoteMessage(null, RemoteMessageType.Heartbeat, _peer_address); +// _message_handler.onData(m); +// } +// } + +// // not very efficient +// private static byte[] _prefix_msg_type(byte[] data) { +// MemoryStream ms = new MemoryStream(); +// BinaryWriter bw = new BinaryWriter(ms); +// bw.Write(_msg_type_data); +// bw.Write(data); +// ms.Position = 0; +// return ms.ToArray(); +// } + +// private async void _handle_error(Exception ex) { +// bts.Log.Gen.error($"TCPConnection._handle_error ex: {ex}"); +// try { +// var socket = _nw_stream.Socket; +// socket.Close(); +// socket.Dispose(); +// } catch (Exception ex2) { +// bts.Log.Gen.error($"TCPConnection._handle_error got exception when closing Socket ex: {ex}"); +// } +// _is_disposed = true; +// RemoteMessage rm = new RemoteMessage(new byte[] { }, RemoteMessageType.Disconnection, _peer_address); +// _message_handler.onData(rm); +// } + +// public void send_with_confirmation(byte[] data, string confId, SendConfirmationDelegate del) { } + +// public async Task send_with_confirmation_async(byte[] data, string conf_id, SendConfirmationDelegate del) { +// try { +// conf_id = (++_msg_id).ToString(); +// await TCPSocketUtils.send_bytes_async(_nw_stream, data); +// del(conf_id, true); +// } catch (Exception ex) { +// _handle_error(ex); +// } +// } + +// public void sendWithConfirmation(byte[] data, ref string conf_id, SendConfirmationDelegate del) { +// conf_id = (++_msg_id).ToString(); +// send(data); +// del(conf_id, true); +// } + +// public void send(byte[] data) { +// Task.Run(async () => await send_async(data)); +// bts.Log.Gen.info($"AsyncTCPConnection2.send self: {get_self_address()} peer: {get_peer_address()} msg len: {data.Length} sent successfully"); +// //_data_send_queue.enqueue(new QueuedMessage(data)); +// } + +// public async Task send_async(byte[] data) { +// // prefix 4 bytes for type (data vs hb) +// MemoryStream str = new MemoryStream(); +// BinaryWriter bw = new BinaryWriter(str); +// bw.Write(_msg_type_data); +// bw.Write(data); +// try { +// await TCPSocketUtils.send_bytes_async(_nw_stream, str.ToArray()); +// } catch (Exception ex) { +// bts.Log.Gen.error($"AsyncTCPConnection2.send_async ex: {ex}"); +// _handle_error(ex); +// } +// } + +// public void getPeerAddress(out string ip, out int port) { +// ip = _peer_address.ip; +// port = _peer_address.port; +// ///.Net has some problems getting the port, so using +// ///native code for that +// //sockaddr addr = new sockaddr(); +// //int namelen = 16; +// //getsockname(mySock.Handle, ref addr, ref namelen); +// //port = addr.sin_port; +// } + +// public RemoteConnectionInfo get_peer_address() { +// string ip; int port; +// getPeerAddress(out ip, out port); +// return new RemoteConnectionInfo(ip, port); +// } + +// public RemoteConnectionInfo get_self_address() { +// string ip; int port; +// getSelfAddress(out ip, out port); +// return new RemoteConnectionInfo(ip, port); +// } + + +// public void getSelfAddress(out string ip, out int port) { +// ip = _self_address.ip; +// port = _self_address.port; +// } + +// private async void _send_hb() { +// if (_last_hb_sent - DateTime.Now > _hb_period) { +// MemoryStream ms = new MemoryStream(); +// BinaryWriter bw = new BinaryWriter(ms); +// bw.Write(_msg_type_hb); +// ms.Position = 0; +// byte[] hb_msg = ms.ToArray(); +// await TCPSocketUtils.send_bytes_async(_nw_stream, hb_msg); +// } +// } + +// public void doWork() { +// _send_hb(); +// } + +// public void Dispose() { +// _nw_stream.Close(); +// _nw_stream.Dispose(); +// _is_disposed = true; +// } + +// public bool isDisposed { +// get { +// return _is_disposed; +// } +// } + +// } +// } \ No newline at end of file diff --git a/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnectionAcceptor_APM.cs b/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnectionAcceptor_APM.cs index 48bc7db0b..ab5f4dea4 100644 --- a/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnectionAcceptor_APM.cs +++ b/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnectionAcceptor_APM.cs @@ -15,6 +15,7 @@ namespace bts { private ITCPConnectionHandler _connection_handler; private HashSet _key_map = new HashSet(); public AsyncTCPConnectionAcceptor_APM(int port, ITCPConnectionHandler connection_handler) { + Log.Gen.info($"AsyncTCPConnectionAcceptor_APM. cons started on port: {port}"); _port = port; _connection_handler = connection_handler; } @@ -25,7 +26,9 @@ namespace bts { } private void _init() { + Log.Gen.info($"AsyncTCPConnectionAcceptor_APM._init started on port: {_port}"); _accept_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + TCPSocketUtils.set_server_socket_options(ref _accept_socket); IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, _port); _accept_socket.Bind(endpoint); _accept_socket.Listen(250); @@ -33,6 +36,7 @@ namespace bts { private void _begin_accepting() { var accept_key = Guid.NewGuid().ToString(); + Log.Gen.info($"AsyncTCPConnectionAcceptor_APM._begin_accepting port: {_port} accept_key: {accept_key}"); var res = _accept_socket.BeginAccept(new AsyncCallback(_on_accept), accept_key); if (res != null && res.IsCompleted && res.CompletedSynchronously) _on_accept(res); @@ -62,11 +66,8 @@ namespace bts { _connection_handler.onConnection(newConn); // go back to accepting more conns _begin_accepting(); - string ip; int port; - newConn.getPeerAddress(out ip, out port); - string connMsg = String.Format("Connection to port {2} made from {0}:{1}", ip, port, _port); - // BlueEventLog.logEvent(connMsg, PS3LogLevels.connection); - //Console.WriteLine(connMsg); + var peer_rci = newConn.get_peer_address(); + Log.Gen.info($"AsyncTCPConnectionAcceptor_APM._on_accept peer_rci: {peer_rci}"); } diff --git a/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnectionAcceptor_AsyncWrapper.cs b/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnectionAcceptor_AsyncWrapper.cs new file mode 100644 index 000000000..856839e5e --- /dev/null +++ b/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnectionAcceptor_AsyncWrapper.cs @@ -0,0 +1,58 @@ +using System.Net.Sockets; +using System.Net; + +using BCG; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + + +namespace bts { + + // opens a TCP port and starts listening to connections. Unlike AsyncTCPConnectionAcceptor_APM, + // it uses TcpListener, instead of raw sockets. + public class AsyncTCPConnectionAcceptor_AsyncWrapper { + private readonly int _accept_port; + private Socket _accept_socket; + private ITCPConnectionHandler _connection_handler; + private TcpListener _server; + private Action _cbs = (c) => { }; + + public AsyncTCPConnectionAcceptor_AsyncWrapper(int accept_port, ITCPConnectionHandler connection_handler) { + Log.Gen.info($"AsyncTCPConnectionAcceptor_AsyncWrapper.cons started on port: {accept_port}"); + _accept_port = accept_port; + _connection_handler = connection_handler; + } + + public void resgiter_callback(Action cb) { + _cbs += cb; + } + + public void start() { + Log.Gen.info($"AsyncTCPConnectionAcceptor_AsyncWrapper._init started on port: {_accept_port}"); + _server = new TcpListener(IPAddress.Any, _accept_port); + _server.Start(); + Task.Run(() => _accept_connections_forever()); + } + + private void _accept_connections_forever() { + Log.Gen.info($"AsyncTCPConnectionAcceptor_AsyncWrapper._begin_accepting port: {_accept_port}"); + while (true) { + // this is a blocking call + Log.Gen.info($"AsyncTCPConnectionAcceptor_AsyncWrapper._begin_accepting port: {_accept_port} starting blocking call AcceptTcpClient"); + TcpClient tcp_client = _server.AcceptTcpClient(); + ITCPConnection conn = _create_connection(tcp_client); + Log.Gen.info($"AsyncTCPConnectionAcceptor_AsyncWrapper._begin_accepting port: {_accept_port}, new connection, self: {conn.get_self_address()} peer: {conn.get_peer_address()} calling onConnection now"); + _connection_handler.onConnection(conn); + } + //_cbs(conn); + } + + private static ITCPConnection _create_connection(TcpClient tcp_client) { + ITCPConnection conn = new AsyncTCPConnection_AsyncWrapper(tcp_client); + // ITCPConnection conn = new AsyncTCPConnection_APM(tcp_client.GetStream().Socket, TimeSpan.FromSeconds(1), ITCPConnection.ConnectionSide.Client); + return conn; + } + } + +} \ No newline at end of file diff --git a/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnection_APM.cs b/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnection_APM.cs index afc506d11..f7da41f20 100644 --- a/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnection_APM.cs +++ b/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnection_APM.cs @@ -36,14 +36,17 @@ using System.Linq; using Bts.PubSub; using Spark.Core; -namespace bts { - public class AsyncTCPConnection_APM : ITCPConnection, IWorker, IDisposable { +namespace bts +{ + public class AsyncTCPConnection_APM : ITCPConnection, IWorker, IDisposable + { // this class is used as the argument of the completion function for BeginSend/Receive // serves as the base class for both Send and ReeceiveMessage classes. // since both TCP sends and receives happen in multiple transfers, this // provides a wrapper around copying the partial transfers into the complete buffer - public class AsyncMessageBase { + public class AsyncMessageBase + { readonly string msg_id = Guid.NewGuid().ToString(); // every BeginSend or BeginReceive has a unique key associated with it public int key; @@ -55,37 +58,45 @@ namespace bts { public int transfer_ptr; protected int _n_transfers = 0; public bool completed_sync = false; - public AsyncMessageBase(byte[] the_buffer, int the_offset) { + public AsyncMessageBase(byte[] the_buffer, int the_offset) + { buffer = the_buffer; transfer_ptr = the_offset; } - public int remaining_size { - get { + public int remaining_size + { + get + { return buffer.Length - transfer_ptr; } } public int original_size => buffer.Length; - public void advance_transfer_pointer(int advance_by) { + public void advance_transfer_pointer(int advance_by) + { transfer_ptr += advance_by; _n_transfers++; - if (transfer_ptr > original_size) { + if (transfer_ptr > original_size) + { bts.Log.Gen.error($"transfer went beyond initial size {ToString()}"); } // TODO: log if it goes past the buffer } - public bool fully_transfered() { + public bool fully_transfered() + { return transfer_ptr >= original_size; } - public override string ToString() { + public override string ToString() + { return $"{GetType().ToString()} msg_id: {msg_id} key: {key} original_length: {original_size} transfer_ptr: {transfer_ptr} n_transfers: {_n_transfers} " + $"fully_transfered: {fully_transfered()} completed_sync: {completed_sync}"; } } - public class AsyncSendMessage : AsyncMessageBase { + public class AsyncSendMessage : AsyncMessageBase + { public string message_id; public SendConfirmationDelegate on_send_del; //private int _n_transfers = 0; @@ -94,35 +105,43 @@ namespace bts { : this(the_buffer, the_offset, String.Empty, null) { } public AsyncSendMessage(byte[] the_buffer, int the_transfer_ptr, string the_message_id, SendConfirmationDelegate the_on_send_del) - : base(the_buffer, the_transfer_ptr) { + : base(the_buffer, the_transfer_ptr) + { message_id = the_message_id; on_send_del = the_on_send_del; } - public override string ToString() { + public override string ToString() + { return base.ToString(); } } - public class AsyncReceiveMessage : AsyncMessageBase { - public enum ReadState { + public class AsyncReceiveMessage : AsyncMessageBase + { + public enum ReadState + { reading_size, reading_data }; readonly ReadState read_state; public AsyncReceiveMessage(int size, ReadState the_read_state) : - this(new byte[size], 0, the_read_state) { } + this(new byte[size], 0, the_read_state) + { } public AsyncReceiveMessage(byte[] the_buffer, int the_transfer_ptr, ReadState the_read_state) - : base(the_buffer, the_transfer_ptr) { + : base(the_buffer, the_transfer_ptr) + { read_state = the_read_state; } - public int read_int32(int start_idx = 0) { + public int read_int32(int start_idx = 0) + { return BitConverter.ToInt32(buffer, start_idx); } - public byte[] read_bytes(int start_idx) { + public byte[] read_bytes(int start_idx) + { byte[] rv = new byte[buffer.Length - start_idx]; Array.Copy(buffer, start_idx, rv, 0, rv.Length); return rv; @@ -131,16 +150,19 @@ namespace bts { public bool is_reading_size() => read_state == ReadState.reading_size; } - public class ErrorMessage { + public class ErrorMessage + { public readonly SocketError? socket_error = null; public readonly Exception exception = null; public readonly bool is_exception = false; public readonly string context = String.Empty; - public ErrorMessage(SocketError socket_error_, string context_) { + public ErrorMessage(SocketError socket_error_, string context_) + { socket_error = socket_error_; context = context_; } - public ErrorMessage(Exception exception_, string context_) { + public ErrorMessage(Exception exception_, string context_) + { is_exception = true; exception = exception_; context = context_; @@ -148,46 +170,20 @@ namespace bts { public bool oom => exception != null && exception is OutOfMemoryException; - public override string ToString() { + public override string ToString() + { if (is_exception) return $"ErrorMessage exception: {exception} context: {context}"; return $"socket_error: {socket_error} context: {context}"; } - - } - #region work around for .Net socket's LocalEndPoint bug - - // [StructLayout(LayoutKind.Sequential)] - // private struct in_addr { - // [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] - // public byte[] sin_addr; - // } - - // [StructLayout(LayoutKind.Sequential)] - // private struct sockaddr { - // public short sin_family; - // public ushort sin_port; - // public in_addr sin_addr; - // [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] - // public byte[] sin_zero; - // } - - // [DllImport("wsock32.dll")] - // private static extern int getsockname(IntPtr s, ref sockaddr name, ref int namelen); - - // [DllImport("wsock32.dll")] - // private static extern int getpeername(IntPtr s, ref sockaddr name, ref int namelen); - - #endregion - private const int DATA_MSG_SIGNAL = 0; private const int HB_MSG_SIGNAL = 1; private int _send_key = 0, _receive_key = 0; private HashSet _read_key_map = new HashSet(), _send_key_map = new HashSet(); - private readonly int _max_msg_size = PubSubConfig.Instance.MaxPacketSize.assert_value(); + private readonly int _max_msg_size = Int32.MaxValue;// PubSubConfig.Instance.MaxPacketSize.assert_value(); private readonly RemoteConnectionInfo _peer_conn_info, _self_conn_info; private readonly ITCPConnection.ConnectionSide _connection_side; private readonly Socket _sock; @@ -201,38 +197,69 @@ namespace bts { private bool _hb_received_yet = false, _data_received_yet = false, _hb_sent_once = false; private DateTime _last_hb_received_time = new DateTime(1900, 1, 1); - public AsyncTCPConnection_APM(Socket sock, TimeSpan hb_period, ITCPConnection.ConnectionSide connection_side) { + public AsyncTCPConnection_APM(Socket sock, TimeSpan hb_period, ITCPConnection.ConnectionSide connection_side) + { _sock = sock; _hb_period = hb_period; _connection_side = connection_side; _sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontRoute, true); - string ip; - int port; - getPeerAddress(out ip, out port); - _peer_conn_info = new RemoteConnectionInfo(ip, port); - getSelfAddress(out ip, out port); - _self_conn_info = new RemoteConnectionInfo(ip, port); + #region testing options + switch (connection_side) + { + case ITCPConnection.ConnectionSide.Server: + TCPSocketUtils.set_server_socket_options(ref _sock); + break; + case ITCPConnection.ConnectionSide.Client: + TCPSocketUtils.set_client_socket_options(ref _sock); + break; + } + #endregion + _peer_conn_info = get_peer_address(); + _self_conn_info = get_self_address(); bts.Log.Gen.info($"AsyncTCPConnection_APM created {ToString()}"); + _detect_connection_status_change(); } - public override string ToString() { + private void _detect_connection_status_change() + { + Action testing_func = () => + { + bool connected = _sock.Connected; + while (true) + { + if (connected != _sock.Connected) + Log.Gen.error($"Connection status changed this: {ToString()} {connected} -> {_sock.Connected}"); + connected = _sock.Connected; + System.Threading.Thread.Sleep(50); + } + }; + ThreadPool.QueueUserWorkItem(_ => testing_func()); + } + + public override string ToString() + { return $"AsyncTCPConnection_APM side: {_connection_side} peer: {_peer_conn_info}, self: {_self_conn_info}"; } #region ITCPConnection Members - public void sendWithConfirmation(byte[] data, ref string conf_id, SendConfirmationDelegate del) { + public void sendWithConfirmation(byte[] data, ref string conf_id, SendConfirmationDelegate del) + { conf_id = Guid.NewGuid().ToString(); byte[] msg = _build_data_message(data); _begin_or_resume_sending(new AsyncSendMessage(msg, 0, conf_id, del)); } - public void send(byte[] data) { + public void send(byte[] data) + { + //Log.Gen.info($"AsyncTCPConnection_APM.send data: {AsyncTCPConnection_AsyncWrapper.to_hex(data, 0, data.Length)}"); byte[] msg = _build_data_message(data); + //Log.Gen.info($"AsyncTCPConnection_APM.send msg: {AsyncTCPConnection_AsyncWrapper.to_hex(msg, 0, msg.Length)}"); _begin_or_resume_sending(new AsyncSendMessage(msg, 0)); } - public void register(ITCPMessageHandler messageHandler) { + public void register(ITCPMessageHandler messageHandler) + { bts.Log.assert_d(_message_handler == null, "Message Handler is already assigned"); //bts.Log.Gen.info($"AsyncTCPConnection_APM for peer = {_peer_conn_info} being registered"); _message_handler = messageHandler; @@ -241,27 +268,18 @@ namespace bts { _read_next_msg(); } - public void getPeerAddress(out string ip, out int port) { - ip = ""; - port = 0; - if (_is_alive) { - IPEndPoint ipEp = _sock.RemoteEndPoint as IPEndPoint; - port = ipEp.Port; - ip = ipEp.Address.ToString(); - } + public RemoteConnectionInfo get_peer_address() + { + return TCPSocketUtils.get_peer_address(_sock); } - public void getSelfAddress(out string ip, out int port) { - ip = ""; - port = 0; - if (_is_alive) { - IPEndPoint ipEp = _sock.LocalEndPoint as IPEndPoint; - ip = ipEp.Address.ToString(); - port = ipEp.Port; - } + public RemoteConnectionInfo get_self_address() + { + return TCPSocketUtils.get_peer_address(_sock); } - public bool isDisposed { + public bool isDisposed + { get { return !_is_alive; } } @@ -270,12 +288,14 @@ namespace bts { #region IWorker Members bool _last_connected = false; - public void doWork() { + public void doWork() + { if (!_is_alive) return; return; // disable hbs for now - if (!_hb_sent_once) { + if (!_hb_sent_once) + { bts.Log.Gen.info("Sending heartbeat to peer {_peer_conn_info} for the first time"); _hb_sent_once = true; } @@ -283,12 +303,14 @@ namespace bts { _begin_or_resume_sending(new AsyncSendMessage(msg, 0)); } - private static int _tid() { + private static int _tid() + { var tid = System.Threading.Thread.CurrentThread.ManagedThreadId; return tid; } - private static string _cb_txt(IAsyncResult res) { + private static string _cb_txt(IAsyncResult res) + { return $"completed?: {res.IsCompleted} sync?: {res.CompletedSynchronously}"; } @@ -296,10 +318,13 @@ namespace bts { #region sending data - private void _begin_or_resume_sending(AsyncSendMessage message) { + private void _begin_or_resume_sending(AsyncSendMessage message) + { //bts.Log.Gen.info($"AsyncTCPConnection_APM._begin_or_resume_sending this: {ToString()} tid: {_tid()} message: {message} _is_alive: {_is_alive}"); - if (_is_alive) { - try { + if (_is_alive) + { + try + { SocketError begin_send_err; // since we get message on on_send we dont need to keep the state around message.key = _send_key++; @@ -307,35 +332,45 @@ namespace bts { out begin_send_err, new AsyncCallback(BeginSend_callback_function), message); if (begin_send_err != SocketError.Success) _handle_error(new ErrorMessage(begin_send_err, "_begin_or_resume_sending")); - } catch (Exception ex) { + } + catch (Exception ex) + { _handle_error(new ErrorMessage(ex, "_begin_or_resume_sending")); } } } - private void BeginSend_callback_function(IAsyncResult res) { - if (res.CompletedSynchronously) { + private void BeginSend_callback_function(IAsyncResult res) + { + if (res.CompletedSynchronously) + { ThreadPool.QueueUserWorkItem(_ => _on_send_async(res)); - } else + } + else _on_send_async(res); } - private void _on_send_async(IAsyncResult res) { + private void _on_send_async(IAsyncResult res) + { AsyncSendMessage message = res.AsyncState as AsyncSendMessage; - if (_send_key_map.Contains(message.key)) { + if (_send_key_map.Contains(message.key)) + { bts.Log.Gen.warn($"AsyncTCPConnection_APM._on_send key: {message.key} already handled"); return; } _send_key_map.Add(message.key); // bts.Log.Gen.info($"AsyncTCPConnection_APM._on_send: pre endSend this: {ToString()} tid: {_tid()} " + // $"res: {_cb_txt(res)} message: {res.AsyncState} _is_alive: {_is_alive}"); - if (_is_alive) { - try { + if (_is_alive) + { + try + { SocketError send_err; int bytes_sent = _sock.EndSend(res, out send_err); //message.offset += bytesSent; message.advance_transfer_pointer(bytes_sent); - if (bytes_sent == 0) { + if (bytes_sent == 0) + { bts.Log.Gen.error($"AsyncTCPConnection_APM._on_send this: {this} sent 0 bytes, throwing exception"); _handle_error(new ErrorMessage(new ApplicationException("Sent 0 bytes, peer socket is likely shutdown"), "_on_send")); @@ -343,22 +378,31 @@ namespace bts { } bts.Log.Gen.info($"AsyncTCPConnection_APM._on_send: post endSend this: {ToString()} tid: {_tid()} res: {_cb_txt(res)} " + $"message: {res.AsyncState} bytes_sent: {bytes_sent} _is_alive: {_is_alive} send_err: {send_err}"); - if (send_err == SocketError.Success) { + if (send_err == SocketError.Success) + { // successful send of some bytes //if (message.offset == message.buffer.Length) { - if (message.fully_transfered()) { + if (message.fully_transfered()) + { // fully sent, if confirmation needs to be sent out - if (!String.IsNullOrEmpty(message.message_id)) { + if (!String.IsNullOrEmpty(message.message_id)) + { message.on_send_del(message.message_id, true); } - } else { + } + else + { // there is more to send _begin_or_resume_sending(message); } - } else { + } + else + { _handle_error(new ErrorMessage(send_err, "_on_send")); } - } catch (Exception ex) { + } + catch (Exception ex) + { _handle_error(new ErrorMessage(ex, "_on_send")); } } @@ -369,8 +413,10 @@ namespace bts { /// future references /// /// - private byte[] _build_hb_message() { - if (_cached_hb_message == null) { + private byte[] _build_hb_message() + { + if (_cached_hb_message == null) + { BinaryWriter bw = new BinaryWriter(new MemoryStream()); // the total msg =[msg_sz, msg_type] int msg_sz = 4; @@ -382,45 +428,54 @@ namespace bts { } // writes size prefixed msg - private byte[] _build_data_message(byte[] data) { + private byte[] _build_data_message(byte[] data) + { // TODO, avoid unecessary memory creation (write directly into byte[] using BitConverter) - BinaryWriter bw = new BinaryWriter(new MemoryStream()); + MemoryStream str = new MemoryStream(); + BinaryWriter bw = new BinaryWriter(str); // the total msg =[msg_sz, msg_type, data] - var msg_sz = data.Length + 4; + Int32 msg_sz = data.Length + 4; bw.Write(msg_sz); // +4 for the type of msg - // to indicate data vs hb + // to indicate data vs hb bw.Write(DATA_MSG_SIGNAL); // for data - // if we want to id every message, this is the place to do it + // if we want to id every message, this is the place to do it bw.Write(data); - return (bw.BaseStream as MemoryStream).ToArray(); + str.Position = 0; //not needed really + return str.ToArray(); } #endregion #region receiving data - private void _read_next_msg() { + private void _read_next_msg() + { _read_size(); } - private void _read_size() { + private void _read_size() + { _begin_or_resume_reading(new AsyncReceiveMessage(4, AsyncReceiveMessage.ReadState.reading_size)); } - private void _read_data(int data_size) { + private void _read_data(int data_size) + { // TODO, this could be a problem is the size is too big - maybe read it in chunks (later) _begin_or_resume_reading(new AsyncReceiveMessage(data_size, AsyncReceiveMessage.ReadState.reading_data)); } - private static string IAsyncResult_txt(IAsyncResult res) { + private static string IAsyncResult_txt(IAsyncResult res) + { return $"IsCompleted: {res.IsCompleted} CompletedSynchronously: {res.CompletedSynchronously}"; } - private void _begin_or_resume_reading(AsyncReceiveMessage rcv_msg) { + private void _begin_or_resume_reading(AsyncReceiveMessage rcv_msg) + { //bts.Log.Gen.info($"AsyncTCPConnection_APM._begin_or_resume_reading: this: {ToString()} tid: {_tid()} message: {rcv_msg} _is_alive: {_is_alive}"); if (!_is_alive) return; - try { + try + { SocketError read_sock_err; rcv_msg.key = _receive_key++; var res = _sock.BeginReceive(rcv_msg.buffer, rcv_msg.transfer_ptr, @@ -428,64 +483,94 @@ namespace bts { SocketFlags.None, out read_sock_err, new AsyncCallback(BeginReceive_callback_function), rcv_msg); - if (read_sock_err != SocketError.Success) { + if (read_sock_err != SocketError.Success) + { bts.Log.Gen.error($"_begin_or_resume_reading this: {this} error: {read_sock_err} rcv_msg: {rcv_msg}"); _handle_error(new ErrorMessage(read_sock_err, "_beging_or_resume_reading")); } - } catch (Exception ex) { + } + catch (Exception ex) + { _handle_error(new ErrorMessage(ex, "_beging_or_resume_reading")); } } + private void _log_incoming_msg(IAsyncResult res) + { + // AsyncReceiveMessage rcv_message = res.AsyncState as AsyncReceiveMessage; + // var buff_txt = AsyncTCPConnection_AsyncWrapper.to_hex(rcv_message.buffer, 0, rcv_message.buffer.Length); + // Log.Gen.info($"BeginReceive_callback_function _log_incoming_msg buff: {buff_txt}"); + + } + // this is the function passed to BeginReceive, we - private void BeginReceive_callback_function(IAsyncResult res) { - if (res.CompletedSynchronously) { + private void BeginReceive_callback_function(IAsyncResult res) + { + _log_incoming_msg(res); + if (res.CompletedSynchronously) + { ThreadPool.QueueUserWorkItem(_ => _on_read_async(res)); - } else + } + else _on_read_async(res); } // this will always be called on the non main-thread. the reason this is on its own thread is that this function ends up // calling _begin_or_resume_reading, which in tuns calls _on_read_async. So to not cause a stack overflow, this is broken // always called on a different thread than _begin_or_resume_reading - private void _on_read_async(IAsyncResult res) { + private void _on_read_async(IAsyncResult res) + { AsyncReceiveMessage rcv_message = res.AsyncState as AsyncReceiveMessage; - if (_read_key_map.Contains(rcv_message.key)) { + if (_read_key_map.Contains(rcv_message.key)) + { bts.Log.Gen.warn($"AsyncTCPConnection_APM._on_read key: {rcv_message.key} already handled"); return; } _read_key_map.Add(rcv_message.key); if (!_is_alive) return; - try { + try + { SocketError read_err; Log.Gen.info($"AsyncTCPConnection_APM._on_read pre-EndReceive rcv_message: {rcv_message} res: {IAsyncResult_txt(res)}"); int bytes_read = _sock.EndReceive(res, out read_err); rcv_message.advance_transfer_pointer(bytes_read); Log.Gen.info($"AsyncTCPConnection_APM._on_read post-EndReceive rcv_message: {rcv_message} res: {IAsyncResult_txt(res)} bytes_read: {bytes_read}"); - if (bytes_read == 0) { + if (bytes_read == 0) + { bts.Log.Gen.error($"AsyncTCPConnection_APM._on_read this: {this} read 0 bytes, throwing exception"); + //bts.Log.Gen.error($"AsyncTCPConnection_APM._on_read this: {this} read 0 bytes, sleeping and ignoring"); + //System.Threading.Thread.Sleep(50); _handle_error(new ErrorMessage(new ApplicationException("Read 0 bytes, peer socket is likely shutdown"), "_on_read")); return; } //return; - if (read_err == SocketError.Success) { - if (rcv_message.fully_transfered()) { - if (rcv_message.is_reading_size()) { + if (read_err == SocketError.Success) + { + if (rcv_message.fully_transfered()) + { + if (rcv_message.is_reading_size()) + { var msg_size = _on_read_size_completely(rcv_message); - if (msg_size != null && msg_size.HasValue) { + if (msg_size != null && msg_size.HasValue) + { _read_data(msg_size.Value); } return; - } else { + } + else + { // data is read int msg_type = rcv_message.read_int32(); bts.Log.assert(msg_type == HB_MSG_SIGNAL || msg_type == DATA_MSG_SIGNAL); - if (msg_type == DATA_MSG_SIGNAL) { + if (msg_type == DATA_MSG_SIGNAL) + { _on_read_data_completely(rcv_message); _read_next_msg(); return; - } else if (msg_type == HB_MSG_SIGNAL) { + } + else if (msg_type == HB_MSG_SIGNAL) + { _on_read_hb_completely(rcv_message); _read_next_msg(); return; @@ -493,43 +578,57 @@ namespace bts { // go back to reading size for a new message //_read_size(); } - } else { + } + else + { // msg has not been fully rd, we have already advanced the transfer ptr _begin_or_resume_reading(rcv_msg: rcv_message); } - } else { - _handle_error(new ErrorMessage(read_err, "_on_read")); } - } catch (Exception ex) { - _handle_error(new ErrorMessage(ex, "_on_read")); + else + { + _handle_error(new ErrorMessage(read_err, "_on_read_async")); + } + } + catch (Exception ex) + { + _handle_error(new ErrorMessage(ex, "_on_read_async")); } } #endregion - private int? _on_read_size_completely(AsyncReceiveMessage msg) { + private int? _on_read_size_completely(AsyncReceiveMessage msg) + { bts.Log.assert(msg.is_reading_size()); bts.Log.assert(msg.fully_transfered()); bts.Log.assert(msg.original_size == 4); var msg_sz = msg.read_int32(); + //var buff_txt = AsyncTCPConnection_AsyncWrapper.to_hex(msg.buffer, 0, msg.buffer.Length); + //bts.Log.Gen.info($"AsyncTCPConnection_APM._on_read_size_completely buff: {buff_txt}"); bts.Log.Gen.info($"AsyncTCPConnection_APM._on_read_size_completely msg: {msg} msg_sz: {msg_sz}"); - if (msg_sz > _max_msg_size) { + if (msg_sz < 0 || msg_sz > _max_msg_size) + { string err_msg = $"Encountered malformed message, prefixed_size: {msg_sz}"; - _handle_error(new ErrorMessage(new ApplicationException(err_msg), "_on_read")); + _handle_error(new ErrorMessage(new ApplicationException(err_msg), "_on_read_size_completely")); return null; - } else { + } + else + { // sz is determined, now we read that many bytes //_read_data(msg_sz); return msg_sz; } } - private void _on_read_hb_completely(AsyncReceiveMessage msg) { + private void _on_read_hb_completely(AsyncReceiveMessage msg) + { bts.Log.assert(!msg.is_reading_size()); bts.Log.assert(msg.fully_transfered()); bts.Log.assert(msg.original_size == 4); bts.Log.assert(msg.read_int32(0) == HB_MSG_SIGNAL); - if (!_hb_received_yet) { + if (!_hb_received_yet) + { _hb_received_yet = true; //bts.Log.Gen.info($"AsyncTCPConnection_APM HB received for the first time from peer {_peer_conn_info}"); } @@ -537,7 +636,8 @@ namespace bts { _message_handler.onData(new RemoteMessage(null, RemoteMessageType.Heartbeat, _peer_conn_info)); } - private void _on_read_data_completely(AsyncReceiveMessage msg) { + private void _on_read_data_completely(AsyncReceiveMessage msg) + { bts.Log.assert(!msg.is_reading_size()); bts.Log.assert(msg.fully_transfered()); var type = msg.read_int32(0); @@ -546,7 +646,8 @@ namespace bts { byte[] data = msg.read_bytes(4); ///callbacks can be made through thread pool to avoid this ///thread from being blocked, by this callback - if (!_data_received_yet) { + if (!_data_received_yet) + { _data_received_yet = true; //bts.Log.Gen.info($"AsyncTCPConnection_APM data received for the first time from peer {_peer_conn_info}"); } @@ -556,16 +657,24 @@ namespace bts { #region IDisposable Members - public void Dispose() { + public void Dispose() + { // socket is closed and disposed here - lock (this) { - if (_is_alive) { + lock (this) + { + bts.Log.Gen.info($"AsyncTCPConnection_APM.Dispose this: {this} Dispose called _dipose_impetus: {_dipose_impetus}"); + if (_is_alive) + { _master_worker.removeWorker(this); _is_alive = false; - bts.Log.Gen.info($"AsycnTCPConnection.Dispose this: {this} being disposed, last HB was received at {_last_hb_received_time}"); - try { + bts.Log.Gen.info($"AsyncTCPConnection_APM.Dispose this: {this} being disposed, last HB was received at {_last_hb_received_time}"); + try + { + bts.Log.Gen.info($"AsyncTCPConnection_APM.Dispose this: {this} shutting down socket now"); _sock.Shutdown(SocketShutdown.Both); - } catch (Exception ex) { + } + catch (Exception ex) + { String.Format("AsyncTCPConnection_APM.Dispose exception: {ex} thrown when closing socket"); if (ex is OutOfMemoryException) throw ex; @@ -577,11 +686,15 @@ namespace bts { #endregion - private void _handle_error(ErrorMessage err_msg) { - lock (this) { - Log.Gen.info($"AsyncTCPConnection_APM._handle_error this: {this} error_msg: {err_msg}"); + private string _dipose_impetus = String.Empty; + private void _handle_error(ErrorMessage err_msg) + { + lock (this) + { + Log.Gen.error($"AsyncTCPConnection_APM._handle_error this: {this} error_msg: {err_msg}"); if (err_msg.oom) throw err_msg.exception; + _dipose_impetus = $"AsyncTCPConnection_APM._handle_error this: {this} error_msg: {err_msg}"; Dispose(); } } diff --git a/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnection_AsyncWrapper.cs b/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnection_AsyncWrapper.cs new file mode 100644 index 000000000..1b5540d1c --- /dev/null +++ b/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnection_AsyncWrapper.cs @@ -0,0 +1,339 @@ +namespace bts +{ + using BCG; + using BCG.Utilities.General; + using System; + using System.IO; + using System.Net.Sockets; + using System.Threading.Tasks; + using System.Threading; + using System.Net; + using System.Text; + + // this ITCPConnection uses the TCPClient class instead of a raw socket (in the hope, that it would configure the socket correctly) + + public class AsyncTCPConnection_AsyncWrapper : ITCPConnection, IWorker, IDisposable + { + public class ConnectionID + { + public readonly RemoteConnectionInfo self; + public readonly RemoteConnectionInfo peer; + public readonly Type conn_type; + public override string ToString() + { + return $"{conn_type} self: {self} peer: {peer}"; + } + public ConnectionID(RemoteConnectionInfo self_, RemoteConnectionInfo peer_, Type conn_type_) + { + self = self_; + peer = peer_; + conn_type = conn_type_; + } + } + private const int DATA_MSG_SIGNAL = 0; + private const int HB_MSG_SIGNAL = 1; + private TcpClient _tcp_client; + private NetworkStream _nw_stream; + private ITCPMessageHandler _msg_handler; + private bool _is_alive = true; + ConnectionID _connection_id; + + // public static string to_hex(byte[] byte_arr, int start_pos, int end_pos) { + // var len = end_pos - start_pos; + // StringBuilder hex_builder = new StringBuilder(len * 2); + // int i = 0; + + // foreach (byte b in byte_arr) { + // if (i >= start_pos && i < end_pos) + // hex_builder.Append($"{b:X2} "); + // i++; + // } + // return hex_builder.ToString().Trim(); + // } + + public AsyncTCPConnection_AsyncWrapper(TcpClient tcp_client) + { + _tcp_client = tcp_client; + _nw_stream = _tcp_client.GetStream(); + _connection_id = new ConnectionID(TCPSocketUtils.get_self_address(_tcp_client.Client), TCPSocketUtils.get_peer_address(_tcp_client.Client), GetType()); + Log.Gen.info("AsyncTCPConnection_AsyncWrapper.cons connection: {_connection_id}"); + } + + private void _detect_connection_status_change() + { + Action testing_func = () => + { + bool connected = _tcp_client.Connected; + while (true) + { + if (connected != _tcp_client.Connected) + Log.Gen.error($"Connection status changed this: {ToString()} {connected} -> {_tcp_client.Connected}"); + connected = _tcp_client.Connected; + System.Threading.Thread.Sleep(50); + if (!connected) + break; + } + }; + ThreadPool.QueueUserWorkItem(_ => testing_func()); + } + + #region Sending + public void _send_fixed_size_msg(byte[] buffer) + { + // string buff_txt = to_hex(buffer, 0, buffer.Length); + // Log.Gen.info($"AsyncTCPConnection_AsyncWrapper._send_fixed_size_msg buffer: {buff_txt}"); + + int total_bytes_sent = 0; + int n_bytes = buffer.Length; + + int n_transfers = 0; + while (_is_alive && total_bytes_sent < n_bytes) + { + int remaining_bytes = n_bytes - total_bytes_sent; + _nw_stream.Write(buffer, total_bytes_sent, remaining_bytes); + total_bytes_sent += remaining_bytes; + n_transfers++; + } + Log.Gen.info($"AsyncTCPConnection_AsyncWrapper._send_fixed_size_msg sent {buffer.Length} bytes in {n_transfers} transfers"); + } + + private void _send_one_msg(byte[] msg) + { + try + { + // the total msg = [msg_sz, msg_type, data] + int sz = msg.Length + 4; + MemoryStream str = new MemoryStream(); + BinaryWriter bw = new BinaryWriter(str); + bw.Write(sz); + bw.Write(DATA_MSG_SIGNAL); + bw.Write(msg); + str.Position = 0; + byte[] buff = str.ToArray(); + _send_fixed_size_msg(buff); + } + catch (Exception ex) + { + _handle_error(new ErrorMessage(ex, $"_send_one_msg call_stacK: {ex.StackTrace}")); + } + } + + private void _send_forever() + { + while (_is_alive) + { + byte[] data = _send_queue.dequeue(); + if (data != null) + { + _send_one_msg(data); + } + } + } + + private SyncQueue _send_queue = new SyncQueue(); + public void send(byte[] data) { + //Log.Gen.info($"AsyncTCPConnection_AsyncWrapper.send data: {to_hex(data, 0, data.Length}"); + _send_queue.enqueue(data); + } + #endregion + + public void register(ITCPMessageHandler message_handler) + { + _msg_handler = message_handler; + // starting thread pool threads to keep reading and sending + ThreadPool.QueueUserWorkItem(_ => _read_msgs_forever()); + ThreadPool.QueueUserWorkItem(_ => _send_forever()); + } + + public RemoteConnectionInfo get_peer_address() + { + return _connection_id.peer; + } + + public RemoteConnectionInfo get_self_address() + { + return _connection_id.self; + } + + public bool isDisposed { get { return !_is_alive; } } + + public void doWork() + { + // send hb + } + + #region Reading + // This makes the blocking IO call, the callstack is _read_msgs_forever -> _read_one_message -> _read_fixed_size_msg + private byte[] _read_fixed_size_msg(int n_bytes) + { + if (n_bytes <= 0) + { + throw new ArgumentException("Number of bytes to read must be greater than zero.", nameof(n_bytes)); + } + byte[] buffer = new byte[n_bytes]; + int total_bytes_read = 0; + int n_transfers = 0; + while (_is_alive && total_bytes_read < n_bytes) + { + int bytes_read = _nw_stream.Read(buffer, total_bytes_read, n_bytes - total_bytes_read); + if (bytes_read <= 0) + { + throw new IOException("Read 0 bytes, the connection was closed before all data could be read."); + } + n_transfers++; + total_bytes_read += bytes_read; + Log.Gen.info($"AsyncTCPConnection_AsyncWrapper._read_fixed_size_msg n_bytes: {n_bytes} bytes_read: {bytes_read} total_bytes_read: {total_bytes_read} buff_len: {buffer.Length}"); + } + Log.Gen.info($"AsyncTCPConnection_AsyncWrapper._read_fixed_size_msg read {n_bytes} bytes in {n_transfers} transfers"); + return buffer; + } + + private class OneRecvMessage + { + public int msg_type; + public byte[] data; + public OneRecvMessage(int msg_type_, byte[] data_) + { + msg_type = msg_type_; + data = data_; + } + public OneRecvMessage(byte[] msg) + { + MemoryStream str = new MemoryStream(msg); + BinaryReader br = new BinaryReader(str); + int msg_type = br.ReadInt32(); + if (msg_type == DATA_MSG_SIGNAL) + { + // TODO, polish it, too much memory bneing allocated + data = br.ReadBytes(msg.Length - 4); + } + } + + public override string ToString() + { + string rv = $"OneMessage msg_type: {msg_type} data_len: {data.Length}"; + return rv; + } + } + + private OneRecvMessage _read_one_message() + { + // read size first + byte[] sz_arr = _read_fixed_size_msg(4); + BinaryReader br = new BinaryReader(new MemoryStream(sz_arr)); + br.BaseStream.Position = 0; + int msg_sz = br.ReadInt32(); + Log.Gen.info($"AsyncTCPConnection_AsyncWrapper._read_one_message read msg_sz: {msg_sz}"); + if (msg_sz < 0) + { + throw new IOException("Read 0 bytes, the connection was closed before all data could be read."); + } + byte[] msg = _read_fixed_size_msg(msg_sz); + Log.Gen.info($"AsyncTCPConnection_AsyncWrapper._read_one_message read msg sz: {msg.Length}"); + // TODO, read first 4 bytes and decide hb or data + OneRecvMessage rv = new OneRecvMessage(msg); + return rv; + } + + private void _read_msgs_forever() + { + while (_is_alive) + { + try + { + OneRecvMessage one_msg = _read_one_message(); + if (one_msg.msg_type == DATA_MSG_SIGNAL) + { + _msg_handler.onData(new RemoteMessage(one_msg.data, RemoteMessageType.Data, _connection_id.peer)); + } + else if (one_msg.msg_type == HB_MSG_SIGNAL) + { + // keep a last hb time an dudpate it here atomically + _msg_handler.onData(new RemoteMessage(null, RemoteMessageType.Heartbeat, _connection_id.peer)); + } + else + { + throw new ApplicationException($"Unknown message type: {one_msg.msg_type}"); + } + } + catch (Exception ex) + { + _handle_error(new ErrorMessage(ex, $"_read_msgs_forever, call_stack: {ex.StackTrace}")); + } + } + Log.Gen.info($"AsyncTCPConnection_AsyncWrapper._read_msgs_forever exiting loop"); + } + #endregion + + public bool is_disposed => !_is_alive; + + public class ErrorMessage + { + public readonly SocketError? socket_error = null; + public readonly Exception exception = null; + public readonly bool is_exception = false; + public readonly string context = String.Empty; + public ErrorMessage(SocketError socket_error_, string context_) + { + socket_error = socket_error_; + context = context_; + } + public ErrorMessage(Exception exception_, string context_) + { + is_exception = true; + exception = exception_; + context = context_; + } + + public bool oom => exception != null && exception is OutOfMemoryException; + + public override string ToString() + { + if (is_exception) + return $"ErrorMessage exception: {exception} context: {context}"; + return $"socket_error: {socket_error} context: {context}"; + } + } + + public void Dispose() + { + // socket is closed and disposed here + lock (this) + { + if (_is_alive) + { + //_master_worker.removeWorker(this); + _is_alive = false; + try + { + bts.Log.Gen.info($"AsyncTCPConnection_APM.Dispose this: {this} closing tcp_client nin an orderly fashion now"); + _tcp_client.Close(); + } + catch (Exception ex) + { + String.Format("AsyncTCPConnection_APM.Dispose exception: {ex} thrown when closing socket"); + if (ex is OutOfMemoryException) + throw ex; + } + _msg_handler.onData(new RemoteMessage(null, RemoteMessageType.Disconnection, _connection_id.peer)); + } + } + } + + private void _handle_error(ErrorMessage err_msg) + { + lock (this) + { + Log.Gen.error($"AsyncTCPConnection_APM._handle_error this: {this} error_msg: {err_msg}"); + if (err_msg.oom) + throw err_msg.exception; + Dispose(); + } + } + + public override string ToString() + { + return _connection_id.ToString(); + } + } +} \ No newline at end of file diff --git a/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnector_APM.cs b/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnector_APM.cs index fa3cae9c2..ebbda0262 100644 --- a/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnector_APM.cs +++ b/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnector_APM.cs @@ -31,13 +31,13 @@ namespace bts { } } - public static void connect_to(BlutoSubAddress server_address, ITCPConnectionHandler handler) { + public static void connect_to(RemoteConnectionInfo server_address, ITCPConnectionHandler handler) { bts.Log.Gen.info($"AsyncTCPConnector_APM.connectTo server: {server_address}"); // when connection is established, this sock passed to an ITCPCOnnection and sent back Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - EndPoint ep = new IPEndPoint(IPAddress.Parse(server_address.ip), server_address.port); - sock.BeginConnect(ep, new AsyncCallback(_on_connect), - new SocketConnectionArgs(ep, sock, handler, server_address.ToString())); + EndPoint ip_ep = new IPEndPoint(IPAddress.Parse(server_address.ip), server_address.port); + sock.BeginConnect(ip_ep, new AsyncCallback(_on_connect), + new SocketConnectionArgs(ip_ep, sock, handler, server_address.ToString())); } private static void _on_connect(IAsyncResult res) { diff --git a/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnector_AsyncWrapper.cs b/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnector_AsyncWrapper.cs new file mode 100644 index 000000000..984cfebf1 --- /dev/null +++ b/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnector_AsyncWrapper.cs @@ -0,0 +1,70 @@ +using System.Net.Sockets; +using System.Net; + +using BCG; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using System.Threading; +using System.Reflection.Metadata.Ecma335; + + +namespace bts { + // Unlike AsyncTCPConnectionAcceptor_APM this class is static since the requests to connect are stand alone requests + // whereas AsyncTCPConnectionAcceptor_APM is always listening for incoming connections which lends itself to more + // statefullness and hence non static + public static class AsyncTCPConnector_AsyncWrapper { + public static void connect_to(RemoteConnectionInfo server_address, ITCPConnectionHandler handler) { + bts.Log.Gen.info($"AsyncTCPConnector_AsyncWrapper.connect_to server: {server_address}"); + //Task.Run(() => _connect_to(server_address, handler)); + Action connect_once = () => { _connect_to(server_address, handler); }; + ThreadPool.QueueUserWorkItem(_ => _keep_trying_blocking_function(connect_once, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5))); + } + + // this is the actual fuction thta calls TCPCLient sync methof and establishes a connection + private static void _connect_to(RemoteConnectionInfo server_rci, ITCPConnectionHandler handler) { + // TODO, random sleep + bts.Log.Gen.info($"AsyncTCPConnector_AsyncWrapper._connect_to server: {server_rci}"); + TcpClient tcp_client = new TcpClient(server_rci.ip, server_rci.port); + bts.Log.Gen.info($"AsyncTCPConnector_AsyncWrapper._connect_to server new TcpClient returned, connected: {tcp_client.Connected}"); + ITCPConnection conn = _create_connection(tcp_client); + var conn_rci = conn.get_peer_address(); + bts.Log.Gen.info($"AsyncTCPConnector_AsyncWrapper._connect_to new connection, server_rci: {server_rci} connection.peer_address: {conn_rci}"); + Log.assert(server_rci.Equals(conn_rci), $"{server_rci}!={conn_rci}"); + bts.Log.Gen.info($"AsyncTCPConnector_AsyncWrapper._connect_to new connection, self: {conn.get_self_address()} peer: {conn.get_peer_address()}, calling onConnection now"); + handler.onConnection(conn); + } + + private static ITCPConnection _create_connection(TcpClient tcp_client) { + ITCPConnection conn = new AsyncTCPConnection_AsyncWrapper(tcp_client); + // ITCPConnection conn = new AsyncTCPConnection_APM(tcp_client.GetStream().Socket, TimeSpan.FromSeconds(1), ITCPConnection.ConnectionSide.Client); + return conn; + } + + // this is a ganeric function that calls a sync action function, and if unsuccessful timesout after "timeout" + // wais for wait_before_retrying before trying again + public static void _keep_trying_blocking_function(Action action, TimeSpan timeout, TimeSpan wait_before_retrying) { + Func try_once = () => { + var cts = new CancellationTokenSource(); + var token = cts.Token; + + var task = Task.Run(action, token); + + if (Task.WaitAny(task, Task.Delay(timeout, token)) == 0) { + // Task completed within timeout + task.GetAwaiter().GetResult(); // Ensure any exceptions/cancellation are rethrown + return true; + } else { + // Timeout + cts.Cancel(); + return false; + } + }; + bool connected = false; + while (!connected) { + connected = try_once(); + System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1)); + } + } + } +} diff --git a/src/DataStreamSuite/PubSub/ManagedTCP/ClientToServerManagedTCPConnector.cs b/src/DataStreamSuite/PubSub/ManagedTCP/ClientToServerManagedTCPConnector.cs new file mode 100644 index 000000000..b0115ec00 --- /dev/null +++ b/src/DataStreamSuite/PubSub/ManagedTCP/ClientToServerManagedTCPConnector.cs @@ -0,0 +1,82 @@ +// using System; +// using System.Collections.Generic; +// using System.Text; +// using System.Net; +// using System.Net.Sockets; +// using System.Threading; +// using System.Threading.Tasks; +// //using BCG.Utilities; +// //using BCG.Utilities.General; + +// namespace BCG { +// internal class SocketConnectionArgs { +// public EndPoint ep; +// public Socket sock; +// public ITCPConnectionHandler handler; +// public string serverURL; + +// internal SocketConnectionArgs(EndPoint theEp, Socket theSock, ITCPConnectionHandler theHandler, +// string theServerURL) { +// ep = theEp; +// sock = theSock; +// handler = theHandler; +// serverURL = theServerURL; +// } +// } + +// public class ClientToServerManagedTCPConnector { +// private static Random myRnd = new Random(DateTime.Now.Millisecond); +// private static TimeSpan myHBTimeSpan = new TimeSpan(0, 0, 0, 0, PubSub3Config.instance.PS3_HeartBeatInterval); +// private static int myWaitTimeBeforeRetryingUpperLimit = 5000, +// myWaitTimeBeforeRetryingLowerLimit = 1000; + +// public static void connectTo(BlutoSubAddress serverAddress, ITCPConnectionHandler handler) { +// Console.WriteLine($"ClientToServerManagedTCPConnector.connectTo server: {serverAddress}"); +// Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); +// EndPoint ep = new IPEndPoint(IPAddress.Parse(serverAddress.ip), serverAddress.port); +// sock.BeginConnect(ep, new AsyncCallback(myOnConnect), new SocketConnectionArgs(ep, sock, handler, serverAddress.ToString())); +// } + +// public static async Task connect_to_async(BlutoSubAddress serverAddress, ITCPConnectionHandler handler, TimeSpan wait_before_retrying, int max_n_attempts = 1024) { +// bts.Log.Gen.info($"ClientToServerManagedTCPConnector.connectTo server: {serverAddress}"); +// await TCPSocketUtils.connect_to_server_async(serverAddress.ip, serverAddress.port, handler, wait_before_retrying, max_n_attempts); +// } + +// public static void connect_to(BlutoSubAddress serverAddress, ITCPConnectionHandler handler, TimeSpan wait_before_retrying, int max_n_attempts = 1024) { +// bts.Log.Gen.info($"ClientToServerManagedTCPConnector.connectTo server: {serverAddress}"); +// Task.Run(async () => { +// await TCPSocketUtils.connect_to_server_async(serverAddress.ip, serverAddress.port, handler, wait_before_retrying, max_n_attempts); +// }); +// } + +// private static void myOnConnect(IAsyncResult res) { +// Console.WriteLine("ClientToServerManagedTCPConnector.myOnConnect " + res.ToString() + " " + res.AsyncState.ToString()); +// SocketConnectionArgs args = res.AsyncState as SocketConnectionArgs; +// try { +// args.sock.EndConnect(res); +// } catch (SocketException sex) { +// string errMsg = String.Format("{0}: Connection to {1} failed.", DateTime.Now.ToString(), args.serverURL.ToString()); +// //BlueEventLog.logEvent(sex.Message + ";" + errMsg, PS3LogLevels.disconnection); +// //Console.WriteLine(errMsg); +// if (args.handler.isDisposed) { +// string doneMsg = String.Format("{0}: Connection to {1} was disposed. Not Retrying.", DateTime.Now.ToString(), args.serverURL.ToString()); +// //Console.WriteLine(doneMsg); +// // BlueEventLog.logEvent(doneMsg, PS3LogLevels.disconnection); +// return; +// } else { +// string retryMsg = String.Format("{0}: Retrying Connection to {1}.", DateTime.Now.ToString(), args.serverURL.ToString()); +// //Console.WriteLine(retryMsg); +// //BlueEventLog.logEvent(retryMsg, PS3LogLevels.disconnection); + +// int waitTime = myRnd.Next(myWaitTimeBeforeRetryingLowerLimit, myWaitTimeBeforeRetryingUpperLimit); +// Thread.Sleep(waitTime); +// args.sock.BeginConnect(args.ep, new AsyncCallback(myOnConnect), args); +// return; +// } +// } +// //BlueEventLog.logEvent(String.Format("Successful connection made to {0}.", args.serverURL.ToString()), PS3LogLevels.connection); +// args.handler.onConnection(new bts.AsyncTCPConnection_APM(args.sock, myHBTimeSpan, ITCPConnection.ConnectionSide.Client)); +// } + +// } +// } diff --git a/src/DataStreamSuite/PubSub/ManagedTCP/ITCPConnection.cs b/src/DataStreamSuite/PubSub/ManagedTCP/ITCPConnection.cs index bb6fe5f99..9afb9f920 100644 --- a/src/DataStreamSuite/PubSub/ManagedTCP/ITCPConnection.cs +++ b/src/DataStreamSuite/PubSub/ManagedTCP/ITCPConnection.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Runtime.CompilerServices; using System.Text; namespace BCG { @@ -20,7 +21,7 @@ namespace BCG { /// /// /// - void sendWithConfirmation(byte[] data, ref string confId, SendConfirmationDelegate del); + //void sendWithConfirmation(byte[] data, ref string confId, SendConfirmationDelegate del); /// /// sends data to the other side. theres no guaranatee that /// data is delievered. @@ -41,7 +42,7 @@ namespace BCG { /// /// /// - void getPeerAddress(out string ip, out int port); + RemoteConnectionInfo get_peer_address(); /// /// Gets its own ip and port, as seen by the peer. So if this @@ -51,7 +52,7 @@ namespace BCG { /// /// /// - void getSelfAddress(out string ip, out int port); + RemoteConnectionInfo get_self_address(); /// /// if the connection is disconnected, it disposes itself, /// hence this is an indicator of whether the connection is diff --git a/src/DataStreamSuite/PubSub/ManagedTCP/RemoteConnectionInfo.cs b/src/DataStreamSuite/PubSub/ManagedTCP/RemoteConnectionInfo.cs index 91aff6fe8..4e3799100 100644 --- a/src/DataStreamSuite/PubSub/ManagedTCP/RemoteConnectionInfo.cs +++ b/src/DataStreamSuite/PubSub/ManagedTCP/RemoteConnectionInfo.cs @@ -3,37 +3,66 @@ using System.Collections.Generic; using System.Text; using System.Net; using bts.utils; +using System.Net.NetworkInformation; +using bts; namespace BCG { public class RemoteConnectionInfo { - private string myIp; - private int myPort; - private IPEndPoint myEndPoint; + private string _ip; + private int _port; + //private IPEndPoint _ip_endpoint; + public static string ipv4_compat_prefix = "::ffff:"; + public static RemoteConnectionInfo null_instance = new RemoteConnectionInfo(String.Empty, 0); + public static string prefix = "bts-cloud://"; + //IP addresses that start with ::ffff: are IPv6-mapped IPv4 addresses. This format is used to represent an IPv4 address within an IPv6 address space. + + public static string clean_ip(string ip) { + string rv = ip; + if (!String.IsNullOrEmpty(ip)) { + if (ip.StartsWith(ipv4_compat_prefix)) { + rv = ip.Substring(ipv4_compat_prefix.Length); + } + } + return rv; + } public RemoteConnectionInfo(string ip, int port) { - myIp = ip; - myPort = port; + _ip = clean_ip(ip); + _port = port; + Log.Gen.info($"RemoteConnectionInfo constructed ip_arg: {ip} _ip: {_ip} port: {_port}"); } - public RemoteConnectionInfo(string ip, short port, IPEndPoint endPoint) - : this(ip, port) { - myEndPoint = endPoint; + public static RemoteConnectionInfo parse_url(string url) { + string[] toks = url.Split("//", StringSplitOptions.RemoveEmptyEntries); + var prefix = toks[0]; + var ip_port = toks[1]; + var ip_port_toks = toks[1].Split(':'); + string ip = ip_port_toks[0]; + int port = Int32.Parse(ip_port_toks[1]); + return new RemoteConnectionInfo(ip, port); } + // public RemoteConnectionInfo(string ip, int port, IPEndPoint ip_endpoint) + // : this(ip, port) { + // _ip_endpoint = ip_endpoint; + // } + public string ip { - get { return myIp; } + get { return _ip; } } public int port { - get { return myPort; } + get { return _port; } } - public IPEndPoint endPoint { - get { return myEndPoint; } - } + // public IPEndPoint end_point { + // // new IPEndPoint(IPAddress.Parse(server_address.ip), server_address.port); + // get { return _ip_endpoint; } + // } public override string ToString() { - return ip + ":" + port; + //return ip + ":" + port; + return $"{prefix}{ip}:{port}"; } public override int GetHashCode() { diff --git a/src/DataStreamSuite/PubSub/ManagedTCP/ServerToClientManagedTCPConnectionAcceptor.cs b/src/DataStreamSuite/PubSub/ManagedTCP/ServerToClientManagedTCPConnectionAcceptor.cs index 19c02ff35..879ad298a 100644 --- a/src/DataStreamSuite/PubSub/ManagedTCP/ServerToClientManagedTCPConnectionAcceptor.cs +++ b/src/DataStreamSuite/PubSub/ManagedTCP/ServerToClientManagedTCPConnectionAcceptor.cs @@ -7,6 +7,7 @@ using System.Net; using BCG; namespace bts { + // TODO: replace it with AsyncTCPConnectionAcceptor_APM public class ServerToClientManagedTCPConnectionAcceptor { private readonly int _port; @@ -53,12 +54,10 @@ namespace bts { ITCPConnection new_conn = new bts.AsyncTCPConnection_APM(new_sock, TimeSpan.FromSeconds(1), ITCPConnection.ConnectionSide.Server); _handler.onConnection(new_conn); _accept_socket.BeginAccept(new AsyncCallback(_on_accept), new object[] { }); - string ip; int port; - new_conn.getPeerAddress(out ip, out port); - Log.Gen.info( - $"ServerToClientManagedTCPConnectionAcceptor._on_accept connection accepted successfully from ip: {ip} port: {port} (local_port: {_port})"); + var peer_rci = new_conn.get_peer_address(); + Log.Gen.info($"ServerToClientManagedTCPConnectionAcceptor._on_accept connection accepted successfully from rci: {peer_rci}"); } - - } + + } diff --git a/src/DataStreamSuite/PubSub/ManagedTCP/SingleServerToClientManagedTCPConnectionAcceptor.cs b/src/DataStreamSuite/PubSub/ManagedTCP/SingleServerToClientManagedTCPConnectionAcceptor.cs index 7434688be..255937e3a 100644 --- a/src/DataStreamSuite/PubSub/ManagedTCP/SingleServerToClientManagedTCPConnectionAcceptor.cs +++ b/src/DataStreamSuite/PubSub/ManagedTCP/SingleServerToClientManagedTCPConnectionAcceptor.cs @@ -1,104 +1,104 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Net; -using System.Net.Sockets; -using System.Threading.Tasks; -using bts; -using Bts.PubSub; - -//using BCG.Utilities; - -namespace BCG { - public class SingleServerToClientManagedTCPConnectionAcceptor { - private TimeSpan myHBTimeSpan, - myWaitTimeBeforeRetrying = new TimeSpan(0, 0, 0, 0, 250); - private ITCPConnectionHandler myHandler; - private Socket myAcceptSock; - private int myPort; - - - public int activateWithRandomPort(ITCPConnectionHandler handler, TimeSpan clientHBTimeSpan) { - myHBTimeSpan = clientHBTimeSpan; - myHandler = handler; - myAcceptSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - int port = 0; - bool madeItThrough = false; - // BlueEventLog.logEvent("Looking for open port to run the server on.", PS3LogLevels.connection); - Random randomizer = new Random(); - PubSubPortRange theRange = Log.notnull(PubSubConfig.Instance.PortRange); - - - //if the range of ports is 1000, then trying 5,000 times means - //your odds of missing an open port are less than 1% - - int maxAttempts = (theRange.maxPort - theRange.minPort) * 5; - int totalAttempts = 0; - while (!madeItThrough) { - port = randomizer.Next(); - port = theRange.minPort + (port % (theRange.maxPort - theRange.minPort)); - - try { - myAcceptSock.Bind(new IPEndPoint(IPAddress.Any, port)); - madeItThrough = true; - } catch (Exception) { - totalAttempts++; - if (totalAttempts < maxAttempts) { - //BlueEventLog.logEvent("Couldn't bind to port " + port.ToString() + "; retrying...", PS3LogLevels.connection); - } else { - // BlueEventLog2.instance().abort("Couldn't find an open port to advertise the server on. Consider modifying PS3_PortRange. Talk to Mark for details."); - } - } - } - myPort = port; - myAcceptSock.Listen(250); - myAcceptSock.BeginAccept(new AsyncCallback(myOnAccept), new object[] { }); - - return myPort; - } - - public int activate(ITCPConnectionHandler handler, int port, TimeSpan clientHBTimeSpan) { - myHBTimeSpan = clientHBTimeSpan; - myHandler = handler; - myAcceptSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, port); - myAcceptSock.Bind(endpoint); - myAcceptSock.Listen(250); - myAcceptSock.BeginAccept(new AsyncCallback(myOnAccept), new object[] { }); - myPort = endpoint.Port; - return myPort; // not sure why we need this class variable myPort, but I am just keeping it up with the existing code - } - - public int accept_on_port(ITCPConnectionHandler handler, string ip, int port, TimeSpan client_HB_timespan) { - Task.Run(async () => { - await TCPSocketUtils.accept_connections_async(ip, port, handler, TimeSpan.FromSeconds(1)); - }); - return port; - } - - private void myOnAccept(IAsyncResult res) { - Socket newSock; - try { - newSock = myAcceptSock.EndAccept(res); - } catch (Exception ex) { - // BlueEventLog.logEvent(ex); - Thread.Sleep(myWaitTimeBeforeRetrying); - myAcceptSock.BeginAccept(new AsyncCallback(myOnAccept), new object[] { }); - if (ex is OutOfMemoryException) - throw ex; - return; - } - newSock.LingerState = new LingerOption(false, 0); - newSock.Blocking = false; - ITCPConnection newConn = new bts.AsyncTCPConnection_APM(newSock, myHBTimeSpan, ITCPConnection.ConnectionSide.Server); - myHandler.onConnection(newConn); - myAcceptSock.BeginAccept(new AsyncCallback(myOnAccept), new object[] { }); - string ip; int port; - newConn.getPeerAddress(out ip, out port); - string connMsg = String.Format("Connection to port {2} made from {0}:{1}", ip, port, myPort); - // BlueEventLog.logEvent(connMsg, PS3LogLevels.connection); - //Console.WriteLine(connMsg); - } - } -} +// using System; +// using System.Collections.Generic; +// using System.Text; +// using System.Threading; +// using System.Net; +// using System.Net.Sockets; +// using System.Threading.Tasks; +// using bts; +// using Bts.PubSub; + +// //using BCG.Utilities; + +// namespace BCG { +// public class SingleServerToClientManagedTCPConnectionAcceptor { +// private TimeSpan myHBTimeSpan, +// myWaitTimeBeforeRetrying = new TimeSpan(0, 0, 0, 0, 250); +// private ITCPConnectionHandler myHandler; +// private Socket myAcceptSock; +// private int myPort; + + +// public int activateWithRandomPort(ITCPConnectionHandler handler, TimeSpan clientHBTimeSpan) { +// myHBTimeSpan = clientHBTimeSpan; +// myHandler = handler; +// myAcceptSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); +// int port = 0; +// bool madeItThrough = false; +// // BlueEventLog.logEvent("Looking for open port to run the server on.", PS3LogLevels.connection); +// Random randomizer = new Random(); +// PubSubPortRange theRange = Log.notnull(PubSubConfig.Instance.PortRange); + + +// //if the range of ports is 1000, then trying 5,000 times means +// //your odds of missing an open port are less than 1% + +// int maxAttempts = (theRange.maxPort - theRange.minPort) * 5; +// int totalAttempts = 0; +// while (!madeItThrough) { +// port = randomizer.Next(); +// port = theRange.minPort + (port % (theRange.maxPort - theRange.minPort)); + +// try { +// myAcceptSock.Bind(new IPEndPoint(IPAddress.Any, port)); +// madeItThrough = true; +// } catch (Exception) { +// totalAttempts++; +// if (totalAttempts < maxAttempts) { +// //BlueEventLog.logEvent("Couldn't bind to port " + port.ToString() + "; retrying...", PS3LogLevels.connection); +// } else { +// // BlueEventLog2.instance().abort("Couldn't find an open port to advertise the server on. Consider modifying PS3_PortRange. Talk to Mark for details."); +// } +// } +// } +// myPort = port; +// myAcceptSock.Listen(250); +// myAcceptSock.BeginAccept(new AsyncCallback(myOnAccept), new object[] { }); + +// return myPort; +// } + +// public int activate(ITCPConnectionHandler handler, int port, TimeSpan clientHBTimeSpan) { +// myHBTimeSpan = clientHBTimeSpan; +// myHandler = handler; +// myAcceptSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); +// IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, port); +// myAcceptSock.Bind(endpoint); +// myAcceptSock.Listen(250); +// myAcceptSock.BeginAccept(new AsyncCallback(myOnAccept), new object[] { }); +// myPort = endpoint.Port; +// return myPort; // not sure why we need this class variable myPort, but I am just keeping it up with the existing code +// } + +// public int accept_on_port(ITCPConnectionHandler handler, string ip, int port, TimeSpan client_HB_timespan) { +// Task.Run(async () => { +// await TCPSocketUtils.accept_connections_async(ip, port, handler, TimeSpan.FromSeconds(1)); +// }); +// return port; +// } + +// private void myOnAccept(IAsyncResult res) { +// Socket newSock; +// try { +// newSock = myAcceptSock.EndAccept(res); +// } catch (Exception ex) { +// // BlueEventLog.logEvent(ex); +// Thread.Sleep(myWaitTimeBeforeRetrying); +// myAcceptSock.BeginAccept(new AsyncCallback(myOnAccept), new object[] { }); +// if (ex is OutOfMemoryException) +// throw ex; +// return; +// } +// newSock.LingerState = new LingerOption(false, 0); +// newSock.Blocking = false; +// ITCPConnection newConn = new bts.AsyncTCPConnection_APM(newSock, myHBTimeSpan, ITCPConnection.ConnectionSide.Server); +// myHandler.onConnection(newConn); +// myAcceptSock.BeginAccept(new AsyncCallback(myOnAccept), new object[] { }); +// string ip; int port; +// newConn.get_peer_address(out ip, out port); +// string connMsg = String.Format("Connection to port {2} made from {0}:{1}", ip, port, myPort); +// // BlueEventLog.logEvent(connMsg, PS3LogLevels.connection); +// //Console.WriteLine(connMsg); +// } +// } +// } diff --git a/src/DataStreamSuite/PubSub/ManagedTCP/TCPSocketUtils.cs b/src/DataStreamSuite/PubSub/ManagedTCP/TCPSocketUtils.cs index ab1673b59..15a58dfc4 100644 --- a/src/DataStreamSuite/PubSub/ManagedTCP/TCPSocketUtils.cs +++ b/src/DataStreamSuite/PubSub/ManagedTCP/TCPSocketUtils.cs @@ -6,14 +6,9 @@ using System.Net.Sockets; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; -using BCG; -using System.Xml.Serialization; -using System.Reflection; -using BCG.Utilities.General; -using System.Net.WebSockets; using bts; using System.Threading; -using Google.Protobuf.WellKnownTypes; +using System.Runtime.InteropServices; namespace BCG { // utility functions for TCP socket async communications. Does the following @@ -22,6 +17,106 @@ namespace BCG { // send data // receive data public static class TCPSocketUtils { + + struct TcpKeepAlive { + public uint OnOff; + public uint KeepAliveTime; + public uint KeepAliveInterval; + } + + public static void set_server_socket_options(ref Socket server_socket) { + + // Enable KeepAlive with detailed settings + TcpKeepAlive keepAliveSettings = new TcpKeepAlive { + OnOff = 1, // Enable KeepAlive + KeepAliveTime = 60000, // 1 minute in milliseconds + KeepAliveInterval = 10000 // 10 seconds in milliseconds + }; + + server_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); + + // Set keep-alive interval and time (Linux-specific method) + if (OperatingSystem.IsLinux()) { + ; + const int keepAliveTime = 60; // Seconds + const int keepAliveInterval = 10; // Seconds + server_socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, keepAliveTime); + server_socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, keepAliveInterval); + } else { + int size = Marshal.SizeOf(keepAliveSettings); + IntPtr ptr = Marshal.AllocHGlobal(size); + Marshal.StructureToPtr(keepAliveSettings, ptr, true); + byte[] inOptionValues = new byte[size]; + Marshal.Copy(ptr, inOptionValues, 0, size); + Marshal.FreeHGlobal(ptr); + + server_socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null); + } + + // Set other socket options as needed + server_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); + server_socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true); + server_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 10000); + server_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 10000); + server_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 8192); + server_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, 8192); + + // Optionally configure linger option + LingerOption lingerOption = new LingerOption(true, 10); + server_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption); + } + + public static RemoteConnectionInfo get_peer_address(Socket sock) { + IPEndPoint ip_ep = sock.RemoteEndPoint as IPEndPoint; + int port = ip_ep.Port; + string ip = ip_ep.Address.ToString(); + return new RemoteConnectionInfo(ip, port); + } + + public static RemoteConnectionInfo get_self_address(Socket socket) { + IPEndPoint ip_ep = socket.LocalEndPoint as IPEndPoint; + int port = ip_ep.Port; + string ip = ip_ep.Address.ToString(); + return new RemoteConnectionInfo(ip, port); + } + + + public static void set_client_socket_options(ref Socket client_socket) { + TcpKeepAlive keep_alive_settings = new TcpKeepAlive { + OnOff = 1, // Enable KeepAlive + KeepAliveTime = 60000, // 1 minute in milliseconds + KeepAliveInterval = 10000 // 10 seconds in milliseconds + }; + + if (OperatingSystem.IsLinux()) { + const int keepAliveTime = 60; // Seconds + const int keepAliveInterval = 10; // Seconds + client_socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, keepAliveTime); + client_socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, keepAliveInterval); + } else { + int size = Marshal.SizeOf(keep_alive_settings); + IntPtr ptr = Marshal.AllocHGlobal(size); + Marshal.StructureToPtr(keep_alive_settings, ptr, true); + byte[] inOptionValues = new byte[size]; + Marshal.Copy(ptr, inOptionValues, 0, size); + Marshal.FreeHGlobal(ptr); + + client_socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null); + } + + // Set other socket options as needed + client_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); + client_socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true); + client_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 10000); + client_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 10000); + client_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 8192); + client_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, 8192); + + // Optionally configure linger option + LingerOption lingerOption = new LingerOption(true, 10); + client_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption); + } + #region socket opening and connecting // keeps accepting connections forever public static async Task accept_connections_async(string ip, int port, ITCPConnectionHandler handler, diff --git a/src/DataStreamSuite/PubSub/Misc/SyncQueue.cs b/src/DataStreamSuite/PubSub/Misc/SyncQueue.cs index bc2eee446..87dd6b2ec 100644 --- a/src/DataStreamSuite/PubSub/Misc/SyncQueue.cs +++ b/src/DataStreamSuite/PubSub/Misc/SyncQueue.cs @@ -6,23 +6,20 @@ using System.Threading; using BCG; //using BCG.Utilities; -namespace BCG -{ +namespace BCG { /// /// Use this class for inter thread communication. It assumed a thread safe /// queue (this is right now implemented using locks, but for better performance /// will be switched over to lock free code, using cas). /// - public class SyncQueue : ISyncQueue - { + public class SyncQueue : ISyncQueue { private ThreadSafeQueue myQueue = new ThreadSafeQueue(); private AutoResetEvent myEvent = new AutoResetEvent(false); - public SyncQueue() {} + public SyncQueue() { } - public void enqueue(T t) - { + public void enqueue(T t) { myQueue.enqueue(t); myEvent.Set(); //return true; @@ -35,42 +32,31 @@ namespace BCG // return true; //} - public T dequeue() - { + public T dequeue() { return dequeue(Int32.MaxValue); } - public T dequeue (int timeout) - { + public T dequeue(int timeout) { DateTime startTime = DateTime.Now; T rv = myQueue.dequeue(); - if (rv != null || timeout <= 0) - { + if (rv != null || timeout <= 0) { return rv; - } - else - { + } else { int timeRemaining = timeout; - while (true) - { + while (true) { bool res = myEvent.WaitOne(timeRemaining, false); - if (res) - { + if (res) { ///timeout has not expired, so thread has been signalled rv = myQueue.dequeue(); - if (rv == null) - { + if (rv == null) { timeRemaining = timeout - Convert.ToInt32(((TimeSpan)(DateTime.Now - startTime)).TotalMilliseconds); if (timeRemaining <= 0) return rv; else continue; - } - else + } else return rv; - } - else - { + } else { ///timeout expired, return default; return default(T); } @@ -79,24 +65,18 @@ namespace BCG } } - public List dequeueMultipleElements(int timeout, int maxElements) - { - if (timeout == 0) - { + public List dequeueMultipleElements(int timeout, int maxElements) { + if (timeout == 0) { return myQueue.dequeueLimited(maxElements); - } - else - { + } else { DateTime startTime = DateTime.Now; List rv = new List(); rv = myQueue.dequeueLimited(maxElements); if (rv.Count == maxElements) return rv; - else - { + else { int timeRemaining = timeout; - while (true) - { + while (true) { T t = dequeue(timeRemaining); if (t != null) rv.Add(t); @@ -108,19 +88,20 @@ namespace BCG } } - public List dequeueMultipleElements(TimeSpan ts, int maxElements) - { + public List dequeueMultipleElements(TimeSpan ts, int maxElements) { return dequeueMultipleElements(Convert.ToInt32(ts.TotalMilliseconds), maxElements); } - public int getCount() - { + public List dequeue_all() { + return myQueue.dequeueAll(); + } + + public int getCount() { return myQueue.getCount(); } - public void terminate() - { + public void terminate() { } } } diff --git a/src/DataStreamSuite/PubSub/PublishedCache.cs b/src/DataStreamSuite/PubSub/PublishedCache.cs index 034a1fb9f..6cb392194 100644 --- a/src/DataStreamSuite/PubSub/PublishedCache.cs +++ b/src/DataStreamSuite/PubSub/PublishedCache.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; namespace bts { // This caches all the published data. This class is created and held by - // PublisherCore. Whend ata is publsihed , PublisherCore passes it to this + // PublisherCore. When data is publsihed , PublisherCore passes it to this // class via the publish call. On a reconnection to the PubSubServer, // PublisherCore calls get_content to get the data to re-publish, to // re-seed the PubSubServer @@ -14,6 +14,7 @@ namespace bts { public void publish(PublishMsg msg) { + Log.Gen.info($"PublishedCache.publish msg: {msg}"); SingleTagData tag_data = null; if (!_data_map.TryGetValue(msg.tag, out tag_data)) { tag_data = new SingleTagData(msg.tag, msg.tag_type); @@ -22,14 +23,15 @@ namespace bts { tag_data.handle_publish(msg); } - public byte[] get_content(string tag, out string tag_type) { + public Tuple get_content(string tag) { SingleTagData tag_data; + byte[] rv = new byte[] { }; if (_data_map.TryGetValue(tag, out tag_data)) { - tag_type = tag_data.tag_type; - return tag_data.get_current_content(); + string tag_type = tag_data.tag_type; + byte[] data = tag_data.get_current_content(); + return new Tuple(tag_type, data); } - tag_type = String.Empty; - return new byte[] { }; + return new Tuple(String.Empty, new byte[] { }); } public void clear(string tag) { diff --git a/src/DataStreamSuite/PubSub/PublisherCore.cs b/src/DataStreamSuite/PubSub/PublisherCore.cs index a10daeedf..a0fe85066 100644 --- a/src/DataStreamSuite/PubSub/PublisherCore.cs +++ b/src/DataStreamSuite/PubSub/PublisherCore.cs @@ -14,26 +14,24 @@ namespace BCG { // to be used when communicating to a pubsubserver protected PubSubServerConnectionFactory _connection_factory = new PubSubServerConnectionFactory(false); - // internal queue used to serialize pubsub method calls + // internal queue used to serialize server calls. All calls to PublisherCore are written to this quwue, + // dequeued by the message pump thread protected SyncQueue _main_queue = new SyncQueue(); // all the data published through this instance of PublisherCore - // is ketp there, in a form that can be used repopulate a pubsub server - // in the event of a crash + // is kept there, in a form that can be used repopulate a pubsub server + // in the event of a conection re-establishment to the PubSubServer protected PublishedCache _state = new PublishedCache(); - // a different IPubSubServerConnection object is used to interact - // with each of the pubsub servers used by this publishercore + // every PubSubServer is communicated with a adifferent IPubSubServerConnection object. // a dictionary for fast retrieval of publishers // tag -> IPubSubServerConnection protected IDictionary _tag_sender_map = new Dictionary(); - // url -> IPubSubServerConnection - private HashSet _connections = new HashSet(); - - // data waiting for transaction to end or abort - // tag->TagWaitingInTransaction + // pubsub server urls vs IPubSubServerConnection + private Dictionary _connection_map = + new Dictionary(); // router object, used to select which pubsub should be used for each tag protected IPubSubRouter _router = null; @@ -90,6 +88,7 @@ namespace BCG { public void publish(PubSubClientMessage msg) { Log.assert(msg.msg_type == PubSubMessageType.PUBLISH); + Log.assert(!String.IsNullOrEmpty(msg.pub_msg.tag_type)); bts.Log.Gen.info($"PublisherCore.publish msg: {msg}"); _main_queue.enqueue(msg); } @@ -122,6 +121,7 @@ namespace BCG { try { while (true) { PubSubClientMessage? msg = _main_queue.dequeue(100); + // only msg tyes expected right now (6/21/24) are PUBLISh type if (msg != null) { bts.Log.Gen.info($"PublisherCore._message_pump msg: {msg}"); switch (msg.msg_type) { @@ -138,8 +138,8 @@ namespace BCG { break; } } - - foreach (var conn in _connections) { + // all interactions with conn are called from the same thread + foreach (var conn in _connection_map.Values) { conn.doWork(); } } @@ -156,102 +156,14 @@ namespace BCG { } private void _commit_transaction() { - _end_transaction(true); + //_end_transaction(true); } private void _abort_transaction() { - _end_transaction(false); + //_end_transaction(false); } - - //based on success, sends a TA or TE, and sets myInTransaction to false - //TODO: if a transaction is sending to multiple pubsubs (in order to - //keep it consistent with the way it was done earlier), this should - //simply publish it non transactionally (easy way out), or - //transactionally with respect to each pubsub - protected virtual void _end_transaction(bool success) { - // lock (this) { - // // BlueEventLog.logAssert(inTransaction); - // //BlueEventLog.logEvent("PublisherCore Finishing Transaction.", BlueEventLevel.Information); - // _is_in_transaction = false; - // if (success) { - // // pubsub server -> tags with updates - // Dictionary> routesToTags = new Dictionary>(); - - // // group updates per pubsub server - // foreach (string tag in myWaitingInTransactionMessages.Keys) { - // string thisURL = _router.get_pub_url_for_tag(tag); - // if (!routesToTags.ContainsKey(thisURL)) - // routesToTags[thisURL] = new List(); - // routesToTags[thisURL].Add(tag); - // } - - // // more than one server means we won't be able to honor the transactionality request - // // log a warning if that is the case. - // if (routesToTags.Keys.Count > 1) { - // //this is going to be a long error message, but it's an importat one to be able to debug. - // StringBuilder errorMessageBuilder = new StringBuilder(); - // errorMessageBuilder.Append("Tags within this transaction are routed to different pubSub servers.\n"); - // errorMessageBuilder.Append("This will break the transactionality of clients receiving the data. Details:\n"); - - // foreach (string route in routesToTags.Keys) { - // foreach (string tag in routesToTags[route]) { - // errorMessageBuilder.Append("\tTag "); - // errorMessageBuilder.Append(tag); - // errorMessageBuilder.Append(" is routed to "); - // errorMessageBuilder.Append(route); - // errorMessageBuilder.Append(".\n"); - // } - - // } - // string errMsg = errorMessageBuilder.ToString(); - // // BlueEventLog.logEvent(errMsg, BlueEventLevel.Diagnosis); - // } - - // // iterate through each server with pending messages - // foreach (KeyValuePair> kvp in routesToTags) { - // IPubSubServerConnection transactionSender = null; - // string publishingApp = ClientInfo.thisClient.processString; - // string connection = kvp.Key; - // Stream transactionData = new MemoryStream(); - - // // iterate through each of the pending tag updates for one server - // foreach (string tag in kvp.Value) { - // ///it would be the same transaction sender that would - // ///return each time - // transactionSender = myGetOrBuildSender(tag); - - - // TagWaitingInTransaction waiting = myWaitingInTransactionMessages[tag]; - // // iterate through each of the updates for a specific tag, specific server - // foreach (byte[] data in waiting.data) - // // update internal state - // _state.publish(waiting.tag, waiting.tagType, data); - // // add a pubsub header and copy each message to the transactionData stream - // waiting.write_to(transactionData, connection, publishingApp); - // } - // // now transactionData holds all the updates for all the tags - // // that are to be sent to the PubSub represented by transactionSender - - // // add a transaction header, indicating how many tags in the transaction - // TransactionMetaData tMd = new TransactionMetaData(kvp.Value.Count); - - // // rewind transaction data to the beggining - // transactionData.Position = 0; - - // // send the entire thing to the specific pubsub server. - // // this is where the data is actually sent out ! - // var ps_msg = new PubSubMessage(new MetaData(tMd), transactionData); - // Console.WriteLine($"serverConn.send metadata: {ps_msg.meta_data}"); - // bts.Log.Gen.info($"PublisherCore.send ps_msg: {ps_msg}"); - // transactionSender.send(ps_msg); - // } - // } - // myWaitingInTransactionMessages.Clear(); - // } - } - protected virtual void _publish(PublishMsg msg) { bts.Log.Gen.info($"PublisherCore._publish msg: {msg}"); // update the state @@ -277,11 +189,13 @@ namespace BCG { protected IPubSubServerConnection _get_or_build_sender(string tag) { IPubSubServerConnection tag_conn = null; if (!_tag_sender_map.TryGetValue(tag, out tag_conn)) { - string route = _router.get_pub_url_for_tag(tag); - tag_conn = _connection_factory.getConnection(route); - if (!_connections.Contains(tag_conn)) { - tag_conn.register_connection_callback(new PubSubServerConnectionStatusChange(_handle_server_reboot)); - _connections.Add(tag_conn); + RemoteConnectionInfo server_rci = _router.get_pub_route_for_tag(tag); + if (!_connection_map.TryGetValue(server_rci, out tag_conn)) { + tag_conn = _connection_factory.get_connection(server_rci); + tag_conn.register_connection_callback((server_url, connected) => { + _handle_pubsubserver_reconnection(server_url, connected); + }); + _connection_map.Add(server_rci, tag_conn); } _tag_sender_map.Add(tag, tag_conn); } @@ -290,18 +204,19 @@ namespace BCG { ///in case of the server coming up, it publishes all the stored state ///for that server, back to it - protected void _handle_server_reboot(string server_url, bool connection) { - bts.Log.Gen.info($"PublisherCore._handle_server_reboot server_url: {server_url} connection: {connection}"); + private void _handle_pubsubserver_reconnection(string server_url, bool connection) { + bts.Log.Gen.info($"PublisherCore._handle_pubsubserver_reconnection server_url: {server_url} connection: {connection}"); if (connection) { // find all tags that are being published to this server foreach (var kv in _tag_sender_map) { var tag = kv.Key; var conn = kv.Value; if (conn.server_url == server_url) { - string tag_type; - var content_bytes = _state.get_content(tag, out tag_type); + var content = _state.get_content(tag); + byte[] content_bytes = content.Item2; + string tag_type = content.Item1; string content_bytes_log = content_bytes == null ? "NULL" : content_bytes.Length.ToString(); - Log.Gen.info($"PublisherCore._handle_server_reboot content_bytes: {content_bytes_log}"); + Log.Gen.info($"PublisherCore._handle_pubsubserver_reconnection server_url: {server_url} content_bytes: {content_bytes_log}"); bts.PublishMsg publish_msg = new bts.PublishMsg() { connection = kv.Key, publishing_app = ClientInfo.thisClient.processString, diff --git a/src/DataStreamSuite/PubSub/Server/Communication/IPubsubMessageHub.cs b/src/DataStreamSuite/PubSub/Server/Communication/IPubsubMessageHub.cs index ec152f9b9..821b3c4c4 100644 --- a/src/DataStreamSuite/PubSub/Server/Communication/IPubsubMessageHub.cs +++ b/src/DataStreamSuite/PubSub/Server/Communication/IPubsubMessageHub.cs @@ -15,11 +15,6 @@ namespace BCG { /// this event is prompted by the doWork. /// public interface IPubsubMessageHub : IWorker { - - /// - /// The port that the message hub is listening on. Return -1 if you're not listening on a port, i.e. for hte case of multicast - /// - int port { get; } /// /// register or unregister callback for data. The data can either be received on this callback /// on an arbitrary thread, or polled via getUpdates @@ -49,6 +44,8 @@ namespace BCG { /// /// List> get_updates(TimeSpan timeout, int maxElements); + // same as above, but gets all updates that are queued up + List> get_all_updates(); /// /// sends data to the receiver. /// diff --git a/src/DataStreamSuite/PubSub/Server/Communication/ManagedTCP/ManagedTCPMessageHub.cs b/src/DataStreamSuite/PubSub/Server/Communication/ManagedTCP/ManagedTCPMessageHub.cs index 3f7a5df14..887bb4aef 100644 --- a/src/DataStreamSuite/PubSub/Server/Communication/ManagedTCP/ManagedTCPMessageHub.cs +++ b/src/DataStreamSuite/PubSub/Server/Communication/ManagedTCP/ManagedTCPMessageHub.cs @@ -15,17 +15,13 @@ using bts; namespace BCG { - // this is the main TCP message exchange in the pubsub server. It accepts connections, + // this is the main TCP message exchange in the pubsub server. It accepts connections, data, as well as send data public class ManagedTCPMessageHub : IPubsubMessageHub, // external facing interface to be used by PubSubMesage Reactor ITCPConnectionHandler, // interface to receive connections when calling ServerToClientManagedTCPConnectionAcceptor.accept_connections ITCPMessageHandler { // interface to receive data from ITCPConnection - private int _port; + private readonly int _port; private bool _is_disposed = false; - public int port { - get { return _port; } - //property is read only - - } + // class used internally to queue messages from one trhead ot another private class ConnectionStatusInfo { public readonly string client_url; public readonly PubSubCallbacks.ConnectionStatus status; @@ -39,16 +35,16 @@ namespace BCG { private PubSubServerDataDelegate _data_cb; /// - /// client to connection + /// client to connection map /// private Dictionary _connection_map = new Dictionary(); /// /// data that is received from the client (on the onData thread) is queued in this - /// to be fetched by the client of this class in the getUpdates. + /// to be fetched by the client of this class in the get_updates. /// private SyncQueue> _received_data_queue; /// - /// data to be sent to the client is stored here and is fetched by the + /// data to be sent to the client is enqueued here and is fetched by the /// myDoItAll thread to be sent to the clients. the send is not directly sent out /// since there is some state management needed, so we do it on the main message /// pump thread @@ -62,27 +58,25 @@ namespace BCG { // _connection_cb arguments are queued here private ThreadSafeQueue _conn_callback_queue = new ThreadSafeQueue(); /// - /// new connections received (on the onConnection thread) is queued + /// new connections received (on the onConnection thread) are queued /// in this and will be fetched by the message_pump thread /// private ThreadSafeQueue _new_connections = new ThreadSafeQueue(); - /// - /// clients that sent heartbeats are stored in here - /// - private ThreadSafeQueue _received_hbs = new ThreadSafeQueue(); private readonly int _read_send_queue_timeout = 100;// just used to pass it on private readonly TimeSpan _hb_send_interval; private TimeSpan _subscriber_drop_threshold; - private TimeSpan _collect_disposed_connections_period = new TimeSpan(0, 0, 0, 0, 1000); + private TimeSpan _collect_disposed_connections_period = TimeSpan.FromMilliseconds(500); private DateTime _last_HB_collection_time = DateTime.Now; private DateTime _last_disposed_dead_collection_time = DateTime.Now; - private ServerToClientManagedTCPConnectionAcceptor _connection_acceptor; + // this si always active, accepting new client connections + private AsyncTCPConnectionAcceptor_AsyncWrapper _connection_acceptor; // TODO, get public ManagedTCPMessageHub(int port, TimeSpan hb_send_interval, int missing_HBs_for_gc, TimeSpan collect_disposed_connections_period) { _port = port; - _connection_acceptor = new ServerToClientManagedTCPConnectionAcceptor(port, this); + // what kind of connection_acceptor is controlled here + _connection_acceptor = new AsyncTCPConnectionAcceptor_AsyncWrapper(_port, this); _hb_send_interval = hb_send_interval; _subscriber_drop_threshold = new TimeSpan(0, 0, 0, 0, Convert.ToInt32(hb_send_interval.TotalMilliseconds * missing_HBs_for_gc)); _collect_disposed_connections_period = collect_disposed_connections_period; @@ -91,6 +85,7 @@ namespace BCG { #region IPubsubMessageHub Members + // this is unused right now, since the get_updates on a polling thread is called to by the client of this class to get messages public void register_data_callback(PubSubServerDataDelegate del) { bts.Log.assert_d(!_activated, "connection callbacks should be registered before the call to activate"); bts.Log.Gen.info("ManagedTCPMessageHub.register_data_callback called"); @@ -104,33 +99,37 @@ namespace BCG { } public void activate() { - _connection_acceptor.activate(); + _connection_acceptor.start(); bts.Log.Gen.info($"ManagedTCPMessageHub.activate TCP Component is ready, listening on port {_port} for incoming connections"); _activated = true; + // as the name says, all messages hand-off happen here Thread do_it_all_thread = new Thread(new ThreadStart(_main_message_pump)); do_it_all_thread.IsBackground = true; + do_it_all_thread.Priority = ThreadPriority.Highest; do_it_all_thread.Start(); } - public List> get_updates(TimeSpan timeout, int maxElements) { - return _received_data_queue.dequeueMultipleElements(timeout, maxElements); + // retutns the incoming either when timeout expires or n_elems are dequeued + public List> get_updates(TimeSpan timeout, int max_n_elems) { + return _received_data_queue.dequeueMultipleElements(timeout, max_n_elems); } - private bool _enqueue_send(string receiver, byte[] data) { - bts.Log.Gen.info($"ManagedTCPMessageHub._enqueue_send receiver: {receiver} data len: {data.Length}"); - _send_data_queue.enqueue(new Pair(receiver, data)); - return true; + // similiar to above, but returns all the elements that have been received since the last time this function was called + public List> get_all_updates() { + return _received_data_queue.dequeue_all(); } - // public bool send(string receiver, System.IO.Stream str) { - // BinaryReader br = new BinaryReader(str); - // return send(receiver, br.ReadBytes(Convert.ToInt32(str.Length - str.Position))); + // private bool _enqueue_send(string receiver, byte[] data) { + // bts.Log.Gen.info($"ManagedTCPMessageHub._enqueue_send receiver: {receiver} data len: {data.Length}"); + // _send_data_queue.enqueue(new Pair(receiver, data)); + // return true; // } public bool send(string receiver, bts.PubSubServerMessage ps_msg) { - bts.Log.Gen.info($"ManagedTCPMessageHub.send receiver: {receiver} ps_msg: {ps_msg}"); var ps_msg_bytes = ps_msg.serialize_into_bytes(); - return _enqueue_send(receiver, ps_msg_bytes); + bts.Log.Gen.info($"ManagedTCPMessageHub.send receiver: {receiver} ps_msg: {ps_msg} serialized msg sz: {ps_msg_bytes.Length}"); + _send_data_queue.enqueue(new Pair(receiver, ps_msg_bytes)); + return true; } #endregion @@ -155,18 +154,13 @@ namespace BCG { #region ITCPConnectionHandler Members /// - /// Enqeues both the connection name (to be reported back - /// via ConnectionStatusChange) and connection (to be - /// stored in the hashtable and used for later communication). - /// This is called on an arbitrary thread + /// This is the only place where + /// clients connect to the pubsubserver. + /// The connection in qneueued, so we can report it back in the same thread /// /// public void onConnection(ITCPConnection connection) { - // this is where we get new connections, dead connections are collected in _collect_disposed_connections - string ip; - int port; - connection.getPeerAddress(out ip, out port); - bts.Log.Gen.info($"ManagedTCPMessageHub.onConnection ip: {ip} port: {port}"); + bts.Log.Gen.info($"ManagedTCPMessageHub.onConnection connection: {connection}"); _new_connections.enqueue(connection); } @@ -175,23 +169,25 @@ namespace BCG { #region ITCPMessageHandler Members // called by ITCPConnection on an arbitrary thread public void onData(RemoteMessage message) { - bts.Log.Gen.info($"ManagedTCPMessgageHub.onData recv msg: {message}"); - string sender = new BlutoSubAddress(message.remoteConnectionInfo.ip, message.remoteConnectionInfo.port).ToString(); + bts.Log.Gen.info($"ManagedTCPMessgageHub.onData message: {message}"); + var sender_rci = message.remoteConnectionInfo; switch (message.messageType) { case RemoteMessageType.Data: // if callback is registered fire it right away, else enqueue it if (_data_cb != null) - _data_cb(sender, message.message); + _data_cb(sender_rci.ToString(), message.message); else - _received_data_queue.enqueue(new Pair(sender, message.message)); + _received_data_queue.enqueue(new Pair(sender_rci.ToString(), message.message)); break; case RemoteMessageType.Connection: - // wont happen + // this conditional will never hit, because onData is ITCPConnection's callback, and ITCPConnection + // will not report a connection, connections are reported through ConnectionAcceptor break; case RemoteMessageType.Disconnection: + // we ignore this here, since in the pump thread function, we poll the connection and GC it if its disconnected break; case RemoteMessageType.Heartbeat: - // dont care about, if it goes missing, we'll get a disconnection message + // we dont need this either, since the HB time can be queried from the conneciton and GC'ed there and then break; default: bts.Log.assert_d(false, "Unknown message type"); @@ -205,10 +201,9 @@ namespace BCG { while (true) { try { while (true) { - // these are the connections that were received on onConnection + // these are the connections that were received on onConnection, written to _conn_callback_queue _handle_new_connections(); - - ///dead connections that are disposed + ///dead connections that are disposed, writtent to _conn_callback_queue _collect_disposed_connections(); Pair p = _send_data_queue.dequeue(_read_send_queue_timeout); @@ -219,7 +214,7 @@ namespace BCG { _connection_map.TryGetValue(p.first, out conn); if (conn != null) { conn.send(p.second); - Log.Gen.info($"ManagedTCPMessageHub._main_message_pump sent n_bytes : {p.second.Length} to: {p.first}"); + Log.Gen.info($"ManagedTCPMessageHub._main_message_pump sending data client: {p.first} size: {p.second.Length}"); } else { string error_msg = $"sending data of sz: {p.second.Count()} to {p.first} failed, this client might have " + "disconnected, in which case it will be garbage collected within 60 secs"; @@ -250,8 +245,7 @@ namespace BCG { disposed_urls.Add(url); } foreach (string url in disposed_urls) { - string dispose_msg = $"Collecting disposed connections : {url} is disposed by the connection itself, " + - $"connection count before deleting this: {_connection_map.Count}"; + string dispose_msg = $"Collecting disposed connection: {url} connection count before deleting this: {_connection_map.Count}"; bts.Log.Gen.warn(dispose_msg); _connection_map.Remove(url); _conn_callback_queue.enqueue(new ConnectionStatusInfo(url, PubSubCallbacks.ConnectionStatus.DISCONNECTED)); @@ -259,22 +253,20 @@ namespace BCG { } } - // these are the connections that were added to _new_connections, on on_connect + // these are the connections that were added to _new_connections on onConnection // (which gets called in another thread) private void _handle_new_connections() { var new_conns = _new_connections.dequeueAll(); foreach (ITCPConnection conn in new_conns) { - string ip; - int port; - conn.getPeerAddress(out ip, out port); - string client_url = new BlutoSubAddress(ip, port).ToString(); - bts.Log.Gen.info($"ManagedTCPMessageHub._handle_new_connections client_url: {client_url}"); + var peer_rci = conn.get_peer_address(); + bts.Log.Gen.info($"ManagedTCPMessageHub._handle_new_connections conn: {conn}"); ///to stop it from being garbabge collected immediatly - _received_hbs.enqueue(client_url); + // ot get data conn.register(this); - _connection_map.Add(client_url, conn); + _connection_map.Add(peer_rci.ToString(), conn); // enqueued here to call the user sub in doWork - _conn_callback_queue.enqueue(new ConnectionStatusInfo(client_url, PubSubCallbacks.ConnectionStatus.CONNECTED)); + // why not fire the handler here ? + _conn_callback_queue.enqueue(new ConnectionStatusInfo(peer_rci.ToString(), PubSubCallbacks.ConnectionStatus.CONNECTED)); } } diff --git a/src/DataStreamSuite/PubSub/Server/PubSubMessageReactor.cs b/src/DataStreamSuite/PubSub/Server/PubSubMessageReactor.cs index 40766243f..85cff8bf5 100644 --- a/src/DataStreamSuite/PubSub/Server/PubSubMessageReactor.cs +++ b/src/DataStreamSuite/PubSub/Server/PubSubMessageReactor.cs @@ -6,6 +6,8 @@ using bts; using Bts.PubSub; using Spark.Core; +using System.Text; +using System.Diagnostics; namespace BCG { // This is the main PubSub Server class where it all starts (called by Program.cs). Its constructed and start is called and thats it. @@ -18,26 +20,9 @@ namespace BCG { private Thread _msg_polling_thread = null; // all the data,list of subscribers etc are in the state private PubSubState _state = new PubSubState(); - private bool myStop = false; private MasterWorker _mainloop_master_worker = MasterWorker.getInstance(false); - // private double myProcessingWarningThreshold = - // Convert.ToDouble(PubSub3Config.instance.PS3_MessageProcessingWarningThreshold); - // private HighPerformanceTimer myTimer = new HighPerformanceTimer(); - - private delegate void SingleTagTimeSliceDelegate(string tag, double processingTimeSeconds); - private SingleTagTimeSliceDelegate onSingleTagPub; private static SyncQueue _internal_pub_queue = new SyncQueue(); - //this thing keeps track of whether a given tag is compressed or not. It is used for logging messages. - - /* This delegate allows pubsub components to be notified when the identity ofe the pubsub is known*/ - // private delegate void IdentityFoundDelegate(string identity, bool isRoot); - // private event IdentityFoundDelegate onIdentityFound; - // private void fireIdentityFound(string identity, bool isRoot) { - // if (onIdentityFound != null) - // onIdentityFound(identity, isRoot); - // } - - //private Dictionary myTagCompressionState = new Dictionary(); + private Stopwatch _stop_watch = new Stopwatch(); public PubSubMessageReactor(int port_no) { bts.Log.Gen.info("PubSubMessageReactor.cons System Initialized"); @@ -51,11 +36,12 @@ namespace BCG { TimeSpan.FromMilliseconds(PubSubConfig.Instance.HeartbeatInterval.assert_value()), PubSubConfig.Instance.MissingHeartbeatsBeforeGc.assert_value(), TimeSpan.FromMilliseconds(PubSubConfig.Instance.DisposedConnectionCheckPeriod.assert_value())); - + // this is the only event this class gets from hub _msg_hub.register_connection_callback(new PubSubCallbacks.PubSubServerConnectionStatusChange(_handle_client_connection)); } + // the connection callback is the only event we get back from the message_hub. private void _handle_client_connection(string client, PubSubCallbacks.ConnectionStatus conn_status) { bts.Log.Gen.info($"PubsubMessageReactor._handle_client_connection client: {client} conn_status: {conn_status}"); ///interested in disconnections only, as connections of no @@ -65,10 +51,6 @@ namespace BCG { _state.remove_connection(client); } - private void stop() { - myStop = true; - } - public void start() { _msg_polling_thread.Start(); } @@ -79,10 +61,13 @@ namespace BCG { /// hanlder /// private void _polling_thread_func() { + Log.Gen.info("PubSubMessageReactor._polling_thread_func starting thread function _polling_thread_func"); TimeSpan poll_timeout = new TimeSpan(0, 0, 0, 0, 2500); _msg_hub.activate(); Action handle_internal_pubs = () => { - var internal_pubs = _internal_pub_queue.dequeueMultipleElements(1, 64000); + Log.Gen.info($"PubSubMessageReactor._polling_thread_func handle_internal_pubs"); + var internal_pubs = _internal_pub_queue.dequeueMultipleElements(TimeSpan.FromSeconds(1), 64000); + //Log.Gen.info($"PubSubMessageReactor._polling_thread_func internal_pubs count: {internal_pubs.Count}"); foreach (var msg in internal_pubs) { try { _handle_pub("Internal", msg, true); @@ -94,12 +79,16 @@ namespace BCG { while (true) { try { - var received_data = _msg_hub.get_updates(poll_timeout, 1); + //bts.Log.Gen.info($"PubSubMessageReactor._polling_thread_func pre get_updates"); + var received_data = _msg_hub.get_all_updates(); var n_msgs = received_data.Count; - if (n_msgs > 0) { - bts.Log.Gen.info($"PubSubMessageReactor._polling_thread_func n_msgs: {n_msgs}"); + if (n_msgs == 0) { + System.Threading.Thread.Sleep(TimeSpan.FromMilliseconds(250)); + continue; } + bts.Log.Gen.info($"PubSubMessageReactor._polling_thread_func post get_updates n_msgs: {n_msgs}"); foreach (var kv in received_data) { + // multiple pubs for the same tags should be batched here _handle_client_msg(kv.first, kv.second); } handle_internal_pubs(); @@ -111,8 +100,25 @@ namespace BCG { } } } + public static string to_hex(byte[] byte_arr, int start_pos, int end_pos) { + var len = end_pos - start_pos; + StringBuilder hex_builder = new StringBuilder(len * 2); + int i = 0; + + foreach (byte b in byte_arr) { + if (i >= start_pos && i < end_pos) + hex_builder.Append($"{b:X2} "); + i++; + } + return hex_builder.ToString().Trim(); + } + // all messages (polled from the message_hub) sent to the client are handled here private void _handle_client_msg(string sender, byte[] msg) { + //_stop_watch.Restart(); + var stop_watch = Stopwatch.StartNew(); + //string msg_txt = to_hex(msg, 0, msg.Length); + Log.Gen.info($"PubSubMessageReactor._handle_client_msg sender: {sender} msg: {msg.Length}"); // TODO: reduce object creation, C# has an ObjectPool PubSubClientMessage ps_client_msg = new PubSubClientMessage(); ps_client_msg.consruct_deserialize(msg); @@ -131,12 +137,15 @@ namespace BCG { _handle_pub(sender, ps_client_msg.pub_msg, false); break; } + stop_watch.Stop(); + Log.Gen.info($"PubSubMessageReactor._handle_client_msg processed ps_client_msg: {ps_client_msg} processing time: {stop_watch.ElapsedMilliseconds} msecs"); } private void _handle_sub(string sender, SubscribeMsg sub_msg) { - //TODO: we make this correction here, since non managed clients are ntosending this correctly + //TODO: we make this correction here, since C++ clients are not sending this correctly bts.Log.Gen.info($"PubSubMessageReactor._handle_sub sender: {sender} sub_msg: {sub_msg}"); - if (String.IsNullOrEmpty(sub_msg.connection) || sub_msg.connection.Contains("unset")) { + if (String.IsNullOrEmpty(sub_msg.connection) || String.Compare(sender, sub_msg.connection) != 0) { + bts.Log.Gen.error($"PubSubMessageReactor._handle_sub correcting sub_msg.connection sender: {sender} sub_msg.connection: {sub_msg.connection}"); sub_msg.connection = sender; } bts.Log.Gen.info($"PubSubMessageReactor._handle_sub(corrected) sender: {sender} sub_msg: {sub_msg}"); @@ -149,10 +158,10 @@ namespace BCG { //ie data has been published once if (data != null) { bts.Log.Gen.info($"ManagedTCPMessgeHub._handle_sub get_content tag: {tag} data len: {data.Length}"); - string tagType = _state.getTagType(tag); + string tag_type_ = _state.getTagType(tag); var msg_to_send = new PubSubServerMessage() { tag = tag, - tag_type = tagType, + tag_type = tag_type_, data = data }; bts.Log.Gen.info($"ManagedTCPMessgeHub._handle_sub sending msg_to_send: {msg_to_send} connection: {sub_msg.connection}"); @@ -170,7 +179,7 @@ namespace BCG { // this is where pubsub's data state is updated _state.update_pub_data(pub_msg); var sub_connections_for_tag = _state.get_subscriber_connections_for_tag(pub_msg.tag); - //bts.Log.Gen.info($"PubSubMessageReactor._handle_pub {sub_connections_for_tag.Count} subs for tag: {pub_msg.tag}"); + bts.Log.Gen.info($"PubSubMessageReactor._handle_pub {sub_connections_for_tag.Count} subs for tag: {pub_msg.tag}"); bts.PubSubServerMessage msg_to_send = new PubSubServerMessage() { tag = pub_msg.tag, tag_type = pub_msg.tag_type, diff --git a/src/DataStreamSuite/PubSub/Server/PubSubSingleTagState.cs b/src/DataStreamSuite/PubSub/Server/PubSubSingleTagState.cs index ae9520df3..842057e8b 100644 --- a/src/DataStreamSuite/PubSub/Server/PubSubSingleTagState.cs +++ b/src/DataStreamSuite/PubSub/Server/PubSubSingleTagState.cs @@ -1,126 +1,126 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +// using System; +// using System.Collections.Generic; +// using System.Linq; +// using System.Text; -/* - * This class contains the recent channges of state of a single pubsub tag, with respect to who has subscribed, who has published, etc. - * It has a list of new subscription events. - * - */ -namespace BCG { - public class PubSubSingleTagState { - private string myTag; - public string tag { - get { return myTag; } - set { myTag = value; } +// /* +// * This class contains the recent channges of state of a single pubsub tag, with respect to who has subscribed, who has published, etc. +// * It has a list of new subscription events. +// * +// */ +// namespace BCG { +// public class PubSubSingleTagState { +// private string myTag; +// public string tag { +// get { return myTag; } +// set { myTag = value; } - } - //we have this here as SortedList so that we can compare for equality - private SortedList myPublishers; - private SortedList mySubscribers; - private Dictionary myNewSubscribers; - private Dictionary myRemovedSubscribers; - private Dictionary myNewPublishers; - private Dictionary myRemovedPublishers; +// } +// //we have this here as SortedList so that we can compare for equality +// private SortedList myPublishers; +// private SortedList mySubscribers; +// private Dictionary myNewSubscribers; +// private Dictionary myRemovedSubscribers; +// private Dictionary myNewPublishers; +// private Dictionary myRemovedPublishers; - public PubSubSingleTagState() { - //the total state of the tag - myPublishers = new SortedList(); - mySubscribers = new SortedList(); +// public PubSubSingleTagState() { +// //the total state of the tag +// myPublishers = new SortedList(); +// mySubscribers = new SortedList(); - //how has the state changed recentlty - myNewSubscribers = new Dictionary(); - myNewPublishers = new Dictionary(); - myRemovedPublishers = new Dictionary(); - myRemovedSubscribers = new Dictionary(); - } +// //how has the state changed recentlty +// myNewSubscribers = new Dictionary(); +// myNewPublishers = new Dictionary(); +// myRemovedPublishers = new Dictionary(); +// myRemovedSubscribers = new Dictionary(); +// } - //returns a list of all the events that need to be published. - public PubSubSingleTagStateEvent[] getNewEventsForPublishing() { - PubSubSingleTagStateEvent[] newEvents = new PubSubSingleTagStateEvent[myNewSubscribers.Count + myNewPublishers.Count + myRemovedPublishers.Count + myRemovedSubscribers.Count]; +// //returns a list of all the events that need to be published. +// public PubSubSingleTagStateEvent[] getNewEventsForPublishing() { +// PubSubSingleTagStateEvent[] newEvents = new PubSubSingleTagStateEvent[myNewSubscribers.Count + myNewPublishers.Count + myRemovedPublishers.Count + myRemovedSubscribers.Count]; - myNewSubscribers.Values.CopyTo(newEvents, 0); - int index = myNewSubscribers.Count; - myNewPublishers.Values.CopyTo(newEvents, index); - index += myNewPublishers.Count; - myRemovedSubscribers.Values.CopyTo(newEvents, index); - index += myRemovedSubscribers.Count; - myRemovedPublishers.Values.CopyTo(newEvents, index); +// myNewSubscribers.Values.CopyTo(newEvents, 0); +// int index = myNewSubscribers.Count; +// myNewPublishers.Values.CopyTo(newEvents, index); +// index += myNewPublishers.Count; +// myRemovedSubscribers.Values.CopyTo(newEvents, index); +// index += myRemovedSubscribers.Count; +// myRemovedPublishers.Values.CopyTo(newEvents, index); - return newEvents; +// return newEvents; - } +// } - //call this after you have published the new events - //this is made public for code readability reasons - //i.e. so that someone reading the SubInfoStateWatcher can understand what's going on more easily - public void resetNewEvents() { - myNewSubscribers = new Dictionary(); - myNewPublishers = new Dictionary(); - myRemovedSubscribers = new Dictionary(); - myRemovedPublishers = new Dictionary(); - } +// //call this after you have published the new events +// //this is made public for code readability reasons +// //i.e. so that someone reading the SubInfoStateWatcher can understand what's going on more easily +// public void resetNewEvents() { +// myNewSubscribers = new Dictionary(); +// myNewPublishers = new Dictionary(); +// myRemovedSubscribers = new Dictionary(); +// myRemovedPublishers = new Dictionary(); +// } - public void newPublish(PubSubSingleTagStateEvent newPublisher) { - //don't do anything here if we already knew about the publishers because we were already dealing with this publishers - if (!myPublishers.ContainsKey(newPublisher.app)) { - myPublishers.Add(newPublisher.app, newPublisher.app); +// public void newPublish(PubSubSingleTagStateEvent newPublisher) { +// //don't do anything here if we already knew about the publishers because we were already dealing with this publishers +// if (!myPublishers.ContainsKey(newPublisher.app)) { +// myPublishers.Add(newPublisher.app, newPublisher.app); - //if we were going to delete it, that means it was already being published by this app - //that means we should no logner delete it, but we don't have to announce that it was published again - if (myRemovedPublishers.ContainsKey(newPublisher.app)) - myRemovedPublishers.Remove(newPublisher.app); - else - myNewPublishers[newPublisher.app] = newPublisher; +// //if we were going to delete it, that means it was already being published by this app +// //that means we should no logner delete it, but we don't have to announce that it was published again +// if (myRemovedPublishers.ContainsKey(newPublisher.app)) +// myRemovedPublishers.Remove(newPublisher.app); +// else +// myNewPublishers[newPublisher.app] = newPublisher; - } - } +// } +// } - public void removePublisher(PubSubSingleTagStateEvent removedPublisher) { - if (myPublishers.ContainsKey(removedPublisher.app)) { - myPublishers.Remove(removedPublisher.app); +// public void removePublisher(PubSubSingleTagStateEvent removedPublisher) { +// if (myPublishers.ContainsKey(removedPublisher.app)) { +// myPublishers.Remove(removedPublisher.app); - //same kind of logic here. If we were about to publish this new publisher, we no longer need to announce it - if (myNewPublishers.ContainsKey(removedPublisher.app)) - myNewPublishers.Remove(removedPublisher.app); - else - myRemovedPublishers[removedPublisher.app] = removedPublisher; - } +// //same kind of logic here. If we were about to publish this new publisher, we no longer need to announce it +// if (myNewPublishers.ContainsKey(removedPublisher.app)) +// myNewPublishers.Remove(removedPublisher.app); +// else +// myRemovedPublishers[removedPublisher.app] = removedPublisher; +// } - } +// } - public void newSubscription(PubSubSingleTagStateEvent newSubscriber) { - if (!mySubscribers.ContainsKey(newSubscriber.app)) { - mySubscribers.Add(newSubscriber.app, newSubscriber.app); +// public void newSubscription(PubSubSingleTagStateEvent newSubscriber) { +// if (!mySubscribers.ContainsKey(newSubscriber.app)) { +// mySubscribers.Add(newSubscriber.app, newSubscriber.app); - if (myRemovedSubscribers.ContainsKey(newSubscriber.app)) - myRemovedSubscribers.Remove(newSubscriber.app); - else - myNewSubscribers[newSubscriber.app] = newSubscriber; +// if (myRemovedSubscribers.ContainsKey(newSubscriber.app)) +// myRemovedSubscribers.Remove(newSubscriber.app); +// else +// myNewSubscribers[newSubscriber.app] = newSubscriber; - } - } +// } +// } - public void removeSubscriber(PubSubSingleTagStateEvent removedSubscriber) { - if (mySubscribers.ContainsKey(removedSubscriber.app)) { - mySubscribers.Remove(removedSubscriber.app); - //if we were going to add this subscriber, we no logner want to - //this means no event needs to be published - if (myNewSubscribers.ContainsKey(removedSubscriber.app)) - myNewSubscribers.Remove(removedSubscriber.app); - else - //we have to remove this guy in this updated - myRemovedSubscribers[removedSubscriber.app] = removedSubscriber; - } +// public void removeSubscriber(PubSubSingleTagStateEvent removedSubscriber) { +// if (mySubscribers.ContainsKey(removedSubscriber.app)) { +// mySubscribers.Remove(removedSubscriber.app); +// //if we were going to add this subscriber, we no logner want to +// //this means no event needs to be published +// if (myNewSubscribers.ContainsKey(removedSubscriber.app)) +// myNewSubscribers.Remove(removedSubscriber.app); +// else +// //we have to remove this guy in this updated +// myRemovedSubscribers[removedSubscriber.app] = removedSubscriber; +// } - } +// } - } -} +// } +// } diff --git a/src/DataStreamSuite/PubSub/Server/PubSubState.cs b/src/DataStreamSuite/PubSub/Server/PubSubState.cs index 8d4abd3c5..a901a012b 100644 --- a/src/DataStreamSuite/PubSub/Server/PubSubState.cs +++ b/src/DataStreamSuite/PubSub/Server/PubSubState.cs @@ -42,29 +42,8 @@ namespace BCG { #region subscription based state changes - /// - /// everytime a subscription is made, this gets called - /// by PubsubServer2. Adds a - /// TODO : subscibers sending sub twice from the client - /// - /// - /// - // public void sub(SubMetaData sub) { - // ///tag based key ds update - // foreach (string tag in sub.tags) { - // if (!_tag_to_connection_map.ContainsKey(tag)) { - // _tag_to_connection_map.Add(tag, new SingleTagConnectionData(tag)); - // } - // _tag_to_connection_map[tag].onSub(sub); - - // if (onSingleTagChange != null) - // onSingleTagChange(new PubSubSingleTagStateEvent(tag, PubSubSingleTagStateEvent.EventType.subscription, sub.connection, sub.subscribing_app)); - // } - // if (onTagMapChanged != null) - // onTagMapChanged(sub.tags); - // } - public void handle_sub(bts.SubscribeMsg sub_msg) { + Log.Gen.info($"PubSubState.handle_sub sub_msg: {sub_msg}"); foreach (string tag in sub_msg.tags) { SingleTagConnectionData tag_conn_map = null; if (!_tag_to_connection_map.TryGetValue(tag, out tag_conn_map)) { @@ -81,24 +60,6 @@ namespace BCG { // TODO } - // public void unsub(UnSubMetaData unsub) { - // foreach (string tag in unsub.tags) { - // if (_tag_to_connection_map.ContainsKey(tag)) { - // ///maybe check here, that if there are no subscribers - // ///and publishers for the tag then remove it. - // _tag_to_connection_map[tag].onUnsub(unsub); - // if (onSingleTagChange != null) - // onSingleTagChange(new PubSubSingleTagStateEvent(tag, PubSubSingleTagStateEvent.EventType.unsubscription, unsub.connection, unsub.unsubscribing_app)); - // } else { - // string warningMsg = String.Format("{0} was never published or subscribed on this pubsub, hence" + - // " the unsub call by app {1} is voided", tag, unsub.unsubscribing_app); - // //BlueEventLog.logEvent(warningMsg, BlueEventLevel.Warning); - // } - // } - // if (onTagMapChanged != null) - // onTagMapChanged(unsub.tags); - // } - public void handle_unsub(bts.UnsubscribeMsg ubnsub_msg) { foreach (string tag in ubnsub_msg.tags) { SingleTagConnectionData conn_data = null; @@ -138,48 +99,11 @@ namespace BCG { } if (onTagMapChanged != null) onTagMapChanged(tags_effected.ToArray()); - - } #endregion #region data based state changes - /// - /// this is the only place in the state class where the - /// data is modified ; happens when data is published - /// - /// - /// - // public void updatePubData(PubMetaData pub, Stream msg) { - // int sz = (int)(msg.Length - msg.Position); - // bts.Log.Gen.info($"PubSubData.updatePubData pub: msg : {msg.Position} / {msg.Length} sz: {sz}"); - // ///this is the only place where SingleTagData should be created - // if (!_tag_to_data_map.ContainsKey(pub.tag)) { - // ///first time data is published for this tag - // _tag_to_data_map.Add(pub.tag, new SingleTagData(pub.tag, pub.type)); - // } - // _tag_to_data_map[pub.tag].pubUpdate(msg); - - // if (!_tag_to_connection_map.ContainsKey(pub.tag)) { - // _tag_to_connection_map.Add(pub.tag, new SingleTagConnectionData(pub.tag)); - // } - // bool pubChanged = false; - // _tag_to_connection_map[pub.tag].onPub(pub, newPublisher: out pubChanged); - // if (pubChanged) { - // if (onTagMapChanged != null) - // onTagMapChanged(new string[] { pub.tag }); - - // if (onSingleTagChange != null) - // onSingleTagChange( - // new PubSubSingleTagStateEvent(pub.tag, - // PubSubSingleTagStateEvent.EventType.publish, - // pub.connection, pub.publishingApp)); - // } - // if (onPublishStats != null) - // onPublishStats(pub.tag, sz); - // } - public void update_pub_data(bts.PublishMsg pub_msg) { try { bts.Log.Gen.info($"PubSubData.update_pub_data pub_msg: {pub_msg}"); diff --git a/src/DataStreamSuite/PubSub/Server/SingleTagConnectionData.cs b/src/DataStreamSuite/PubSub/Server/SingleTagConnectionData.cs index a64288fff..b4080953b 100644 --- a/src/DataStreamSuite/PubSub/Server/SingleTagConnectionData.cs +++ b/src/DataStreamSuite/PubSub/Server/SingleTagConnectionData.cs @@ -78,6 +78,7 @@ namespace BCG { } public bool handle_sub(SubscribeMsg sub_msg) { + Log.Gen.info($"SingleTagConnectionData.handle_sub sub_msg: {sub_msg}"); if (_sub_conn_to_app_map.ContainsKey(sub_msg.connection)) { bts.Log.Gen.info($"tag: {_tag} has already been subscribed by connection: {sub_msg.connection}"); return false; diff --git a/src/DataStreamSuite/PubSub/Server/SingleTagData.cs b/src/DataStreamSuite/PubSub/Server/SingleTagData.cs index 9bb3cd0ae..87cc5d9fc 100644 --- a/src/DataStreamSuite/PubSub/Server/SingleTagData.cs +++ b/src/DataStreamSuite/PubSub/Server/SingleTagData.cs @@ -10,7 +10,8 @@ using BCG; namespace bts { /// - /// this is the data (not pub/subs/connections) for one tag. This is owned by PubSubState and offers + /// this is the data (not pub/subs/connections) for one tag. This exists in both the PublisherCOre on the + /// publisher side, as well as the PubSubServer /// 2 main functions /// 1. handle_publish, called in response to a pubsub publish /// 2. get_current_content, to retreive the state built in response to 1. @@ -47,7 +48,7 @@ namespace bts { // PubsubState calls this public void handle_publish(PublishMsg pub_msg) { string handler_str = _tag_handler != null ? _tag_handler.GetType().ToString() : "NULL"; - bts.Log.Gen.info($"SingleTagData.handle_publish pub_msg: {pub_msg} handler: {handler_str} "); + bts.Log.Gen.info($"SingleTagData.handle_publish tag: {_tag} pub_msg: {pub_msg} handler: {handler_str} "); try { _tag_handler.update(_tag, pub_msg.data_to_publish); @@ -62,7 +63,9 @@ namespace bts { } public byte[] get_current_content() { - return _tag_handler.get_content(_tag); + byte[] rv = _tag_handler.get_content(_tag); + bts.Log.Gen.info($"SingleTagData.get_current_content tag: {_tag} rv: {rv}"); + return rv; } private void _on_handler_internal_publish(ICollection> cbItems) { diff --git a/src/DataStreamSuite/PubSub/SingleServerSubscriberCore.cs b/src/DataStreamSuite/PubSub/SingleServerSubscriberCore.cs index 72ca1ae29..ab6c69693 100644 --- a/src/DataStreamSuite/PubSub/SingleServerSubscriberCore.cs +++ b/src/DataStreamSuite/PubSub/SingleServerSubscriberCore.cs @@ -3,7 +3,9 @@ using bts; using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; +using System.Runtime.InteropServices; namespace BCG { /// @@ -27,9 +29,9 @@ namespace BCG { public event PubSubConnectionChange onPubSubConnectionChange; - public SingleServerSubscriberCore(string server_url, PubSubServerConnectionFactory connection_factory) { - bts.Log.Gen.info($"SingleServerSubscriberCore constructed for server_url: {server_url}"); - _connection = connection_factory.getConnection(server_url); + public SingleServerSubscriberCore(RemoteConnectionInfo server_rci, PubSubServerConnectionFactory connection_factory) { + bts.Log.Gen.info($"SingleServerSubscriberCore constructed for server_url: {server_rci}"); + _connection = connection_factory.get_connection(server_rci); _connection.register_connection_callback(new PubSubServerConnectionStatusChange(_handle_server_reboot)); _connection.register_data_callback(_on_data); } @@ -49,9 +51,9 @@ namespace BCG { msg.consruct_deserialize(m); if (_tags.Contains(msg.tag)) rv.Add(msg); - else - bts.Log.Gen.warn("SingleServerSubscriberCore.get_updates msg: {msg} is not subscribed currently"); - + else { + Log.Gen.warn("SingleSeverSubsciberCore.get_updates msg: {msg} does not have a subscription"); + } } return rv; } @@ -125,6 +127,7 @@ namespace BCG { tags = tag_args } }; + Log.Gen.info($"SingleServerSubscriberCore._subscribe sending msg: {msg}"); _connection.send(msg); } diff --git a/src/DataStreamSuite/PubSub/SubscriberCore.cs b/src/DataStreamSuite/PubSub/SubscriberCore.cs index acc21df6d..fb17bb243 100644 --- a/src/DataStreamSuite/PubSub/SubscriberCore.cs +++ b/src/DataStreamSuite/PubSub/SubscriberCore.cs @@ -1,125 +1,126 @@ -using bts; - -using Bts.PubSub; - -using System; -using System.Collections.Generic; - -namespace BCG { - - /// - /// This class serves as the subscrition interface to the pubsub. The only methods - /// it exposes are getUpdates and subscribe. Internally, it manages a SingleServerSubscriberCore - /// foreach server. So this class does the routing part, and each SingleServerSubscriberCore - /// handles dealing sending (sub/unsub) and receiving (data) messages from the transport. - /// There is no sharing with respect to this class. Ie, it creates new SingleServerSubscriberCore - /// to the servers even though there might be so created by other instances of the SubscriberCore - /// - /// - public class SubscriberCore : ISubscriberCore { - private Dictionary _server_url_to_subcore_map = new Dictionary(); - private IPubSubRouter _tag_router; - private PubSubServerConnectionFactory _connection_factory = new PubSubServerConnectionFactory(true); - - public event PubSubConnectionChange onPubSubConnectionChange; - - - #region constructors - - public SubscriberCore() { - //this defaults to a basic pubsubrouter if the config key is not filled out - _tag_router = new PubSubRouter(Log.notnull(PubSubConfig.Instance.SubscriberRoutes).ToArray()); - } - public SubscriberCore(string site_name) { - _tag_router = new PubSubRouter(PubSubConfig.Instance.SubscriberRoutesFor(site_name).ToArray()); - } - - private IPubSubRouter _get_router() => - new PubSubRouter(Log.notnull(PubSubConfig.Instance.SubscriberRoutes).ToArray()); - - public SubscriberCore(PubSubRoute[] routes) { - _tag_router = new PubSubRouter(routes); - } - - public SubscriberCore(IPubSubRouter router) { - _tag_router = router; - } - - #endregion - - public IEnumerable get_updates(TimeSpan timeout) { - List rv = new List(); - foreach (var kv in _server_url_to_subcore_map) { - var sub_core = kv.Value; - rv.AddRange(sub_core.get_updates(timeout)); - } - return rv; - } - - private IDictionary _n_update_map = new Dictionary(); - private void _log_n_updates(IEnumerable updates) { - foreach (PubSubUpdate u in updates) { - if (!_n_update_map.ContainsKey(u.tag)) { - _n_update_map.Add(u.tag, 0); - } - _n_update_map[u.tag] = _n_update_map[u.tag] + 1; - } - // log it now - foreach (var kv in _n_update_map) { - bts.Log.Gen.info($"StaticSubscrberCore tag: {kv.Key} n_updates: {kv.Value}"); - } - } - - public void subscribe(params string[] tags) { - lock (_server_url_to_subcore_map) { - foreach (string tag in tags) { - string server_url = _tag_router.get_sub_url_for_tag(tag); - var server_sub_core = _find_subscribercore(server_url); - server_sub_core.subscribe(tag); - } - } - } - - private ISingleServerSubscriberCore _find_subscribercore(string server_url) { - ISingleServerSubscriberCore rv = null; - if (!_server_url_to_subcore_map.TryGetValue(server_url, out rv)) { - rv = new SingleServerSubscriberCore(server_url, _connection_factory); - _server_url_to_subcore_map.Add(server_url, rv); - rv.onPubSubConnectionChange += _handle_pubsubserver_connection_change; - } - return rv; - } - - - public void _handle_pubsubserver_connection_change(bool is_connected, string server_url) { - if (onPubSubConnectionChange != null) - onPubSubConnectionChange(is_connected, server_url); - - } - - public void unsubscribe(params string[] tags) { - lock (_server_url_to_subcore_map) { - - foreach (string tag in tags) { - string server_url = _tag_router.get_sub_url_for_tag(tag); - var server_subcore = _find_subscribercore(server_url); - server_subcore.unsubscribe(tag); - } - } - } - - public IPubSubRouter get_router() { - return _tag_router; - } - - #region IDisposable Members - - public void Dispose() { - foreach (var sssc in _server_url_to_subcore_map.Values) - sssc.Dispose(); - _connection_factory.Dispose(); - } - - #endregion - } -} +using bts; + +using Bts.PubSub; + +using System; +using System.Collections.Generic; + +namespace BCG { + + /// + /// This class serves as the subscrition interface to the pubsub. The only methods + /// it exposes are getUpdates and subscribe. Internally, it manages a SingleServerSubscriberCore + /// foreach server. So this class does the routing part, and each SingleServerSubscriberCore + /// handles dealing sending (sub/unsub) and receiving (data) messages from the transport. + /// There is no sharing with respect to this class. Ie, it creates new SingleServerSubscriberCore + /// to the servers even though there might be so created by other instances of the SubscriberCore + /// + /// + public class SubscriberCore : ISubscriberCore { + private Dictionary _server_route_to_subcore_map = + new Dictionary(); + private IPubSubRouter _tag_router; + private PubSubServerConnectionFactory _connection_factory = new PubSubServerConnectionFactory(true); + + public event PubSubConnectionChange onPubSubConnectionChange; + + + #region constructors + + public SubscriberCore() { + //this defaults to a basic pubsubrouter if the config key is not filled out + _tag_router = new PubSubRouter(Log.notnull(PubSubConfig.Instance.SubscriberRoutes).ToArray()); + } + public SubscriberCore(string site_name) { + _tag_router = new PubSubRouter(PubSubConfig.Instance.SubscriberRoutesFor(site_name).ToArray()); + } + + private IPubSubRouter _get_router() => + new PubSubRouter(Log.notnull(PubSubConfig.Instance.SubscriberRoutes).ToArray()); + + public SubscriberCore(PubSubRoute[] routes) { + _tag_router = new PubSubRouter(routes); + } + + public SubscriberCore(IPubSubRouter router) { + _tag_router = router; + } + + #endregion + + public IEnumerable get_updates(TimeSpan timeout) { + List rv = new List(); + foreach (var kv in _server_route_to_subcore_map) { + var sub_core = kv.Value; + rv.AddRange(sub_core.get_updates(timeout)); + } + return rv; + } + + private IDictionary _n_update_map = new Dictionary(); + private void _log_n_updates(IEnumerable updates) { + foreach (PubSubUpdate u in updates) { + if (!_n_update_map.ContainsKey(u.tag)) { + _n_update_map.Add(u.tag, 0); + } + _n_update_map[u.tag] = _n_update_map[u.tag] + 1; + } + // log it now + foreach (var kv in _n_update_map) { + bts.Log.Gen.info($"StaticSubscrberCore tag: {kv.Key} n_updates: {kv.Value}"); + } + } + + public void subscribe(params string[] tags) { + lock (_server_route_to_subcore_map) { + foreach (string tag in tags) { + RemoteConnectionInfo server_rci = _tag_router.get_sub_route_for_tag(tag); + var server_sub_core = _find_subscribercore(server_rci); + server_sub_core.subscribe(tag); + } + } + } + + private ISingleServerSubscriberCore _find_subscribercore(RemoteConnectionInfo server_rci) { + ISingleServerSubscriberCore rv = null; + if (!_server_route_to_subcore_map.TryGetValue(server_rci, out rv)) { + rv = new SingleServerSubscriberCore(server_rci, _connection_factory); + _server_route_to_subcore_map.Add(server_rci, rv); + rv.onPubSubConnectionChange += _handle_pubsubserver_connection_change; + } + return rv; + } + + + public void _handle_pubsubserver_connection_change(bool is_connected, string server_url) { + if (onPubSubConnectionChange != null) + onPubSubConnectionChange(is_connected, server_url); + + } + + public void unsubscribe(params string[] tags) { + lock (_server_route_to_subcore_map) { + + foreach (string tag in tags) { + var server_rci = _tag_router.get_sub_route_for_tag(tag); + var server_subcore = _find_subscribercore(server_rci); + server_subcore.unsubscribe(tag); + } + } + } + + public IPubSubRouter get_router() { + return _tag_router; + } + + #region IDisposable Members + + public void Dispose() { + foreach (var sssc in _server_route_to_subcore_map.Values) + sssc.Dispose(); + _connection_factory.Dispose(); + } + + #endregion + } +} diff --git a/src/DataStreamSuite/PubSub/Testing/SimpleTCPClient.cs b/src/DataStreamSuite/PubSub/Testing/SimpleTCPClient.cs index c5fff1d8b..b923a52be 100644 --- a/src/DataStreamSuite/PubSub/Testing/SimpleTCPClient.cs +++ b/src/DataStreamSuite/PubSub/Testing/SimpleTCPClient.cs @@ -15,7 +15,7 @@ using System.Transactions; namespace BCG { public class SimpleTCPClient : ITCPConnectionHandler, ITCPMessageHandler { - private readonly BlutoSubAddress _server_addr; + private readonly RemoteConnectionInfo _server_addr; private int _m_msgs_received = 0; private readonly UInt32 _msg_sz = 1024;// * 1024; private readonly int _max_n_msgs = Int32.MaxValue; @@ -23,10 +23,11 @@ namespace BCG { int _send_wait_period_ms = 5000; Action _listener; - public SimpleTCPClient(string server_ip, int server_port, UInt32 msg_sz, int send_wait_period_ms) { + public SimpleTCPClient(string server_ip, int server_port, UInt32 msg_sz, int send_wait_period_ms, int max_n_msgs) { + _max_n_msgs = max_n_msgs; _msg_sz = msg_sz; _send_wait_period_ms = send_wait_period_ms; - _server_addr = new BlutoSubAddress(server_ip, server_port); + _server_addr = new RemoteConnectionInfo(server_ip, server_port); } public void start() { @@ -34,7 +35,10 @@ namespace BCG { } private void _connect() { - bts.AsyncTCPConnector_APM.connect_to(_server_addr, this); + Log.Gen.info($"SimpleTCPClient._connect to: {_server_addr}"); + + bts.AsyncTCPConnector_AsyncWrapper.connect_to(_server_addr, this); + //bts.AsyncTCPConnector_APM.connect_to(_server_addr, this); } public void register_listener(Action cb) { @@ -43,10 +47,10 @@ namespace BCG { public void onConnection(ITCPConnection connection) { string ip; int port; - connection.getPeerAddress(out ip, out port); - bts.Log.Gen.info($"SimpleTCPClientAsync.onConnection connected to server ip: {ip} port: {port}, starting task to send data in a loop"); + var peer_rci = connection.get_peer_address(); + bts.Log.Gen.info($"SimpleTCPClient.onConnection connected to server: {peer_rci}, starting task to send data in a loop"); if (_listener != null) { - _listener.Invoke($"Connected to server ip: {ip} port {port}"); + _listener.Invoke($"Connected to server {peer_rci}"); } connection.register(this); // start sending data @@ -56,14 +60,23 @@ namespace BCG { private void _keep_sending_data(ITCPConnection connection) { byte[] buff = new byte[_msg_sz]; - for (int i = 0; i < buff.Length; i++) { - buff[i] = (byte)i; - } + MemoryStream str = new MemoryStream(buff); + BinaryWriter bw = new BinaryWriter(str); + Action fill_msg = (rep_i) => { + str.Position = 0; + int n_ints = (int)_msg_sz / 4; + for (int i = 0; i < n_ints; i++) { + bw.Write(rep_i); + } + }; + + for (int i = 0; i < _max_n_msgs; i++) { if (!_send_flag) { return; } - bts.Log.Gen.info("Sending msg: {i} sz: {buff.Length}"); + fill_msg(1); + bts.Log.Gen.info($"Sending msg: {i} sz: {buff.Length}"); System.Threading.Thread.Sleep(_send_wait_period_ms); connection.send(buff); _listener.Invoke($"Data sent, sz: {buff.Length}"); @@ -72,9 +85,11 @@ namespace BCG { public void onData(RemoteMessage msg) { _m_msgs_received++; - Console.WriteLine($"SimpleTCPClientAsync.onData n_msgs: {_m_msgs_received} msg: {msg}"); + if (msg.messageType == RemoteMessageType.Connection) + Log.Gen.error($"SimpleTCPClient.onData n_msgs: {_m_msgs_received} msg: {msg}"); _listener.Invoke($"Message received msg: {msg}"); if (msg.messageType == RemoteMessageType.Disconnection) { + Log.Gen.error($"SimpleTCPClient.onData disconnected, reconnecting"); _send_flag = false; _connect(); } diff --git a/src/DataStreamSuite/PubSub/Testing/SimpleTCPServer.cs b/src/DataStreamSuite/PubSub/Testing/SimpleTCPServer.cs index 9be2682ab..a99086c35 100644 --- a/src/DataStreamSuite/PubSub/Testing/SimpleTCPServer.cs +++ b/src/DataStreamSuite/PubSub/Testing/SimpleTCPServer.cs @@ -8,25 +8,23 @@ namespace BCG { public class SimpleTCPServer : ITCPConnectionHandler, ITCPMessageHandler { int _n_msgs_received = 0; bool _isDisposed = false; - AsyncTCPConnectionAcceptor_APM _acceptor; + AsyncTCPConnectionAcceptor_AsyncWrapper _acceptor; IDictionary _conn_map = new Dictionary(); readonly bool _echo_msg_back; public SimpleTCPServer(int port, bool echo_msg_back) { - _acceptor = new AsyncTCPConnectionAcceptor_APM(port, this); + Log.Gen.info($"SimpleTCPServer.const port: {port} echo_msg_back: {echo_msg_back}"); + _acceptor = new AsyncTCPConnectionAcceptor_AsyncWrapper(port, this); _echo_msg_back = echo_msg_back; } public void init() { - //_acceptor = new AsyncTCPConnectionAcceptor_APM(12345, this); - _acceptor.init(); + _acceptor.start(); } public void onConnection(ITCPConnection connection) { - string ip; int port; - connection.getPeerAddress(out ip, out port); - RemoteConnectionInfo rci = new RemoteConnectionInfo(ip, port); + RemoteConnectionInfo rci = connection.get_peer_address(); _conn_map[rci] = connection; bts.Log.Gen.info($"SimpleTCPServer.onConnection new client connected conn: {rci}"); connection.register(this); @@ -34,7 +32,8 @@ namespace BCG { public void onData(RemoteMessage msg) { - var log_msg = $"SimpleTCPServer.onData msg: {msg}"; + _n_msgs_received++; + var log_msg = $"SimpleTCPServer.onData msgs_received: {_n_msgs_received} msg: {msg} _echo_msg_back: {_echo_msg_back}"; Log.Gen.info(log_msg); Console.WriteLine(log_msg); if (!_echo_msg_back) { @@ -44,11 +43,10 @@ namespace BCG { ITCPConnection this_conn; bool found = _conn_map.TryGetValue(rci, out this_conn); if (!found) { - Console.WriteLine("Could not find connection !!!!!!"); + Log.Gen.error($"Could not find connection: {rci}"); return; } - _n_msgs_received++; - Console.WriteLine($"\n\nSimpleTCPServerAsync.onData msgs_received: {_n_msgs_received} msg: {msg} ci: {rci} NOW echoing it back\n\n"); + Log.Gen.info($"\n\n\nSimpleTCPServerAsync.onData msgs_received: {_n_msgs_received} msg: {msg} ci: {rci} NOW echoing it back\n\n\n"); if (msg.messageType == RemoteMessageType.Data) { this_conn.send(msg.message); } else { diff --git a/src/DataStreamSuite/PubSub/documentation/internal_readme.txt b/src/DataStreamSuite/PubSub/documentation/internal_readme.txt new file mode 100644 index 000000000..aaa5afda2 --- /dev/null +++ b/src/DataStreamSuite/PubSub/documentation/internal_readme.txt @@ -0,0 +1,117 @@ +Basic TCP: +ITCPConnection implemented by AsyncTCPConnection_APM is the innermost class resposinsble for TCP sends and received. Its used +on both client and server symmetrically. All the hard async send/receive logic is there. +AsyncTCPConnectionAcceptor_APM opens a port and listens and accepts to connections from the client. It creates the ITCPConnection +on the server. +AsyncTCPConnector_APM connects to the server (above) and creates an ITCPConnection on the client side. + +IPubSubServerConnection: +All communication to PubSubServer happens using this. It has 3 main types of calls: +1. send: to asyncronoulsy end data +2. get data: either through a polling call or callback +3. get connection info: through callbacks + +The only implementation of the above is PubSubServerManagedTCPConnection +(there used to be an MSMQ one and another wrapped around native code - but neither exists anymore) + +PubSubMessages: +PubSubClientMessage is the only messages thats sent from client to pubsubserver. Its serialized on the +client and sent over to the pubsubserver, where uints received ad deserialized + +SubscriberCore:ISubscriberCore (retired now) +| +V +SingleServerSubscriberCore:ISingleServerSubscriberCore + +PublisherCore:IPublisherCore (transactions not supported for now), keeps AllPublishedTagState to cache state on the publisher +| +V +IPubSubServerConnection + +PubSubServer: +PubSubMessageReactor (top level, called from main), contain PubSubState (which has all data and connection state) +ManagedTCPMessageHub : IPubsubMessageHub (this is what handles each ITCPConnection for each connection) + +PubSubState keeps the total pubsub data in 2 classes +Dictionary and +Dictionary +SingleTagData has the tag and IPubSubServerTagHandler (or byte[]) (IPubSubServerTagHandler holds the data state) +for streams the IPubSubServerTagHandler is the PubsubServerTagHandler, which is designed for multiple tags and has a IDictionary +TagStateBank containes the PubsubDeserial izationController, which knows how to deserialize the stream publishes and build state, ad simialirly produce the state on demand +PubsubTagHandlerFactory returns a IPubSubServerTagHandler for each tag, called by the server state handler, SingleTagData and publisher tag state, AllPublishedTagState + +SingleTagConnectionData contains connection vs sub, and connection vs pub +PubSubState calls +SystemSubscriptionMapPublisher.init(this); +SystemStatsPublisher.init(this); +SystemHeartbeatPublisher.init(); +--------------------------------------------------------------- +How internal tags are published? +There are 3 internal publishers (ie compute somerthing an dpublish tit PubSubServer, such that clients can subscribe to it): +SystemStatsPublisher, SystemSubscriptionMapPublisher and SystemHeartbeatPublisher +These are somewhat tricky because they are both listeners to PubUsbState event and intrnally publish, but are also IPubSubServerTagHandler +SystemSubscriptionMapPublisher: +just one instance, a static init is called by PubSubState and it passes itself. SystemSubscriptionMapPublisher subscribes to the event +gets the affected tags, marks them dirty, in doWork creates the state and calls the internal_publish. +Now, as the result of an internal_publish (which is pretty much like a rmote publish as far as the PubsubServer is concerned), SingleTagData +ends up calling SystemSubscriptionMapPublisher (since it also serves as the tagHandler for the tag it publishes via internal_publish) + + + +PubSubState has onPublishStats (tag, sz) that is fired on update_pub_data +onPublishStats is subscribed by SystemStatsPublisher +SystemStatsPublisher.onPublishStats updates the state and on the next doWork calls PubSubMessageReactor.internal_send +SystemStatsPublisher is also an IPubSubServerTagHandler so SingleTagData calls it getContent to get full state + +Streams: +PubTableBroker allows publishing of streams through createTable, addRow, deleteRow, changeRow, makeBatchChanges -> +PubTablePublisher:IPubTablePublisher per tag (addRow, deleteRow, changeRow, createTable, batchRemoveAdd) +PubTablePublisher has BlueDataSerializationController:IBlueDataSerializer to serialize the rows to byte[] +BlueDataSerializationController uses a IBlueDataSerializer, which is specialized for the tag (using UniversalSerializer for now) + +IBlueDataSerializer has just one function +void serialize (byte op, IBlueRowCollection[] rows, out byte[] serializedData); +the second arg is IBlueRowCollection[] because in case of op = StreamOpCode.multipleRemoveAdd, it has multiple IBlueRowCollection for rem and add +(BlueDataSerializer.serialize's comment has the serialization layout) + +For each serializer we have 2 matching deserializers, IPubsubDeserializer (for PubSubservr) and IClientDeserializer (for clients subscribing to streams) +For UniversalSerializer, we have PubsubUniversalDeserializer and ClientUniversalDeserializer + +------------------------------------------------------------------- +TCP publishing: +To run the base TCP layer run PubSubServer as an echo server, +(set run_echo_tcp_server_only in spark\src\DataStreamSuite\PubSubServer\Program.cs) +to run a client that sends a tcp message tot he echo server, run +SimpleTCPEchoStream + + +Pubsub publishing: +----------------- +PubSubTestingStream (bounces pubs across the pubsub server) +mutableAppend(pubSubTesting(100,10000000,100000,"test_1"), +pubSubTesting(250,10000000,100000,"test_2")) + + +Stream publishing: +------------------ +PublisherStream (publishes any stream to the pubsubserver) +r=second(100) +r=project(r,"id") +r=math(r,"x = id*id") +publisher(r, "test_x") + + +tracking message into the pubsubserver +-------------------------------------- +connection: +ServerToClientManagedTCPConnectionAcceptor._on_accept + var log_msg = $"ServerToClientManagedTCPConnectionAcceptor._on_accept called port: {_port} state: {res.AsyncState}"; + Log.Gen.info(log_msg); + +data: +ManagedTCPMessageHub.onData +bts.Log.Gen.info($"ManagedTCPMessgageHub.onData recv msg: {message}"); +PubSubMessageReactor._polling_thread_func +bts.Log.Gen.info($"PubSubMessageReactor._polling_thread_func n_msgs: {n_msgs}"); +PubSubMessageReactor._handle_client_msg +bts.Log.Gen.info($"PubSubMessageReator._handle_client_msg ps_client_msg: {ps_client_msg}"); diff --git a/src/DataStreamSuite/PubSub/documentation/readme.txt b/src/DataStreamSuite/PubSub/documentation/readme.txt index dc7a27efc..64b024e3c 100644 --- a/src/DataStreamSuite/PubSub/documentation/readme.txt +++ b/src/DataStreamSuite/PubSub/documentation/readme.txt @@ -1,117 +1,58 @@ -Basic TCP: -ITCPConnection implemented by AsyncTCPConnection_APM is the innermost class resposinsble for TCP sends and received. Its used -on both client and server symmetrically. All the hard async send/receive logic is there. -AsyncTCPConnectionAcceptor_APM opens a port and listens and accepts to connections from the client. It creates the ITCPConnection -on the server. -AsyncTCPConnector_APM connects to the server (above) and creates an ITCPConnection on the client side. +If the DSQA comes up empty, we need to take it one step at a time and ensure it in the following order: -IPubSubServerConnection: -All communication to PubSubServer happens using this. It has 3 main types of calls: -1. send: to asyncronoulsy end data -2. get data: either through a polling call or callback -3. get connection info: through callbacks +-------------------- +PubsubServer routes: +-------------------- +the client (both publisher and subscriber) need to connect tot he rigth pubsubserver. There are 3 days to do this: +1. Bring up a DSQA and check the title bar, it should be tag:regExp: PubSunRoute +the ip and port matter, the prefix is just fo the human eye. +2. Run the stream pss_routes(). +It will give a row per tag reg exp vs the pss route (pss == pubsub server0) +3. Check the clirnt logs for: +PubSubRouter.get_sub_url_for_tag tag: and PubSubRouter.get_pub_url_for_tag tag: -The only implementation of the above is PubSubServerManagedTCPConnection -(there used to be an MSMQ one and another wrapped around native code - but neither exists anymore) +------------------- +Connection Attempt: +------------------- +Check the pss logs for: +"AsyncTCPConnectionAcceptor_AsyncWrapper.cons started on port:" +Make sure it is listening to the correct port -PubSubMessages: -PubSubClientMessage is the only messages thats sent from client to pubsubserver. Its serialized on the -client and sent over to the pubsubserver, where uints received ad deserialized - -SubscriberCore:ISubscriberCore (retired now) -| -V -SingleServerSubscriberCore:ISingleServerSubscriberCore - -PublisherCore:IPublisherCore (transactions not supported for now), keeps AllPublishedTagState to cache state on the publisher -| -V -IPubSubServerConnection - -PubSubServer: -PubSubMessageReactor (top level, called from main), contain PubSubState (which has all data and connection state) -ManagedTCPMessageHub : IPubsubMessageHub (this is what handles each ITCPConnection for each connection) - -PubSubState keeps the total pubsub data in 2 classes -Dictionary and -Dictionary -SingleTagData has the tag and IPubSubServerTagHandler (or byte[]) (IPubSubServerTagHandler holds the data state) -for streams the IPubSubServerTagHandler is the PubsubServerTagHandler, which is designed for multiple tags and has a IDictionary -TagStateBank containes the PubsubDeserial izationController, which knows how to deserialize the stream publishes and build state, ad simialirly produce the state on demand -PubsubTagHandlerFactory returns a IPubSubServerTagHandler for each tag, called by the server state handler, SingleTagData and publisher tag state, AllPublishedTagState - -SingleTagConnectionData contains connection vs sub, and connection vs pub -PubSubState calls -SystemSubscriptionMapPublisher.init(this); -SystemStatsPublisher.init(this); -SystemHeartbeatPublisher.init(); ---------------------------------------------------------------- -How internal tags are published? -There are 3 internal publishers (ie compute somerthing an dpublish tit PubSubServer, such that clients can subscribe to it): -SystemStatsPublisher, SystemSubscriptionMapPublisher and SystemHeartbeatPublisher -These are somewhat tricky because they are both listeners to PubUsbState event and intrnally publish, but are also IPubSubServerTagHandler -SystemSubscriptionMapPublisher: -just one instance, a static init is called by PubSubState and it passes itself. SystemSubscriptionMapPublisher subscribes to the event -gets the affected tags, marks them dirty, in doWork creates the state and calls the internal_publish. -Now, as the result of an internal_publish (which is pretty much like a rmote publish as far as the PubsubServer is concerned), SingleTagData -ends up calling SystemSubscriptionMapPublisher (since it also serves as the tagHandler for the tag it publishes via internal_publish) +On the client, make sure it is attemping to connect to the right pss +"AsyncTCPConnector_AsyncWrapper.connect_to server:" +------------------------------------ +Successful connection establishment: +------------------------------------ -PubSubState has onPublishStats (tag, sz) that is fired on update_pub_data -onPublishStats is subscribed by SystemStatsPublisher -SystemStatsPublisher.onPublishStats updates the state and on the next doWork calls PubSubMessageReactor.internal_send -SystemStatsPublisher is also an IPubSubServerTagHandler so SingleTagData calls it getContent to get full state +On pss, a successful connection should result in the log: +"calling onConnection now" +The whole log is +Log.Gen.info($"AsyncTCPConnectionAcceptor_AsyncWrapper._begin_accepting port: {_accept_port}, new connection, self: {conn.get_self_address()} peer: {conn.get_peer_address()} calling onConnection now"); -Streams: -PubTableBroker allows publishing of streams through createTable, addRow, deleteRow, changeRow, makeBatchChanges -> -PubTablePublisher:IPubTablePublisher per tag (addRow, deleteRow, changeRow, createTable, batchRemoveAdd) -PubTablePublisher has BlueDataSerializationController:IBlueDataSerializer to serialize the rows to byte[] -BlueDataSerializationController uses a IBlueDataSerializer, which is specialized for the tag (using UniversalSerializer for now) - -IBlueDataSerializer has just one function -void serialize (byte op, IBlueRowCollection[] rows, out byte[] serializedData); -the second arg is IBlueRowCollection[] because in case of op = StreamOpCode.multipleRemoveAdd, it has multiple IBlueRowCollection for rem and add -(BlueDataSerializer.serialize's comment has the serialization layout) - -For each serializer we have 2 matching deserializers, IPubsubDeserializer (for PubSubservr) and IClientDeserializer (for clients subscribing to streams) -For UniversalSerializer, we have PubsubUniversalDeserializer and ClientUniversalDeserializer - -------------------------------------------------------------------- -TCP publishing: -To run the base TCP layer run PubSubServer as an echo server, -(set run_echo_tcp_server_only in spark\src\DataStreamSuite\PubSubServer\Program.cs) -to run a client that sends a tcp message tot he echo server, run -SimpleTCPEchoStream +On the client, a successful connection should result in the log: +"AsyncTCPConnector_AsyncWrapper._connect_to new connection," -Pubsub publishing: ------------------ -PubSubTestingStream (bounces pubs across the pubsub server) -mutableAppend(pubSubTesting(100,10000000,100000,"test_1"), -pubSubTesting(250,10000000,100000,"test_2")) +------------------------------------ +Successful message sent from client: +------------------------------------ +"AsyncTCPConnection_AsyncWrapper._send_fixed_size_msg sent" - -Stream publishing: ------------------- -PublisherStream (publishesa any stream to the pubsubserver) -r=second(100) -r=project(r,"id") -r=math(r,"x = id*id") -publisher(r, "test_x") - - -tracking message into the pubsubserver -------------------------------------- -connection: -ServerToClientManagedTCPConnectionAcceptor._on_accept - var log_msg = $"ServerToClientManagedTCPConnectionAcceptor._on_accept called port: {_port} state: {res.AsyncState}"; - Log.Gen.info(log_msg); +Successful message received on client: +-------------------------------------- +"AsyncTCPConnection_AsyncWrapper._read_fixed_size_msg read" -data: -ManagedTCPMessageHub.onData -bts.Log.Gen.info($"ManagedTCPMessgageHub.onData recv msg: {message}"); -PubSubMessageReactor._polling_thread_func -bts.Log.Gen.info($"PubSubMessageReactor._polling_thread_func n_msgs: {n_msgs}"); -PubSubMessageReactor._handle_client_msg -bts.Log.Gen.info($"PubSubMessageReator._handle_client_msg ps_client_msg: {ps_client_msg}"); + +pss's send/receive is the same log, since it uses the same class AsyncTCPConnection_AsyncWrapper +--------------------------------- +Successful message sent from pss: +--------------------------------- +"AsyncTCPConnection_AsyncWrapper._send_fixed_size_msg sent" + +----------------------------------- +Successful message received on pss: +----------------------------------- +"AsyncTCPConnection_AsyncWrapper._read_fixed_size_msg read" \ No newline at end of file diff --git a/src/DataStreamSuite/PubSubServer/Configurations/PubsubServer_Linux.json b/src/DataStreamSuite/PubSubServer/Configurations/PubsubServer_Linux.json new file mode 100644 index 000000000..4c9a17a45 --- /dev/null +++ b/src/DataStreamSuite/PubSubServer/Configurations/PubsubServer_Linux.json @@ -0,0 +1,61 @@ +{ + "user": "bts", + "pubsub": { + "milliseconds_between_sub_info_updates": 1000, + "milliseconds_between_time_slice_updates": 5000, + "milliseconds_between_no_buffer_space_retries": 100, + "retries_on_no_buffer_space": 1, + "do_it_all_seconds_between_logs": 0, + "heartbeat_interval": 15000, + "missing_heartbeats_before_gc": 50, + "use_managed_sockets": true, + "state_update_period": 5000, + "statistics_update_period": 5000, + "disposed_connection_check_period": 1000, + "message_processing_warning_threshold": 1000, + "server_port": 12345, + "publisher_routes": [ + { + "name": "default", + "server_address": "bts-cloud://192.168.1.80:12345", + "tag": ".*" + } + ], + "subscriber_routes": [ + { + "name": "default", + "server_address": "bts-cloud://192.168.1.80:12345", + "tag": ".*" + } + ], + "max_packet_size": 500000000, + "blue_comm_must_die": true, + "crushable_tags": [], + "tag_type_to_assembly_map": [ + { + "handler_class": "BCG.PubSubServerTagHandler", + "assembly": "DataStreamCore.dll" + } + ], + "server_queue": "PubSubQueue", + "port_range": { + "first": 30400, + "last": 31700 + }, + "bind_to_random_port": false, + "debug_tags": "^NOTAGS$", + "latency_report_threshold_ms": 1500, + "use_substations": false, + "use_dynamic_clients": false, + "is_substation": false, + "internally_publish_sub_info": true, + "use_managed_clients_in_native_code": false, + "compressed_tags": "^NOTAGS$", + "tags_to_report_compression_ratio": "^NOTAGS$", + "disable_msmq": false, + "use_prepublished_server_state": false, + "ip_translation": null, + "gc_activation_threshold": 0, + "wait_period_after_gc": 1000 + } +} \ No newline at end of file diff --git a/src/DataStreamSuite/PubSubServer/Program.cs b/src/DataStreamSuite/PubSubServer/Program.cs index fbcdc066e..5b1be3303 100644 --- a/src/DataStreamSuite/PubSubServer/Program.cs +++ b/src/DataStreamSuite/PubSubServer/Program.cs @@ -12,6 +12,7 @@ using mbts.config; using Spark.Core; using System; +using System.Collections.Specialized; using System.Threading; using System.Threading.Tasks; @@ -24,9 +25,11 @@ int Run(PubSubServerConfig cfg) { cfg.MergeWith(PubSubServerConfig.Default()); PubSubConfig.SetGlobalConfig(Log.notnull(cfg.PubSub)); Configuration.initialize(cfg.Sparkd); - Log.Gen.info("Starting PubSubServer"); + bool run_echo_server = false; + bool echo_msg_back = false; + cfg.SimpleEchoServer = run_echo_server; return cfg.SimpleEchoServer ?? false ? - RunEchoServer(cfg.PubSub.ServerPort.assert_value()) : + RunEchoServer(cfg.PubSub.ServerPort.assert_value(), echo_msg_back) : RunPubSubServer(); } catch (Exception ex) { // Write the error to console first, in case the logging system is compromised. @@ -59,11 +62,14 @@ int RunPubSubServer() { return 0; } -int RunEchoServer(short port) { - Console.WriteLine("Running as TCP Echo server, Hit enter to continue"); +int RunEchoServer(short port, bool echo) { + string log_msg = $"Running as TCP Echo server, port: {port} echo: {echo} Hit enter to continue:"; + Console.WriteLine(log_msg); Console.ReadLine(); - Console.WriteLine($"ready to listen to port: {port}"); - var sts = new SimpleTCPServer(port, true); + var ready_msg = $"ready to listen to port: {port}"; + Log.Gen.info(ready_msg); + Console.WriteLine(ready_msg); + var sts = new SimpleTCPServer(port, echo); sts.init(); Console.CancelKeyPress += OnCancelKeyPress; while (true) { diff --git a/src/DataStreamSuite/DataStream/Primitives/MongoDB/BenzingaNewStream.cs b/src/DataStreamSuite/SharedStreams/Business/BenzingaNews/BenzingaNewsStream.cs similarity index 61% rename from src/DataStreamSuite/DataStream/Primitives/MongoDB/BenzingaNewStream.cs rename to src/DataStreamSuite/SharedStreams/Business/BenzingaNews/BenzingaNewsStream.cs index 7660bcc66..2b0868bef 100644 --- a/src/DataStreamSuite/DataStream/Primitives/MongoDB/BenzingaNewStream.cs +++ b/src/DataStreamSuite/SharedStreams/Business/BenzingaNews/BenzingaNewsStream.cs @@ -7,26 +7,45 @@ namespace bts { using System.Text.Json; using System.Text.Json.Nodes; [DataStreamUserRespresentation("benzingaNews")] - public class BenzingaNewStream : ViewStream { + public class BenzingaNewsStream : ViewStream { private IBlueTableSchema _schema = null; private int _id = 0; - // constructor takes in the raw mongo db stream, and the time to live (ttl), "7d" for example - public BenzingaNewStream(ViewStream mongodb_raw_stream, string ttl) { + + + private static ViewStream _pre_process_raw_kvstream(ViewStream mongo_db_str) { + ViewStream r = new KeyValueToRelationalStream(mongo_db_str, "doc_id", "key", "value"); + r = new DateStandardizationStream(r, "created_at", "ISO8601"); + return r; + } + + public BenzingaNewsStream(string connection_string, string db_name, string collection_name, string poll_period, string ttl) + : this(new MongoDBStream(connection_string, db_name, collection_name, poll_period), ttl) { + } + + // public BenzingaNewsStream() + // : this(new MongoDBStream(DataStreamPub connection_string, db_name, collection_name, poll_period), ttl) { + // } + + // assumes it gets a raw mongodb_raw_kv_stream with key value pairs + public BenzingaNewsStream(ViewStream mongodb_raw_kv_stream, string ttl) { + ViewStream output_stream = _pre_process_raw_kvstream(mongodb_raw_kv_stream); // Hiding body (with project, columns can be hidden, or renamed) - ViewStream output_stream = new ProjectStream(mongodb_raw_stream, "!body"); + output_stream = new ProjectStream(output_stream, "!body"); // add column news_source = 'Benzinga', so we can append other news sources output_stream = new AddColumnsStream(output_stream, @"news_source : Benzinga"); // now SuperMapStream is used to map one row into multiple, one per symbol, // (SuperMapStream takes 2 lambdas, one to get the enw schema and another to // return an array of rows, per one row) - output_stream = new SuperMapStream(mongodb_raw_stream, + output_stream = new SuperMapStream(output_stream, (IBlueTableSchema s) => { // this lambda returns the new schema (ie with extra cols symbol, exchange, is_primary_exchange) if (_schema == null) { var out_schema = s; out_schema = BlueDataUtility.remove_columns(out_schema, "securities"); - out_schema = BlueDataUtility.add_column(s, "doc_id_internal", typeof(string)); + out_schema = BlueDataUtility.remove_columns(out_schema, "body"); + out_schema = BlueDataUtility.remove_columns(out_schema, "tags"); + out_schema = BlueDataUtility.add_column(out_schema, "doc_id_internal", typeof(string)); out_schema = BlueDataUtility.add_column(out_schema, "symbol", typeof(string)); out_schema = BlueDataUtility.add_column(out_schema, "exchange", typeof(string)); out_schema = BlueDataUtility.add_column(out_schema, "is_primary_exchange", typeof(bool)); @@ -44,11 +63,13 @@ namespace bts { } foreach (JsonNode jnode in json_objs) { if (jnode is JsonObject json_object) { + string symbol = jnode["symbol"] == null ? String.Empty : jnode["symbol"].ToString(); + string exchange = jnode["exchange"] == null ? String.Empty : jnode["exchange"].ToString(); MutableBlueRow nr = new MutableBlueRow(_schema, r); nr.setValue("id", _id++); nr.setValue("doc_id_internal", $"{r["doc_id"]}_{jnode["symbol"]}"); - nr.setValue("symbol", jnode["symbol"]); - nr.setValue("exchange", jnode["exchange"]); + nr.setValue("symbol", symbol); + nr.setValue("exchange", exchange); nr.setValue("is_primary_exchange", Boolean.Parse(jnode["primary"].ToString())); expanded_rows.Add(nr); } diff --git a/src/DataStreamSuite/SharedStreams/Business/BenzingaNews/BenzingaNewsSymbolStateStream.cs b/src/DataStreamSuite/SharedStreams/Business/BenzingaNews/BenzingaNewsSymbolStateStream.cs new file mode 100644 index 000000000..944c9b73a --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/Business/BenzingaNews/BenzingaNewsSymbolStateStream.cs @@ -0,0 +1,33 @@ +namespace bts { + using BCG; + + using System.Collections.Generic; + using System.Linq; + using System.Security.Cryptography; + + //[DataStreamUserRespresentation("benzingaNewsSymbols")] + public class BenzingaNewsSymbolStateStream : ViewStream, INonIncGroupByEvaluator { + public BenzingaNewsSymbolStateStream(ViewStream news_str) { + ViewStream r = new NonIncGroupByStream(news_str, this); + mySetRealSource(r); + } + public BenzingaNewsSymbolStateStream(string connection_string, string db_name, string collection_name, string poll_period, string ttl) : + this(new BenzingaNewsStream(connection_string, db_name, collection_name, poll_period, ttl)) { + } + + public IBlueRowCollection evaluate(IDictionary> grouped_rows) { + BlueTable rv = null; + foreach (var kv in grouped_rows) { + var symbol_rows = kv.Value; + IBlueRow state_row = BlueDataUtility.find_max(symbol_rows, "created_at"); + rv = rv == null ? new BlueTable(state_row.schema) : rv; + rv.addRow(state_row); + } + return rv; + } + + public string[] get_group_by_cols() { + return new string[] { "symbol" }; + } + } +} \ No newline at end of file diff --git a/src/DataStreamSuite/SharedStreams/Business/BenzingaNews/BenzingaNewsSymbolsStream.cs b/src/DataStreamSuite/SharedStreams/Business/BenzingaNews/BenzingaNewsSymbolsStream.cs new file mode 100644 index 000000000..b29ebbb6c --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/Business/BenzingaNews/BenzingaNewsSymbolsStream.cs @@ -0,0 +1,14 @@ +namespace bts { + using BCG; + [DataStreamUserRespresentation("benzingaNewsSymbols")] + + public class BenzingaNewsSymbolsStream : ViewStream { + public BenzingaNewsSymbolsStream(ViewStream news_str) { + ViewStream rs = new DistinctRowStream(news_str, "symbol"); + mySetRealSource(rs); + } + public BenzingaNewsSymbolsStream(string connection_string, string db_name, string collection_name, string poll_period, string ttl) : + this(new BenzingaNewsStream(connection_string, db_name, collection_name, poll_period, ttl)) { + } + } +} \ No newline at end of file diff --git a/src/DataStreamSuite/SharedStreams/Business/MarketData/BookStream.cs b/src/DataStreamSuite/SharedStreams/Business/MarketData/BookStream.cs index 43caebf85..eb84462a0 100644 --- a/src/DataStreamSuite/SharedStreams/Business/MarketData/BookStream.cs +++ b/src/DataStreamSuite/SharedStreams/Business/MarketData/BookStream.cs @@ -62,7 +62,7 @@ namespace BCG { } private void _on_books(TableUpdate update) { - _log_updates(update); + //_log_updates(update); bts.Log.Gen.info($"BookStream._on_books state: {update.state.Count()} changes: {update.changes.Count()} added: {update.added.Count()}"); _cached_state = update.state; } diff --git a/src/DataStreamSuite/SharedStreams/Config/SharedStreamConfig.cs b/src/DataStreamSuite/SharedStreams/Config/SharedStreamConfig.cs new file mode 100644 index 000000000..aa34ab624 --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/Config/SharedStreamConfig.cs @@ -0,0 +1,48 @@ +namespace Bts.DataStreamPublisher; + +using Bts.PubSub; + +//using CommandLine; + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using System.Text.Json.Serialization; + +public class SharedStreamConfig { + + [JsonPropertyName("mongodb_url")] + public string MONGO_DB_URL { get; set; } + + [JsonPropertyName("mongodb_db_name")] + public string MONGO_DB_NAME { get; set; } + + [JsonPropertyName("mongodb_db_collection")] + public string MONGO_DB_COLLECTION { get; set; } + + [JsonPropertyName("benzinga_news_ttl")] + public string BENZINGA_NEWS_TTL { get; set; } + + [JsonPropertyName("pubsub")] + public PubSubConfig? PubSub { get; set; } + + + /// + /// Merges options with those defined in `ConfigFile` (does not overwrite + /// non-null existing values). + /// + /// + /// JsonSerializer.Deserialize returns null + /// + public void MergeWithConfigFile() { + // if (ConfigFile is null) { + // return; + // } + // var cfgString = File.ReadAllText(ConfigFile); + // var parsedCfg = JsonSerializer.Deserialize(cfgString) ?? + // throw new InvalidOperationException($"Failed to parse json from {ConfigFile}"); + // MergeWith(parsedCfg); + // ConfigFile = null; + } +} diff --git a/src/DataStreamSuite/SharedStreams/System/PS3/Config b/src/DataStreamSuite/SharedStreams/System/PS3/Config new file mode 100644 index 000000000..e69de29bb diff --git a/src/DataStreamSuite/SharedStreams/System/PS3/Health/DeadPublisherTagsStream.cs b/src/DataStreamSuite/SharedStreams/System/PS3/Health/DeadPublisherTagsStream.cs index ccad30c47..63e89efba 100644 --- a/src/DataStreamSuite/SharedStreams/System/PS3/Health/DeadPublisherTagsStream.cs +++ b/src/DataStreamSuite/SharedStreams/System/PS3/Health/DeadPublisherTagsStream.cs @@ -1,19 +1,14 @@ -using System; -using System.Collections.Generic; -using System.Text; +using bts; -namespace BCG -{ +namespace BCG { /// /// List of all the tags that result from a /// dead publisher, ie tags that have data /// but no active publisher /// - [DataStreamUserRespresentation ("deadPublisherTags")] - public class DeadPublisherTagsStream : ViewStream - { - public DeadPublisherTagsStream() - { + [DataStreamUserRespresentation("deadPublisherTags")] + public class DeadPublisherTagsStream : ViewStream { + public DeadPublisherTagsStream() { ViewStream serverState = new PubSubServerStateStream(); serverState = new FilterStream(serverState, "publishers='' and deadPublishers<>''"); serverState = new ProjectStream(serverState, "!subscribers publishers deadPublishers"); diff --git a/src/DataStreamSuite/SharedStreams/System/PS3/PubsubRoutesStream.cs b/src/DataStreamSuite/SharedStreams/System/PS3/PubsubRoutesStream.cs new file mode 100644 index 000000000..738635b6b --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/System/PS3/PubsubRoutesStream.cs @@ -0,0 +1,28 @@ +namespace BCG { + [DataStreamUserRespresentation("pss_routes")] + public class PubsubRoutesStream : ViewStream { + private ViewStreamDatabase _vsd; + private IPubSubRouter _router = new PubSubRouter(); + + public PubsubRoutesStream() + : this(ViewStreamDatabase.instance) { } + + public PubsubRoutesStream(ViewStreamDatabase vsd) { + _vsd = vsd; + } + + protected override void myOnFirstSubscriber() { + IBlueTableSchema schema = BlueDataUtility.form_schema("PubSubRoutes", + Tuple.Create("id", TypeCode.Int32), + Tuple.Create("tag_regexp", TypeCode.String), + Tuple.Create("server_url", TypeCode.String)); + BlueTable rows = new BlueTable(schema); + var routes = _router.sub_routes(); + foreach (var route in routes) { + IBlueRow nr = new BlueRow(schema, rows.Count, route.tag_reg_exp, route.server_address); + rows.addRow(nr); + } + myFireEvent(new DataPacket(rows, rows, new BlueTable(schema))); + } + } +} \ No newline at end of file diff --git a/src/DataStreamSuite/SharedStreams/System/PS3/Stats/PubSubServerTagStatsStream.cs b/src/DataStreamSuite/SharedStreams/System/PS3/Stats/PubSubServerTagStatsStream.cs index 2f2acabcb..17e5a172a 100644 --- a/src/DataStreamSuite/SharedStreams/System/PS3/Stats/PubSubServerTagStatsStream.cs +++ b/src/DataStreamSuite/SharedStreams/System/PS3/Stats/PubSubServerTagStatsStream.cs @@ -5,9 +5,7 @@ using BCG.Utilities.General; using MathNet.Numerics.RootFinding; namespace bts { - - - [DataStreamUserRespresentation("tagStats")] + [DataStreamUserRespresentation("pss_stats")] public class PubSubServerTagStatsStream : ViewStream, IWorker { private SubscriberCore _sub_core; private ViewStreamDatabase _vsd; diff --git a/src/DataStreamSuite/SharedStreams/System/PS3/Subscription/AllTagsStream.cs b/src/DataStreamSuite/SharedStreams/System/PS3/Subscription/AllTagsStream.cs index 1a0f20281..786a38bca 100644 --- a/src/DataStreamSuite/SharedStreams/System/PS3/Subscription/AllTagsStream.cs +++ b/src/DataStreamSuite/SharedStreams/System/PS3/Subscription/AllTagsStream.cs @@ -1,50 +1,50 @@ -using System; -using System.Collections; -using System.IO; - -using BCG.Utilities.General; -using BCG.Utilities; -using Bts.PubSub; -using Spark.Core; - -namespace BCG { - - public class AllTagsStream : ViewStream, IWorker { - private IWorker myRealWorkerStream; - public AllTagsStream() - : this("") { } - - public AllTagsStream(string prefix) - : this(prefix, ViewStreamDatabase.instance) { } - - public AllTagsStream(ViewStreamDatabase vsd, string regExp) { - ViewStream rs; - mySetRealSource(rs = new TagSynopsisStream(vsd, regExp, true)); - myRealWorkerStream = rs as IWorker; - } - - public AllTagsStream(string prefix, ViewStreamDatabase db) - : this(prefix, db, db.subscriber.get_router()) { } - - public AllTagsStream(string prefix, ViewStreamDatabase db, IPubSubRouter router) { - ViewStream rs = null; - //if we're using substations, we don't care about the router - if (PubSubConfig.Instance.UseSubstations.assert_value()) { - mySetRealSource(rs = new TagSynopsisStream(db, "^" + prefix + ".*", true)); - } else { - mySetRealSource(rs = new TagSynopsisStream(db, router.get_all_pubsub_sub_urls(), "^" + prefix + ".*", true)); - } - myRealWorkerStream = rs as IWorker; - } - - #region IWorker Members - - public void doWork() { - if (myRealWorkerStream != null) - myRealWorkerStream.doWork(); - } - - #endregion - } - -} +// using System; +// using System.Collections; +// using System.IO; + +// using BCG.Utilities.General; +// using BCG.Utilities; +// using Bts.PubSub; +// using Spark.Core; + +// namespace BCG { + +// public class AllTagsStream : ViewStream, IWorker { +// private IWorker myRealWorkerStream; +// public AllTagsStream() +// : this("") { } + +// public AllTagsStream(string prefix) +// : this(prefix, ViewStreamDatabase.instance) { } + +// public AllTagsStream(ViewStreamDatabase vsd, string regExp) { +// ViewStream rs; +// mySetRealSource(rs = new TagSynopsisStream(vsd, regExp, true)); +// myRealWorkerStream = rs as IWorker; +// } + +// public AllTagsStream(string prefix, ViewStreamDatabase db) +// : this(prefix, db, db.subscriber.get_router()) { } + +// public AllTagsStream(string prefix, ViewStreamDatabase db, IPubSubRouter router) { +// ViewStream rs = null; +// //if we're using substations, we don't care about the router +// if (PubSubConfig.Instance.UseSubstations.assert_value()) { +// mySetRealSource(rs = new TagSynopsisStream(db, "^" + prefix + ".*", true)); +// } else { +// mySetRealSource(rs = new TagSynopsisStream(db, router.get_all_pubsub_sub_urls(), "^" + prefix + ".*", true)); +// } +// myRealWorkerStream = rs as IWorker; +// } + +// #region IWorker Members + +// public void doWork() { +// if (myRealWorkerStream != null) +// myRealWorkerStream.doWork(); +// } + +// #endregion +// } + +// } diff --git a/src/DataStreamSuite/SharedStreams/System/PS3/Subscription/PubSubServerStateStream.cs b/src/DataStreamSuite/SharedStreams/System/PS3/Subscription/PubSubServerStateStream.cs index 6ec046d62..f395cfbfb 100644 --- a/src/DataStreamSuite/SharedStreams/System/PS3/Subscription/PubSubServerStateStream.cs +++ b/src/DataStreamSuite/SharedStreams/System/PS3/Subscription/PubSubServerStateStream.cs @@ -1,16 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Text; using BCG.Utilities.General; -using System.Collections; -using System.IO; -using MongoDB.Driver.Core.WireProtocol.Messages; +using BCG; -namespace BCG { +namespace bts { /// /// Gets the subscription and publication state for one /// server. /// + [DataStreamUserRespresentation("pss_state")] public class PubSubServerStateStream : ViewStream, IWorker { private IDictionary _tag_map = new Dictionary(); private readonly string _tag = "System_AllSubscriptions"; diff --git a/src/DataStreamSuite/SharedStreams/System/PS3/Subscription/TagSynopsisStream.cs b/src/DataStreamSuite/SharedStreams/System/PS3/Subscription/TagSynopsisStream.cs index 62f9dd29b..b410762b2 100644 --- a/src/DataStreamSuite/SharedStreams/System/PS3/Subscription/TagSynopsisStream.cs +++ b/src/DataStreamSuite/SharedStreams/System/PS3/Subscription/TagSynopsisStream.cs @@ -1,117 +1,117 @@ -using System; -using System.Collections.Generic; -using System.Text; -using BCG.Utilities.General; -using System.Collections; -using System.IO; -using Bts.PubSub; -using bts; - -namespace BCG { - [DataStreamUserRespresentation("tagSynopsis")] - public class TagSynopsisStream : ViewStream, IStreamMapper, IWorker { - private List myWorkers = new List(); - IBlueTableSchema mySchema = new BlueTableSchema("AllTags", - new ColumnInfo("id", 0, typeof(int)), - new ColumnInfo("tag", 1, typeof(string)), - new ColumnInfo("subscribers", 2, typeof(int)), - new ColumnInfo("pubSub", 3, typeof(string)), - new ColumnInfo("dataPresent", 4, typeof(bool))); - - public TagSynopsisStream() { - mySetRealSource(new TagSynopsisStream(ViewStreamDatabase.instance, ViewStreamDatabase.instance.subscriber.get_router().get_all_pubsub_sub_urls())); - } - - public TagSynopsisStream(string tagRegExp) { - mySetRealSource(new TagSynopsisStream(ViewStreamDatabase.instance, ViewStreamDatabase.instance.subscriber.get_router().get_all_pubsub_sub_urls(), tagRegExp)); - } - - public TagSynopsisStream(ViewStreamDatabase vsd, string route) { - - ViewStream vs = new PubSubServerStateStream(/*route,*/ vsd); - vs = new MapStream(vs, this); - myWorkers.Add(vs as IWorker); - - mySetRealSource(vs); - } - - - public TagSynopsisStream(bool cons_overloader, string route) : - this(ViewStreamDatabase.instance, new string[] { route }) { - } - - public TagSynopsisStream(ViewStreamDatabase vsd, ICollection routes) { - List vss = new List(); - foreach (string r in routes) { - ViewStream vs = new PubSubServerStateStream(/*r,*/ vsd); - vs = new MapStream(vs, this); - vss.Add(vs); - myWorkers.Add(vs as IWorker); - } - mySetRealSource(new AppendStream(vss.ToArray())); - } - - public TagSynopsisStream(ViewStreamDatabase vsd, string tagRegExp, bool filterOutNonPublished) { - // if (PubSub3Config.instance.PS3_UseSubstations) - // { - // mySetRealSource(new ThreadSafeStream(new SubstationTagSynopsisStream(vsd, tagRegExp, filterOutNonPublished))); - - // } - // else - { - PubSubRouter theRouter = new(Log.notnull(PubSubConfig.Instance.SubscriberRoutes).ToArray()); - ICollection thisVSDRoutes = theRouter.get_all_pubsub_sub_urls(); - - ViewStream vs = new FilterStream(new TagSynopsisStream(vsd, thisVSDRoutes), "tag", tagRegExp); - - if (filterOutNonPublished) - vs = new FilterStream(vs, "dataPresent=true"); - mySetRealSource(vs); - } - - } - - public TagSynopsisStream(ViewStreamDatabase vsd, ICollection routes, string tagRegExp) { - mySetRealSource(new FilterStream(new TagSynopsisStream(vsd, routes), "tag", tagRegExp)); - } - - public TagSynopsisStream(ViewStreamDatabase vsd, ICollection routes, string tagRegExp, bool filterOutNonPublished) { - ViewStream vs = new TagSynopsisStream(vsd, routes, tagRegExp); - if (filterOutNonPublished) - vs = new FilterStream(vs, "dataPresent=true"); - mySetRealSource(vs); - } - - - #region IStreamMapper Members - - public IBlueTableSchema getOutputSchema(IBlueTableSchema inputSchema) { - return mySchema; - } - - #endregion - - #region IDynamicStreamMapper Members - - public IBlueRow map(IBlueRow row) { - string subValue = row["subscribers"].ToString().Trim(); - return new BlueRow(getOutputSchema(null), - row["id"], - row["tag"], - subValue.Length == 0 ? 0 : subValue.Split(',').Length, - row["server"], - row["publishers"].ToString().Length > 0 || row["deadPublishers"].ToString().Length > 0); - } - - #endregion - - #region IWorker Members - - public void doWork() { - foreach (IWorker w in myWorkers) - w.doWork(); - } - - #endregion - } -} +// using System; +// using System.Collections.Generic; +// using System.Text; +// using BCG.Utilities.General; +// using System.Collections; +// using System.IO; +// using Bts.PubSub; +// using bts; + +// namespace BCG { +// [DataStreamUserRespresentation("tagSynopsis")] +// public class TagSynopsisStream : ViewStream, IStreamMapper, IWorker { +// private List myWorkers = new List(); +// IBlueTableSchema mySchema = new BlueTableSchema("AllTags", +// new ColumnInfo("id", 0, typeof(int)), +// new ColumnInfo("tag", 1, typeof(string)), +// new ColumnInfo("subscribers", 2, typeof(int)), +// new ColumnInfo("pubSub", 3, typeof(string)), +// new ColumnInfo("dataPresent", 4, typeof(bool))); + +// public TagSynopsisStream() { +// mySetRealSource(new TagSynopsisStream(ViewStreamDatabase.instance, ViewStreamDatabase.instance.subscriber.get_router().get_all_pubsub_sub_urls())); +// } + +// public TagSynopsisStream(string tagRegExp) { +// mySetRealSource(new TagSynopsisStream(ViewStreamDatabase.instance, ViewStreamDatabase.instance.subscriber.get_router().get_all_pubsub_sub_urls(), tagRegExp)); +// } + +// public TagSynopsisStream(ViewStreamDatabase vsd, string route) { + +// ViewStream vs = new PubSubServerStateStream(/*route,*/ vsd); +// vs = new MapStream(vs, this); +// myWorkers.Add(vs as IWorker); + +// mySetRealSource(vs); +// } + + +// public TagSynopsisStream(bool cons_overloader, string route) : +// this(ViewStreamDatabase.instance, new string[] { route }) { +// } + +// public TagSynopsisStream(ViewStreamDatabase vsd, ICollection routes) { +// List vss = new List(); +// foreach (string r in routes) { +// ViewStream vs = new PubSubServerStateStream(/*r,*/ vsd); +// vs = new MapStream(vs, this); +// vss.Add(vs); +// myWorkers.Add(vs as IWorker); +// } +// mySetRealSource(new AppendStream(vss.ToArray())); +// } + +// public TagSynopsisStream(ViewStreamDatabase vsd, string tagRegExp, bool filterOutNonPublished) { +// // if (PubSub3Config.instance.PS3_UseSubstations) +// // { +// // mySetRealSource(new ThreadSafeStream(new SubstationTagSynopsisStream(vsd, tagRegExp, filterOutNonPublished))); + +// // } +// // else +// { +// PubSubRouter theRouter = new(Log.notnull(PubSubConfig.Instance.SubscriberRoutes).ToArray()); +// ICollection thisVSDRoutes = theRouter.get_all_pubsub_sub_urls(); + +// ViewStream vs = new FilterStream(new TagSynopsisStream(vsd, thisVSDRoutes), "tag", tagRegExp); + +// if (filterOutNonPublished) +// vs = new FilterStream(vs, "dataPresent=true"); +// mySetRealSource(vs); +// } + +// } + +// public TagSynopsisStream(ViewStreamDatabase vsd, ICollection routes, string tagRegExp) { +// mySetRealSource(new FilterStream(new TagSynopsisStream(vsd, routes), "tag", tagRegExp)); +// } + +// public TagSynopsisStream(ViewStreamDatabase vsd, ICollection routes, string tagRegExp, bool filterOutNonPublished) { +// ViewStream vs = new TagSynopsisStream(vsd, routes, tagRegExp); +// if (filterOutNonPublished) +// vs = new FilterStream(vs, "dataPresent=true"); +// mySetRealSource(vs); +// } + + +// #region IStreamMapper Members + +// public IBlueTableSchema getOutputSchema(IBlueTableSchema inputSchema) { +// return mySchema; +// } + +// #endregion + +// #region IDynamicStreamMapper Members + +// public IBlueRow map(IBlueRow row) { +// string subValue = row["subscribers"].ToString().Trim(); +// return new BlueRow(getOutputSchema(null), +// row["id"], +// row["tag"], +// subValue.Length == 0 ? 0 : subValue.Split(',').Length, +// row["server"], +// row["publishers"].ToString().Length > 0 || row["deadPublishers"].ToString().Length > 0); +// } + +// #endregion + +// #region IWorker Members + +// public void doWork() { +// foreach (IWorker w in myWorkers) +// w.doWork(); +// } + +// #endregion +// } +// } diff --git a/src/DataStreamSuite/SharedStreams/System/PS3/TableMetaDataStream.cs b/src/DataStreamSuite/SharedStreams/System/PS3/TableMetaDataStream.cs new file mode 100644 index 000000000..49ab64a91 --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/System/PS3/TableMetaDataStream.cs @@ -0,0 +1,114 @@ +namespace bts +{ + using BCG; + using BCG.Utilities.General; + + public class TableMetaDataStream : ViewStream, IWorker + { + private class TableState + { + public ViewStream table_stream; + public IBlueTableSchema schema = null; + public bool processed = false; + public TableState(ViewStream table_stream_) + { + table_stream = table_stream_; + table_stream.onChange += _handle_table_update; + } + private void _handle_table_update(object dp_obj) + { + DataPacket dp = dp_obj as DataPacket; + schema = dp.schema; + } + public void unsub() + { + table_stream.onChange -= _handle_table_update; + } + } + private IBlueTableSchema _schema = BlueDataUtility.form_schema("TableMetaData", + Tuple.Create("id", TypeCode.Int32), + Tuple.Create("table_name", TypeCode.String), + Tuple.Create("col_idx", TypeCode.Int32), + Tuple.Create("col_type_code", TypeCode.Int32), + Tuple.Create("col_name", TypeCode.String)); + + private ViewStreamDatabase _vsd; + private ViewStream _base_stream; + private IDictionary _table_map = new Dictionary(); + private BlueTable _state; + public TableMetaDataStream() + : this(ViewStreamDatabase.instance) { } + public TableMetaDataStream(ViewStreamDatabase vsd) + { + _vsd = vsd; + _base_stream = new PubSubServerStateStream(_vsd); + _state = new BlueTable(_schema); + } + protected override void myOnFirstSubscriber() + { + _base_stream.onChange += _handle_base_stream; + _vsd.addWorker(this); + } + + protected override void myOnLastSubscriber() + { + _base_stream.onChange -= _handle_base_stream; + _vsd.removeWorker(this); + } + + public void doWork() + { + bool changed = false; + foreach (TableState ts in _table_map.Values) + { + if (!ts.processed && ts.schema != null) + { + foreach (ColumnInfo ci in ts.schema.columnInfo) + { + int id = _state.Count; + var table_name = ts.schema.tableName; + var col_idx = ci.colNo; + var col_name = ci.colName; + TypeCode type_code = BlueDataUtility.get_typecode(ci.colType); + BlueRow nr = new BlueRow(_schema, id, table_name, col_idx, Convert.ToInt32(type_code), + col_name); + changed = true; + _state.addRow(nr); + } + ts.processed = true; + ts.unsub(); + } + } + if (changed) + { + var dp_out = BlueDataUtility.build_dp_inc(_state, myLastValue as DataPacket); + myFireEvent(dp_out); + } + } + + private void _handle_base_stream(object dp_obj) + { + DataPacket dp = dp_obj as DataPacket; + foreach (IBlueRow r in dp.newRows) + { + string tag = r.get("tag"); + if (tag.StartsWith("DS_")) + { + _handle_table(tag); + } + } + } + + private void _handle_table(string tag_name) + { + Log.assert(tag_name.StartsWith("DS_")); + string table_name = tag_name.Remove(0, 3); + TableState ts = null; + if (!_table_map.TryGetValue(table_name, out ts)) + { + ts = new TableState(new TableStream(table_name, _vsd)); + _table_map.Add(table_name, ts); + } + } + } +} \ No newline at end of file diff --git a/src/Spark.Admin.WebApp/src/Accounts/Types.fs b/src/Spark.Admin.WebApp/src/Accounts/Types.fs index c7ddfa7f0..eaf9be013 100644 --- a/src/Spark.Admin.WebApp/src/Accounts/Types.fs +++ b/src/Spark.Admin.WebApp/src/Accounts/Types.fs @@ -17,7 +17,7 @@ type Tab = | PositionManagementTab | MarginTab -let venues = [| Venue.BINANCE; Venue.BinanceUs; Venue.BinanceUsdsFutures; Venue.COINBASE; Venue.DERIBIT; Venue.GLBX; Venue.ICE; Venue.SIM; |] +let venues = [| Venue.BINANCE; Venue.BinanceUs; Venue.BinanceUsdsFutures; Venue.CBOE; Venue.COINBASE; Venue.DERIBIT; Venue.GLBX; Venue.ICE; Venue.TAIFEX; Venue.SIM; |] let securityTypes = [| SecurityType.SPOT; SecurityType.FUTURE; SecurityType.OPTION; SecurityType.SPREAD; |] @@ -69,6 +69,11 @@ type ICEExchangeField = | AccountCode of string | MiscTagMapping of JSMap +type TaifexExchangeField = + | CTI of CTICode + | Origin of CustomerOrFirm + | ClearingAccount of string + type SIMExchangeField = | CTI of CTICode | Origin of CustomerOrFirm diff --git a/src/Spark.Admin.WebApp/src/Accounts/View.fs b/src/Spark.Admin.WebApp/src/Accounts/View.fs index 9293bf565..5877e8d80 100644 --- a/src/Spark.Admin.WebApp/src/Accounts/View.fs +++ b/src/Spark.Admin.WebApp/src/Accounts/View.fs @@ -797,9 +797,9 @@ let venueToString (venue:bts.api.Venue) = | bts.api.Venue.BINANCE -> "BINANCE" | bts.api.Venue.BinanceUs -> "BinanceUs" | bts.api.Venue.BinanceUsdsFutures -> "BinanceUsdsFutures" - | bts.api.Venue.COINBASE -> "COINBASE" | bts.api.Venue.FTX -> "FTX" | bts.api.Venue.OKX -> "OKX" + | bts.api.Venue.TAIFEX -> "TAIFEX" let exchange_display expirationNameList = let s = sprintf "%O" expirationNameList.product.exchange diff --git a/src/client/spark/Orders/OrderTypeVMs/OrderTypeVMFactory.cs b/src/client/spark/Orders/OrderTypeVMs/OrderTypeVMFactory.cs index 563999c11..f099da8b2 100644 --- a/src/client/spark/Orders/OrderTypeVMs/OrderTypeVMFactory.cs +++ b/src/client/spark/Orders/OrderTypeVMs/OrderTypeVMFactory.cs @@ -1,1099 +1,1099 @@ -using bts; -using bts.api; -using bts.collections; -using bts.spark; -using bts.utils; - -using Google.Protobuf; -using Google.Protobuf.Reflection; - -using mbts.collections; -using mbts.spark.utilities; -using mbts.ui.shell; -using mbts.ui.utilities; -using mbts.ui.utility; -using mbts.utils; - -using Spark.Api.Orders; -using Spark.Core; -using Spark.Core.Collections; -using Spark.Core.Disposables; -using Spark.Core.Reactive; - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Dynamic; -using System.Linq; -using System.Reactive; -using System.Reactive.Linq; -using System.Runtime.CompilerServices; -using System.Windows.Input; - -using AlgoDef = bts.api.orderman.CustomOrderDefinition; -using AlgoDefi = bts.api.orderman.CustomOrderDefinitionImmutable; -using AlgoType = bts.api.orderman.CustomOrderDefinition.CustomOneofCase; - -namespace mbts.spark { - enum AlgoEditingPermissions { - None = 0, - AllowEditValues = 1, - AllowEditStructure = 1 << 1, - AllowSaveValues = 1 << 2, - AllowSaveStructure = 1 << 3, - } - - static partial class OrderTypeVMFactory { - public const AlgoEditingPermissions default_editing_permissions = AlgoEditingPermissions.AllowEditValues | AlgoEditingPermissions.AllowEditStructure; - - public static IAlgoVM market() => new MarketOrderVM(); - public static IAlgoVM limit() => new LimitOrderVM(); - public static IAlgoVM stop(AlgoKey key, string display_name) => new StopOrderVM(key, display_name, default_editing_permissions); - public static IAlgoVM stop_limit(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new StopLimitOrderVM(key, display_name, editing_permissions); - public static IAlgoVM time_box(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new TimeBoxOrderVM(key, display_name, editing_permissions); - public static IAlgoVM tick(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new TickOrderVM(key, display_name, editing_permissions); - public static IAlgoVM lean(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new LeanOrderVM(key, display_name, editing_permissions); - public static IAlgoVM join(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new JoinOrderVM(key, display_name, editing_permissions); - public static IAlgoVM top(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new TopOrderVM(key, display_name, editing_permissions); - public static IAlgoVM cover(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new CoverOrderVM(key, display_name, editing_permissions); - public static IAlgoVM oco(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new OCOOrderVM(key, display_name, editing_permissions); - public static IAlgoVM pricer(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new PricerOrderVM(key, display_name, editing_permissions); - public static IAlgoVM offset(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new OffsetOrderVM(key, display_name, editing_permissions); - public static IAlgoVM trigger(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new TriggerOrderVM(key, display_name, editing_permissions); - public static IAlgoVM glbx_iceberg(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new GLBXIcebergOrderVM(key, display_name, editing_permissions); - public static IAlgoVM iceberg(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new IcebergOrderVM(key, display_name, editing_permissions); - public static IAlgoVM spreader(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new SpreaderOrderVM(key, display_name, editing_permissions); - public static IAlgoVM dynamic(AlgoKey key, string display_name, string dynamic_type, AlgoEditingPermissions editing_permissions) => new DynamicOrderVM(key, dynamic_type, display_name, editing_permissions); - public static IAlgoVM splitter(AlgoKey key, string display_name, AlgoEditingPermissions permissions) => new SplitterAlgoVM(key, display_name, permissions); - public static IAlgoVM generic(AlgoKey key, string display_name, AlgoType algo_type, AlgoEditingPermissions editing_permissions) => GenericOrderFactory.create_vm(key, algo_type, display_name, editing_permissions); - public static IAlgoVM composite(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new CompositeAlgoVM(key, display_name, editing_permissions); - - public static IAlgoVM create(AlgoData def_data, AlgoEditingPermissions editing_permissions = default_editing_permissions, bool is_expanded = false) { - var vm = def_data.key.is_persisted ? - new CompositeAlgoVM(def_data.key, def_data.name, editing_permissions) : - create(def_data.key, def_data.name, def_data.value.CustomCase, editing_permissions, is_expanded); - vm.load_from(def_data.value); - return vm; - } - - public static IAlgoVM create(AlgoKey key, string name, AlgoType algo_type, AlgoEditingPermissions editing_permissions = default_editing_permissions, bool is_expanded = false) { - IAlgoVM vm; - switch (algo_type) { - case AlgoType.Market: vm = new MarketOrderVM(key, name); break; - case AlgoType.Limit: vm = new LimitOrderVM(key, name); break; - case AlgoType.Stop: vm = stop(key, name); break; - case AlgoType.StopLimit: vm = stop_limit(key, name, editing_permissions); break; - case AlgoType.TimeBox: vm = time_box(key, name, editing_permissions); break; - case AlgoType.Tick: vm = tick(key, name, editing_permissions); break; - case AlgoType.Lean: vm = lean(key, name, editing_permissions); break; - case AlgoType.Join: vm = join(key, name, editing_permissions); break; - case AlgoType.Top: vm = top(key, name, editing_permissions); break; - case AlgoType.Cover: vm = cover(key, name, editing_permissions); break; - case AlgoType.Oco: return oco(key, name, editing_permissions); - case AlgoType.Pricer: return pricer(key, name, editing_permissions); - case AlgoType.Offset: vm = offset(key, name, editing_permissions); break; - case AlgoType.Trigger: vm = trigger(key, name, editing_permissions); break; - case AlgoType.GlbxIceberg: vm = glbx_iceberg(key, name, editing_permissions); break; - case AlgoType.Iceberg: vm = iceberg(key, name, editing_permissions); break; - case AlgoType.Spreader: vm = spreader(key, name, editing_permissions); break; - case AlgoType.Dynamic: vm = dynamic(key, name, name, editing_permissions); break; - case AlgoType.Splitter: vm = splitter(key, name, editing_permissions); break; - case AlgoType.Composite: vm = composite(key, name, editing_permissions); break; - case AlgoType.None: vm = new DefaultAlgoVM(); break; - default: vm = generic(key, name, algo_type, editing_permissions); break; - } - vm.is_expanded = is_expanded && vm.can_expand; - return vm; - } - - static class OrderTypeVMUtils { - static readonly IReadOnlyDictionary _algo_type_index = - AlgoDef.Descriptor.Fields.InFieldNumberOrder() - .ToDictionary(fd => fd.MessageType.ClrType); - - public static FieldDescriptor find_descriptor() => - _algo_type_index.TryGetValue(typeof(T), out FieldDescriptor fd) ? - fd : throw new NotSupportedException($"No {nameof(AlgoDef)} {nameof(FieldDescriptor)} exists for type '{typeof(T)}.'"); - } - - #region OrderTypeVM Base Classes - abstract class OrderTypeVMBase : DisposableViewModelBase, IAlgoVM, - IObserver, - IObserver, - IObserver, - IObserver where TMutable : class, IMessage, new() where TImmutable : struct, IImmutableMessage { - static readonly FieldDescriptor _descriptor = OrderTypeVMUtils.find_descriptor(); - readonly IDictionary _children_vm = new ExpandoObject(); - protected List _resources = new(); - - readonly ObservableKeyedCollection _auto_props = new ObservableKeyedCollection(t => t.name); - readonly ObservableKeyedCollection - _algo_params = new ObservableKeyedCollection(pvm => pvm.id), - _child_algo_params = new ObservableKeyedCollection(pvm => pvm.id); - readonly ObservableCollectionEx _algo_params_combo = new ObservableCollectionEx(); - readonly ObservableKeyedCollection _child_algo_selector_data = new ObservableKeyedCollection(sd => sd.prop_name); - readonly ObservableAutoWrapper _child_algo_selectors; - readonly Property _is_expanded; - readonly DeferrableAction _def_change_notifier; - string _display_name; - bool _is_initialized; - SecurityInput _security_input; - AlgoEditingPermissions _editing_permissions; - IDisposable _pending_load; - - protected OrderTypeVMBase(AlgoKey id, string display_name, AlgoEditingPermissions editing_permissions) { - this.id = id; - _display_name = display_name; - _editing_permissions = editing_permissions; - _child_algo_selectors = new ObservableAutoWrapper(_child_algo_selector_data, sd => sd.selector); - _is_expanded = backing(nameof(is_expanded)); - _def_change_notifier = new DeferrableAction(() => definition_changed?.Invoke()); - PropertyChanged += (s, e) => { - switch (e.PropertyName) { - // ignore props that don't affect the resultant AlgoDef - case nameof(is_expanded): - case nameof(editing_permissions): - return; - default: - _def_change_notifier.Invoke(); - return; - } - }; - _resources.AddRange( - ObservableAutoWrapper.dispose_on_removed(_auto_props.AsCollection(), true), - ObservableAutoWrapper.connect_item_hooks(_child_algo_selector_data, sd => { - ImmutableDisposable def_sub = null; - sd.selector.selected_algo_changed += subscribe_new_algo; - return new ImmutableDisposable( - sd.hooks ?? Disposable.empty, - ObservableAutoWrapper.try_dispose_on_removed(sd.selector.algos, true)) + - new Action(() => { - sd.selector.selected_algo_changed -= subscribe_new_algo; - Disposable.dispose(ref def_sub); - }); - - void subscribe_new_algo(IAlgoVM old_algo, IAlgoVM new_algo) { - RaisePropertyChanged(sd.prop_name); - Disposable.dispose(ref def_sub); - def_sub = new ImmutableDisposable(); - if (assert(new_algo != null, sd.prop_name, "No algo specified.")) { - def_sub += new_algo.subscribe_definition().Subscribe( - _ => _def_change_notifier.Invoke()); - if (new_algo is INotifyDataErrorInfo ndei) - def_sub += ndei.subscribe_has_errors().Subscribe( - he => assert(!he, sd.prop_name, "Algo has invalid parameters.")); - } - } - }, true)); - } - - public event Action definition_changed; - event Action _security_changed; - // core - public AlgoDefi definition => new AlgoDefi(this.created_assigned()); - public AlgoType order_type => OrderDataHelper.get_order_type(new TMutable()); - public AlgoKey id { get; } - public IReadOnlyObservableCollection algo_params => _algo_params; - // display - public string display_name { get => _display_name; protected set => Set(ref _display_name, value); } - public virtual string abbreviation => model == null ? display_name : model.factory.abbreviate_algo(new OneOf(order_type)); - public virtual AlgoDisplayGroup group => order_type.is_bts_algo_type() ? AlgoDisplayGroup.BTS : AlgoDisplayGroup.Exchange; - public OrdersModel orders_model => model; - public virtual OrderMetadata meta => OrderMetadataStore.get_metadata(order_type); - // child algos - [EditorBrowsable(EditorBrowsableState.Never)] - public dynamic children_vm { - get { - ensure_init(); - return _children_vm; - } - } - public ObservableCollection child_algo_selectors => _child_algo_selectors; - [EditorBrowsable(EditorBrowsableState.Never)] - public ObservableCollection child_algo_selectors_view { - get { - ensure_init(); - return _child_algo_selectors; - } - } - // editing permissions - public AlgoEditingPermissions editing_permissions { get => _editing_permissions; private set => Set(ref _editing_permissions, value); } - // expand - public virtual bool can_expand => !meta.NoProps; - public virtual bool is_expanded { get => _is_expanded.Value; set => _is_expanded.Value = value; } - // protected (observed props) - protected OrdersModel model { get; private set; } - protected SecurityMD? security_md => _security_input.security_md; - protected SecurityImmutable? security => _security_input.security; - - public virtual void assign_to(AlgoDef value) { - if (!(_descriptor.Accessor.GetValue(value) is TMutable algo)) - _descriptor.Accessor.SetValue(value, algo = new TMutable()); - ensure_init(); - foreach (var p in _auto_props) - p.assign(algo); - foreach (var sd in _child_algo_selector_data) { - if (sd.selector.selected_algo != null) { - if (!(sd.get_mutable_from_impl(algo) is AlgoDef child_algo)) { - child_algo = new AlgoDef(); - sd.set_order(value, child_algo); - } - sd.selector.selected_algo.assign_to(child_algo); - } - } - } - - public void ensure_init() { - if (!_is_initialized) { - _is_initialized = true; - sync_selectors(); - } - } - - public bool key_match(KeyEventArgs key) => - !string.IsNullOrEmpty(display_name) && key.Key == (Key.A + display_name[0] - 'A'); - - public void load_from(AlgoDefi value) { - if (value.CustomCase != order_type) { - value = value.actual(); - if (value.CustomCase != order_type) - return; - } - using (_def_change_notifier.defer()) { - var algom = _descriptor.Accessor.GetValue(value.CloneToMutable()) as TMutable ?? new TMutable(); - var security_src = Observable.Create(o => { - o.OnNext(security); - _security_changed += o.OnNext; - return Disposable.Create(() => _security_changed -= o.OnNext); - }); - Disposable.dispose(ref _pending_load); - _pending_load = Disposable.Create( - // load children - ObservableAutoWrapper.connect_item_hooks( - _child_algo_selector_data.AsCollection(), - sd => security_src.SubscribeEach(_ => ObservableAutoWrapper.connect_item_actions(_child_algo_selector_data.AsCollection(), selector_load_impl))), - // load regular props - ObservableAutoWrapper.connect_item_actions(_auto_props.AsCollection(), p => p.load(algom))); - } - - void selector_load_impl(AlgoSelectorData sd) { - var inner_def = sd.get_order(value); - if (inner_def.HasValue && inner_def.Value.CustomCase != AlgoType.None) { - var ival = inner_def.Value; - var vm = sd.selector.algos.GetOrAdd( - AlgoKey.from_custom_def(ival), - k => create(k, ival.display_name(), ival.CustomCase, is_expanded: is_expanded)); - vm.load_from(inner_def.Value); - sd.selector.selected_algo = vm; - } - } - } - - public void load_many(IEnumerable values) { - var value_list = values as IList ?? values.ToList(); - switch (value_list.Count) { - case 0: return; - case 1: - // **do not remove this case (as of 04/04/2019, some code below assumes that value_list has more than 1 element) - load_from(value_list[0]); - return; - } - var algos = value_list.Select(value => _descriptor.Accessor.GetValue(value.CloneToMutable()) as TMutable ?? new TMutable()).ToList(); - var security_src = Observable.Create(o => { - o.OnNext(security); - _security_changed += o.OnNext; - return Disposable.Create(() => _security_changed -= o.OnNext); - }); - Disposable.dispose(ref _pending_load); - _pending_load = Disposable.Create( - ObservableAutoWrapper.connect_item_hooks( - _child_algo_selector_data.AsCollection(), - sd => security_src.Subscribe(_ => ObservableAutoWrapper.connect_item_actions(_child_algo_selector_data.AsCollection(), selector_load_impl))), - ObservableAutoWrapper.connect_item_actions(_auto_props.AsCollection(), p => p.load_many(algos))); - - void selector_load_impl(AlgoSelectorData sd) { - // **assume that algos has more than 1 element - var child_list = new List(2); - var init = sd.get_from_impl(algos[0]); - if (!init.HasValue) { - // this method loads common values, if any child is null, there is no common value (i.e., the common value is null) - return; - } - AlgoKey key; - if (security.HasValue) { - key = AlgoKey.from_custom_def(init.Value); - child_list.Add(init.Value); - for (int i = 1; i < algos.Count; i++) { - var child = sd.get_from_impl(algos[i]); - if (!child.HasValue || key != AlgoKey.from_custom_def(child.Value)) - return; - child_list.Add(child.Value); - } - } else { - key = AlgoKey.from_custom_def(init.Value); - child_list.Add(init.Value); - for (int i = 1; i < algos.Count; i++) { - var child = sd.get_from_impl(algos[i]); - if (!child.HasValue || key != AlgoKey.from_custom_def(child.Value)) - return; - child_list.Add(child.Value); - } - } - var vm = sd.selector.algos.GetOrAdd(key, k => create(k, init.Value.display_name(), init.Value.CustomCase, is_expanded: is_expanded)); - vm.load_many(child_list); - sd.selector.selected_algo = vm; - } - } - - protected void raise_definition_changed() => - _def_change_notifier.Invoke(); - - protected virtual void validate() { } - - protected override void Dispose(bool disposing) => - _resources.DisposeAll(true); - - #region Child Algo Selectors - protected virtual IEnumerable get_selector_data() => - OrderDataHelper.get_child_algo_data(order_type); - - protected void sync_selectors() { - if (!_is_initialized) - return; - using (reset()) { - foreach (var c in get_selector_data()) { - _children_vm[c.name] = mk_selector(c.name, c.get_child_from_impl, new Func(defi => { - var mchild = c.get_child(defi.CloneToMutable()); - if (mchild != null) - return new AlgoDefi(mchild); - return null; - }), - c.assign_child); - } - } - // local methods - IDisposable reset() { - var to_remove = _child_algo_selector_data.Keys.ToList(); - _child_algo_selector_data.CollectionChanged += on_change; - void on_change(object sender, NotifyCollectionChangedEventArgs e) { - switch (e.Action) { - case NotifyCollectionChangedAction.Reset: - throw new InvalidOperationException($"{nameof(_child_algo_selector_data)} was reset; unable to continue processing incremental changes."); - default: - // catches Replace/Remove/Add ops (Add ops account for cases where the item was effectively replaced by a remove/re-add) - if (e.NewItems != null) { - foreach (AlgoSelectorData sd in e.NewItems) - to_remove.Remove(sd.prop_name); - } - break; - } - } - return Disposable.Create(() => { - _child_algo_selector_data.CollectionChanged -= on_change; - foreach (var id in to_remove) - _child_algo_selector_data.Remove(id); - }); - } - IAlgoSelector mk_selector(string prop_name, Func get_mutable_from_impl, Func get_order, Action set_order) { - string prop_display_name = DisplayNameHelper.snake_to_title_case(prop_name); - var rv = new AlgoSelector(prop_name, prop_display_name); - var param = new AlgoParamVM(prop_name, prop_display_name); - var hook = Disposable.Create( - rv.subscribe_selected_algo().Subscribe(avm => { - if (avm != param.value) - param.value = avm; - }), - param.subscribe_value().Subscribe(child_vm => rv.selected_algo = child_vm)); - _child_algo_selector_data[prop_name] = new AlgoSelectorData(prop_name, rv, get_mutable_from_impl, get_order, set_order, hook); - _child_algo_params.Add(param); - return rv; - } - } - #endregion - - #region Auto-Properties (non-child-algo params) - protected Property add_property( - string prop_name, - int target_field_number, - T init_value = default, - T non_uniform_value = default, - bool validate_on_changed = false, - AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite, - Func to_display_value = null, - Func from_display_value = null, - IObservable refresh_display_value = null) { - // - var prop = backing(prop_name, init_value); - _on_property_added(prop_name, target_field_number, prop, prop.set, non_uniform_value, validate_on_changed, permissions, to_display_value, from_display_value, refresh_display_value); - return prop; - } - - protected Property add_nullable_property( - string prop_name, - int target_field_number, - T init_value = default, - bool validate_on_changed = false, - AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite, - IObservable refresh_display_value = null) where T : struct { - var prop = backing(prop_name, init_value); - _on_nullable_property_added( - prop_name, - target_field_number, - prop, - prop.set, - validate_on_changed, - permissions, - refresh_display_value); - return prop; - } - - protected Property add_property(string prop_name, int[] target_field_number_path, T init_value = default, T non_uniform_value = default, bool validate_on_changed = false, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) { - var prop = backing(prop_name, init_value); - _on_property_added(prop_name, prop_name, DisplayNameHelper.snake_to_title_case(prop_name), target_field_number_path, prop, prop.set, non_uniform_value, validate_on_changed, permissions); - return prop; - } - - protected UserProperty add_user_property(string prop_name, int target_field_number, T init_value = default, T non_uniform_value = default, bool validate_on_changed = false) { - var prop = user_backing(prop_name, init_value); - _on_property_added(prop_name, target_field_number, prop, prop.bypass_setter, non_uniform_value, validate_on_changed, AlgoParamPermissions.ReadWrite); - return prop; - } - - protected UserProperty add_nullable_user_property(string prop_name, int target_field_number, T init_value = default, bool validate_on_changed = false) where T : struct { - var prop = user_backing(prop_name, init_value); - _on_nullable_property_added(prop_name, target_field_number, prop, prop.bypass_setter, validate_on_changed, AlgoParamPermissions.ReadWrite); - return prop; - } - - protected UserProperty add_user_property(string prop_name, int target_field_number, OneofDescriptor oneof_descriptor, T init_value = default, T non_uniform_value = default, bool validate_on_changed = false, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) where T : struct { - var prop = user_backing(prop_name, init_value); - _on_property_added(prop_name, target_field_number, oneof_descriptor, prop, prop.bypass_setter, non_uniform_value, validate_on_changed, permissions); - return prop; - } - - protected UserProperty add_user_property(string prop_name, int[] target_field_number_path, T init_value = default, T non_uniform_value = default, bool validate_on_changed = false, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) { - var prop = user_backing(prop_name, init_value); - _on_property_added(prop_name, prop_name, DisplayNameHelper.snake_to_title_case(prop_name), target_field_number_path, prop, prop.bypass_setter, non_uniform_value, validate_on_changed, permissions); - return prop; - } - - protected UserProperty add_nullable_user_property(string prop_name, int[] target_field_number_path, T init_value = default, bool validate_on_changed = false, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) where T : struct { - var prop = user_backing(prop_name, init_value); - _on_nullable_property_added(prop_name, prop_name, DisplayNameHelper.snake_to_title_case(prop_name), target_field_number_path, prop, prop.bypass_setter, validate_on_changed, permissions); - return prop; - } - - protected UserProperty add_nullable_user_property(string prop_name, string display_name, int[] target_field_number_path, T init_value = default, bool validate_on_changed = false, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) where T : struct { - var prop = user_backing(prop_name, init_value); - _on_nullable_property_added(prop_name, prop_name, display_name, target_field_number_path, prop, prop.bypass_setter, validate_on_changed, permissions); - return prop; - } - - protected UserProperty add_user_property(string prop_name, string display_name, int[] target_field_number_path, T init_value = default, T non_uniform_value = default, bool validate_on_changed = false) { - var prop = user_backing(prop_name, init_value); - _on_property_added(prop_name, prop_name, display_name, target_field_number_path, prop, prop.bypass_setter, non_uniform_value, validate_on_changed); - return prop; - } - - protected Property add_property(string prop_name, int target_field_number, TImmutableValue? init_value = null, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) where TMutableValue : class, IMessage, new() where TImmutableValue : struct, IImmutableMessage { - var prop = backing(prop_name, init_value); - var field_desc = new TMutable().Descriptor.FindFieldByNumber(target_field_number); - var param = new AlgoParamVM(prop_name, DisplayNameHelper.snake_to_title_case(prop_name), init_value) { permissions = permissions }; - _algo_params.Add(param); - _auto_props.Add(new AutoProp( - prop_name, - algo => { - if (param.has_value) - field_desc.Accessor.SetValue(algo, prop.Value.HasValue ? ((dynamic)prop.Value.Value).CloneToMutable() : null); - }, - algo => assign_to_prop_and_commit(get_from_algo(algo)), - algos => assign_to_prop_and_commit(algos.Select(get_from_algo).Distinct().SafeSingleOrDefault()), - _link_props(param, prop))); - return prop; - TImmutableValue? get_from_algo(TMutable algo) => - field_desc.Accessor.GetValue(algo) is TMutableValue mval ? ProtoHelper.immutable_factory(mval) : (TImmutableValue?)null; - void assign_to_prop_and_commit(TImmutableValue? value) { - prop.set(value); - param.mark_committed(); - } - } - - protected Property add_property(string prop_name, Func get_from_def, Action assign_to_def, TValue init_value = default, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) => - add_property(prop_name, get_from_def, assign_to_def, out AlgoParamVM param, init_value, permissions); - - protected Property add_property(string prop_name, Func get_from_def, Action assign_to_def, out AlgoParamVM param, TValue init_value = default, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) { - var prop = backing(prop_name, init_value); - var local_param = new AlgoParamVM(prop_name, prop_name, init_value) { permissions = permissions }; - param = local_param; - _link_props(local_param, prop); - _algo_params.Add(local_param); - _auto_props.Add(new AutoProp( - prop_name, - def => { - if (local_param.has_value) - assign_to_def(def, prop.Value); - }, - def => assign_to_prop_and_commit(get_from_def(def)), - algos => assign_to_prop_and_commit(algos.Select(get_from_def).Distinct().SafeSingleOrDefault()), - _link_props(local_param, prop))); - return prop; - void assign_to_prop_and_commit(TValue value) { - prop.set(value); - local_param.mark_committed(); - } - } - - protected Property add_property(string prop_name, Func get_from_def, Action assign_to_def, Action set_local, Func get_local, string local_prop = null, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) { - var init_val = get_local(); - var prop = backing(prop_name, init_val); - var param = new AlgoParamVM(prop_name, prop_name, init_val) { permissions = permissions }; - _link_props(param, prop); - _algo_params.Add(param); - _auto_props.Add(new AutoProp( - prop_name, - def => { - if (param.has_value) - assign_to_def(def, get_local()); - }, - def => set_local_and_commit(get_from_def(def)), - algos => set_local_and_commit(algos.Select(get_from_def).Distinct().SafeSingleOrDefault()), - _link_props(param, prop))); - return prop; - void set_local_and_commit(TValue value) { - set_local(value); - param.mark_committed(); - } - } - - protected void add_property( - string prop_name, - Func get_from_def, - Action assign_to_def, - Func get_local, - Action set_local, - IObservable subscribe_local, - TValue non_uniform_value = default, - AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite, - string template_key = null) { - var param = new AlgoParamVM(prop_name, DisplayNameHelper.snake_to_title_case(prop_name), get_local(), template_key) { - permissions = permissions - }; - _algo_params.Add(param); - _auto_props[prop_name] = new AutoProp(prop_name, - def => { - if (param.has_value) - assign_to_def(def, get_local()); - }, - def => set_local_and_commit(get_from_def(def)), - defs => set_local_and_commit(defs.Select(get_from_def).Distinct().SafeSingleOrDefault(non_uniform_value)), - _link_props(param, subscribe_local, set_local, EqualityComparer.Default, non_uniform_value, false)); - void set_local_and_commit(TValue value) { - set_local(value); - param.mark_committed(); - } - } - - protected void remove_property(string prop_name) { - _algo_params.Remove(prop_name); - _auto_props.Remove(prop_name); - } - - protected void link_enabled(string source_prop_name, string target_prop_name) => - link_enabled(source_prop_name, target_prop_name, _ => _); - - protected void link_enabled(string source_prop_name, string target_prop_name, Func get_enabled) { - if (_algo_params.TryGetValue(source_prop_name, out IAlgoParamVM sp) && _algo_params.TryGetValue(target_prop_name, out IAlgoParamVM target)) { - if (sp is IAlgoParamVM source) { - target.is_enabled = get_enabled(source.value); - source.value_changed += on_source_changed; - _resources.Add(Disposable.Create(() => source.value_changed -= on_source_changed)); - void on_source_changed(TSource oldval, TSource newval) => target.is_enabled = get_enabled(newval); - } - } - } - - void _on_property_added(string prop_name, int target_field_number, IProperty prop, Action assign_to_prop, T non_uniform_value, bool validate_on_changed, AlgoParamPermissions permissions, Func to_display_value = null, Func from_display_value = null, IObservable refresh_display_value = null) { - var field_desc = new TMutable().Descriptor.FindFieldByNumber(target_field_number); - var param = new AlgoParamVM(prop_name, DisplayNameHelper.snake_to_title_case(prop_name), prop.Value, EqualityComparer.Default, null, to_display_value, from_display_value) { - permissions = permissions - }; - _algo_params.Add(param); - var prop_hook = _link_props(param, prop, assign_to_prop, non_uniform_value, validate_on_changed); - if (refresh_display_value != null) { - prop_hook = Disposable.Create( - refresh_display_value.Subscribe(_ => param.refresh_display_value()), - prop_hook); - } - _auto_props.Add(new AutoProp(prop_name, mval => { - if (mval != null && param.has_value) - field_desc.Accessor.SetValue(mval, prop.Value); - }, - mval => assign_to_prop_and_commit(mval == null ? default : ConvertUtils.try_convert(field_desc.Accessor.GetValue(mval))), - mvals => assign_to_prop_and_commit(mvals.Select(v => ConvertUtils.try_convert(field_desc.Accessor.GetValue(v))).Distinct().SafeSingleOrDefault(non_uniform_value)), - prop_hook)); - void assign_to_prop_and_commit(T value) { - assign_to_prop(value); - param.mark_committed(); - } - } - - void _on_nullable_property_added( - string prop_name, - int target_field_number, - IProperty prop, - Action assign_to_prop, - bool validate_on_changed, - AlgoParamPermissions permissions, - IObservable refresh_display_value = null) where T : struct { - var field_desc = new TMutable().Descriptor.FindFieldByNumber(target_field_number); - var param = new AlgoParamVM(prop_name, DisplayNameHelper.snake_to_title_case(prop_name), prop.Value) { permissions = permissions }; - _algo_params.Add(param); - - var prop_hook = _link_props(param, prop, assign_to_prop, null, validate_on_changed); - if (refresh_display_value != null) { - prop_hook = Disposable.Create( - refresh_display_value.Subscribe(_ => param.refresh_display_value()), - prop_hook); - } - - _auto_props.Add(new AutoProp( - prop_name, - mval => { - if (mval != null && prop.Value.HasValue) - field_desc.Accessor.SetValue(mval, prop.Value.Value); - }, - mval => assign_to_prop_and_commit(mval is null ? - default : ConvertUtils.try_convert(field_desc.Accessor.GetValue(mval))), - mvals => assign_to_prop_and_commit(mvals - .Select(v => ConvertUtils.try_convert(field_desc.Accessor.GetValue(v))) - .Distinct() - .TryGetSingle(out var dv) ? dv : null), - prop_hook)); - - void assign_to_prop_and_commit(T? value) { - assign_to_prop(value); - param.mark_committed(); - } - } - - void _on_property_added(string prop_name, int target_field_number, OneofDescriptor oneof_descriptor, IProperty prop, Action assign_to_prop, T non_uniform_value, bool validate_on_changed, AlgoParamPermissions permissions) where T : struct { - var target_field_desc = ProtoHelper.Descriptor().FindFieldByNumber(target_field_number); - var param = new AlgoParamVM(prop_name, DisplayNameHelper.snake_to_title_case(prop_name), prop.Value) { permissions = permissions }; - var oneof_index = ProtoHelper.get_oneof_descriptor_index(oneof_descriptor); - _algo_params.Add(param); - _auto_props.Add(new AutoProp(prop_name, mval => { - if (mval == null || !param.has_value) - return; - if (!(target_field_desc.Accessor.GetValue(mval) is IMessage msg)) { - var type = ProtoHelper.get_field_type(target_field_desc); - target_field_desc.Accessor.SetValue(mval, msg = (IMessage)Activator.CreateInstance(type)); - } - var field_desc = ProtoHelper.get_oneof_field_descriptor(prop.Value); - var curr_field_desc = oneof_descriptor.Accessor.GetCaseFieldDescriptor(msg); - if (field_desc != curr_field_desc) { - if (field_desc == null) { - oneof_descriptor.Accessor.Clear(msg); - } else { - var t = ProtoHelper.get_field_type(field_desc); - if (t != null) - field_desc.Accessor.SetValue(msg, Activator.CreateInstance(t)); - } - } - }, mval => { - if (mval != null && target_field_desc.Accessor.GetValue(mval) is IMessage msg) - assign_to_prop_and_commit(ProtoHelper.get_oneof_case(oneof_descriptor, msg)); - }, - mvals => assign_to_prop_and_commit(mvals.Select(v => ConvertUtils.try_convert(target_field_desc.Accessor.GetValue(v))).Distinct().SafeSingleOrDefault()), - _link_props(param, prop, assign_to_prop, non_uniform_value, validate_on_changed))); - void assign_to_prop_and_commit(T value) { - assign_to_prop(value); - param.mark_committed(); - } - } - - void _on_property_added(string id, string prop_name, string display_name, int[] target_field_number_path, IProperty prop, Action assign_to_prop, T non_uniform_value = default, bool validate_on_changed = false, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) { - IMessage seed = new TMutable(); - var field_descs = Array.ConvertAll(target_field_number_path, n => { - var fd = seed.Descriptor.FindFieldByNumber(n); - var next_type = ProtoHelper.get_field_type(fd); - seed = Activator.CreateInstance(next_type) as IMessage; - return fd; - }); - var param = new AlgoParamVM(id, display_name, prop.Value) { permissions = permissions }; - _algo_params.Add(param); - _auto_props.Add(new AutoProp(prop_name, mval => { - if (mval != null && param.has_value) { - IMessage src = mval; - int i = 0; - do { - if (!(field_descs[i].Accessor.GetValue(src) is IMessage val)) { - var type = ProtoHelper.get_field_type(field_descs[i]); - val = Activator.CreateInstance(type) as IMessage; - if (val == null) return; - field_descs[i].Accessor.SetValue(src, val); - } - src = val; - } while (++i < field_descs.Length - 1); - field_descs[field_descs.Length - 1].Accessor.SetValue(src, prop.Value); - } - }, mval => assign_to_prop_and_commit(get_from_def(mval)), - mvals => assign_to_prop_and_commit(mvals.Select(get_from_def).Distinct().SafeSingleOrDefault(non_uniform_value)), - _link_props(param, prop, assign_to_prop, non_uniform_value, validate_on_changed))); - - T get_from_def(TMutable mval) { - var v = mval as IMessage; - for (int i = 0; i < field_descs.Length - 1 && v != null; i++) - v = field_descs[i].Accessor.GetValue(v) as IMessage; - return v == null ? default : ConvertUtils.try_convert(field_descs[field_descs.Length - 1].Accessor.GetValue(v)); - } - void assign_to_prop_and_commit(T value) { - assign_to_prop(value); - param.mark_committed(); - } - } - - void _on_nullable_property_added(string id, string prop_name, string display_name, int[] target_field_number_path, IProperty prop, Action assign_to_prop, bool validate_on_changed, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) where T : struct { - IMessage seed = new TMutable(); - var field_descs = Array.ConvertAll(target_field_number_path, n => { - var fd = seed.Descriptor.FindFieldByNumber(n); - var next_type = ProtoHelper.get_field_type(fd); - seed = Activator.CreateInstance(next_type) as IMessage; - return fd; - }); - var param = new AlgoParamVM(id, display_name, prop.Value) { permissions = permissions }; - _algo_params.Add(param); - _auto_props.Add(new AutoProp(prop_name, mval => { - if (mval != null && param.has_value) { - IMessage src = mval; - int i = 0; - do { - if (!(field_descs[i].Accessor.GetValue(src) is IMessage val)) { - var type = ProtoHelper.get_field_type(field_descs[i]); - val = Activator.CreateInstance(type) as IMessage; - if (val == null) return; - field_descs[i].Accessor.SetValue(src, val); - } - src = val; - } while (++i < field_descs.Length - 1); - if (prop.Value.HasValue) - field_descs[field_descs.Length - 1].Accessor.SetValue(src, prop.Value.Value); - } - }, mval => assign_to_prop_and_commit(get_from_def(mval)), - mvals => assign_to_prop_and_commit(mvals.Select(get_from_def).Distinct().TryGetSingle(out T dv) ? dv : (T?)null), - _link_props(param, prop, assign_to_prop, null, validate_on_changed))); - - T get_from_def(TMutable mval) { - var v = mval as IMessage; - for (int i = 0; i < field_descs.Length - 1 && v != null; i++) - v = field_descs[i].Accessor.GetValue(v) as IMessage; - return v == null ? default : ConvertUtils.try_convert(field_descs[field_descs.Length - 1].Accessor.GetValue(v)); - } - void assign_to_prop_and_commit(T? value) { - assign_to_prop(value); - param.mark_committed(); - } - } - - IDisposable _link_props(AlgoParamVM param, Property prop) => - _link_props(param, prop, prop.set, EqualityComparer.Default, default, false); - - IDisposable _link_props(AlgoParamVM param, IProperty prop, Action assign_to_prop, T invalid_value, bool validate_on_changed) => - _link_props(param, prop, assign_to_prop, EqualityComparer.Default, default, validate_on_changed); - - IDisposable _link_props(AlgoParamVM param, IProperty prop, Action assign_to_prop, IEqualityComparer comparer, T invalid_value = default, bool validate_on_changed = false) => - _link_props(param, prop.SubscribeValue(), assign_to_prop, comparer, invalid_value, validate_on_changed); - - IDisposable _link_props(AlgoParamVM param, IObservable prop_value_source, Action assign_to_prop, IEqualityComparer comparer, T invalid_value = default, bool validate_on_changed = false) { - param.has_value = !comparer.Equals(param.value, invalid_value); - return Disposable.Create( - prop_value_source.Subscribe(on_value_changed), - param.subscribe_value().Subscribe(assign_to_prop)); - void on_value_changed(T value) { - if (validate_on_changed) - validate(); - param.value = value; - param.has_value = !comparer.Equals(value, invalid_value); - } - } - #endregion - - protected virtual void on_model_internal() { } - protected virtual void on_security_md_internal() { } - protected virtual void on_security_internal() { } - - // model - void IObserver.OnNext(OrdersModel model) { - if (this.model != null) { - // this is not expected to happen, if it does just log and continue. - // it should be investigated at some point, bc it is a redundant update, but there is no need to sound the alarm and crash. - bts.Log.Ui.warn("Redundant OrdersModel update detected."); - return; - } - this.model = model; - RaisePropertyChanged(nameof(abbreviation)); - using (_def_change_notifier.defer()) { - on_model_internal(); - sync_selectors(); - } - } - void IObserver.OnError(Exception error) { } - void IObserver.OnCompleted() { } - // security md - void IObserver.OnNext(SecurityMD? security_md) { - using (_def_change_notifier.defer()) - using (_update_sec_input()) - _security_input = _security_input.with_security_md(security_md); - } - void IObserver.OnError(Exception error) { } - void IObserver.OnCompleted() { } - // security - void IObserver.OnNext(SecurityImmutable? security) { - using (_def_change_notifier.defer()) - using (_update_sec_input()) - _security_input = _security_input.with_security(security); - } - - void IObserver.OnError(Exception error) { } - void IObserver.OnCompleted() { } - // editing permissions - void IObserver.OnNext(AlgoEditingPermissions editing_permissions) => this.editing_permissions = editing_permissions; - void IObserver.OnError(Exception error) { } - void IObserver.OnCompleted() { } - - IDisposable _update_sec_input() { - var old_sec = security; - var old_sec_md = security_md; - return Disposable.Create(() => { - if (security != old_sec) { - on_security_internal(); - _security_changed?.Invoke(security); - } - if (security_md != old_sec_md) - on_security_md_internal(); - }); - } - - class AutoProp : IDisposable { - public readonly string name; - public readonly Action assign, load; - public readonly Action> assign_many, load_many; - IDisposable _dispose; - - public AutoProp(string name, Action assign, Action load, Action> load_many, IDisposable dispose) - : this(name, assign, load, algos => algos.ForEach(assign), load_many, dispose) { } - - public AutoProp(string name, Action assign, Action load, Action> assign_many, Action> load_many, IDisposable dispose) { - this.name = name; - this.assign = assign; - this.load = load; - this.load_many = load_many; - this.assign_many = assign_many; - _dispose = dispose; - } - - public void Dispose() => - Disposable.dispose(ref _dispose); - } - } - - // security input may come in 2 forms: - // 1) SecurityImmutable? - // 2) SecurityMD? - // This structure resolves conflicts that may arise from the different inputs - struct SecurityInput { - readonly SecurityMD? _raw_security_md; - readonly SecurityImmutable? _raw_security; - - public readonly SecurityMD? security_md; - public readonly SecurityImmutable? security; - - SecurityInput(SecurityImmutable? raw_security, SecurityMD? raw_security_md, SecurityImmutable? security, SecurityMD? security_md) { - _raw_security = raw_security; - _raw_security_md = raw_security_md; - this.security_md = security_md; - this.security = security; - } - - public SecurityInput with_security(SecurityImmutable? security) => - new SecurityInput( - security, - _raw_security_md, - security, - security.HasValue && _raw_security_md.HasValue && _raw_security_md.Value.security.Id != security.Value.Id ? - null : _raw_security_md); - - public SecurityInput with_security_md(SecurityMD? security_md) => - new SecurityInput( - _raw_security, - security_md, - security_md?.security ?? _raw_security, - security_md); - } - - struct AlgoSelectorData : IDisposable { - public readonly string prop_name; - public readonly AlgoSelector selector; - public readonly Func get_order; - public readonly Func get_mutable_from_impl; - public readonly Action set_order; - public readonly IDisposable hooks; - - public AlgoSelectorData(string id, AlgoSelector selector, Func get_mutable_from_impl, Func get_order, Action set_order, IDisposable hooks = null) { - this.prop_name = id; - this.selector = selector; - this.get_mutable_from_impl = get_mutable_from_impl; - this.get_order = get_order; - this.set_order = set_order; - this.hooks = hooks; - } - public AlgoDefi? get_from_impl(IMessage msg) { - var mchild = get_mutable_from_impl(msg); - return mchild != null ? new AlgoDefi(mchild) : (AlgoDefi?)null; - } - public void Dispose() => - hooks.Dispose(); - } - - class AlgoSelector : IAlgoSelector, INotifyPropertyChanged { - IAlgoVM _algo; - AlgoParamPermissions _permissions = AlgoParamPermissions.ReadWrite; - IReadOnlyDictionary _pending_data; - AlgoKey? _pending_default; - IDisposable _loaded_data_hook; - - public AlgoSelector(string id, string display_name) { - this.id = id; - this.display_name = display_name; - algos_view = ObservableAutoWrapper.create_sorted_wrapper(algos, AlgoCollectionHelper.algo_vm_comparer); - selected_algo_changed += (o, n) => _raise_property_changed(nameof(selected_algo)); - } - - public void load_algo_data(IReadOnlyDictionary algo_data, AlgoKey? default_algo) { - _pending_data = algo_data; - _pending_default = default_algo; - _sync_formats(); - } - - public event PropertyChange selected_algo_changed; - public event PropertyChange permissions_changed; - public event PropertyChangedEventHandler PropertyChanged; - - public string id { get; } - public string display_name { get; } - public bool is_enabled { get; set; } = true; - - public bool initialized { get; private set; } - - public ObservableKeyedCollection algos { get; } = - new ObservableKeyedCollection(vm => vm.id); - - public IReadOnlyObservableCollection algos_view { get; } - - public AlgoParamPermissions permissions { - get => _permissions; - set { - if (_set(ref _permissions, value, out var oldval)) - permissions_changed?.Invoke(oldval, value); - } - } - - public IAlgoVM selected_algo { - get { - if (!initialized) { - initialized = true; - _sync_formats(); - if (_algo != null && _algo.can_expand) - _algo.is_expanded = true; - } - return _algo; - } - set { - // this is a hack around a wpf snafu: in the AlgoStudio, the ComboBox bound to order_types/value, does not have a stable DataContext. - // Its DataContext is bound to the selected-definition/template. When this changes, the ItemsSource changes, and the [ComboBox]view always sets its SelectedItem to null. - // We must do something to prevent this, it isn't a mere annoyance that forces the user to re-select the ordertype after they select another template. - // In AlgoStudio, the ComboBox is only enabled for definining a new algo-structure, for templates it is disabled, so the user can't even open the dropdown! - // There is probably a better solution/workaround for this problem, but in the meantime this does the trick. - if (value == null && _algo != null && algos.Contains(_algo)) - return; - _select_algo(value); - } - } - - #region IAlgoParamVM - IAlgoVM IAlgoParamVM.value { get => selected_algo; set => selected_algo = value; } - IAlgoVM IAlgoParamVM.display_value { get => selected_algo; set => selected_algo = value; } - event PropertyChange IAlgoParamVM.value_changed { add => selected_algo_changed += value; remove => selected_algo_changed -= value; } - object IAlgoParamVM.value { get => selected_algo; set => selected_algo = (IAlgoVM)value; } - object IAlgoParamVM.display_value { get => selected_algo; set => selected_algo = (IAlgoVM)value; } - bool IAlgoParamVM.has_value => _algo != null; - // changing child algos is not allowed, so an algo selector is never dirty - bool IAlgoParamVM.is_dirty => false; - event Action IAlgoParamVM.is_dirty_changed { add { } remove { } } - - void IAlgoParamVM.revert() { } - void IAlgoParamVM.mark_committed() { } - #endregion - - public IObservable subscribe_selected_algo() { - return Observable.Create(o => { - if (initialized && _algo != null) { - o.OnNext(_algo); - } - selected_algo_changed += on_property_change; - return Disposable.Create(() => selected_algo_changed -= on_property_change); - void on_property_change(IAlgoVM oldval, IAlgoVM newval) => - o.OnNext(newval); - }); - } - - void _select_algo(IAlgoVM new_algo) { - if (new_algo != _algo) { - var old_algo = _algo; - _algo = new_algo; - selected_algo_changed?.Invoke(old_algo, new_algo); - } - } - - void _sync_formats() { - if (initialized && _pending_data != null) { - Disposable.dispose(ref _loaded_data_hook); - var data = _pending_data; - algos.SyncWithDictionary(data, d => create(d, is_expanded: true)); - _loaded_data_hook = ObservableAutoWrapper.connect_item_hooks(algos, vm => - ObservableAutoWrapper.connect_item_actions(vm.child_algo_selectors, s => s.load_algo_data(data, null))); - if (_algo == null || !algos.ContainsKey(_algo.id)) { - if (_pending_default.HasValue && algos.TryGetValue(_pending_default.Value, out IAlgoVM match)) - selected_algo = match; - } - } - } - - bool _set(ref T backing, T new_value, [CallerMemberName] string prop = "") => - _set(ref backing, new_value, out T _, EqualityComparer.Default, prop); - - bool _set(ref T backing, T new_value, out T old_value, [CallerMemberName] string prop = "") => - _set(ref backing, new_value, out old_value, EqualityComparer.Default, prop); - - bool _set(ref T backing, T new_value, out T old_value, IEqualityComparer comparer, [CallerMemberName] string prop = "") { - if (!comparer.Equals(new_value, backing)) { - old_value = backing; - backing = new_value; - return true; - } - old_value = backing; - return false; - } - - void _raise_property_changed([CallerMemberName] string prop = "") => - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop)); - - void IObserver<(IReadOnlyDictionary algo_data, AlgoKey? default_algo)>.OnNext((IReadOnlyDictionary algo_data, AlgoKey? default_algo) value) => - load_algo_data(value.algo_data, value.default_algo); - void IObserver<(IReadOnlyDictionary algo_data, AlgoKey? default_algo)>.OnCompleted() { } - void IObserver<(IReadOnlyDictionary algo_data, AlgoKey? default_algo)>.OnError(Exception error) { } - } - #endregion - } -} +using bts; +using bts.api; +using bts.collections; +using bts.spark; +using bts.utils; + +using Google.Protobuf; +using Google.Protobuf.Reflection; + +using mbts.collections; +using mbts.spark.utilities; +using mbts.ui.shell; +using mbts.ui.utilities; +using mbts.ui.utility; +using mbts.utils; + +using Spark.Api.Orders; +using Spark.Core; +using Spark.Core.Collections; +using Spark.Core.Disposables; +using Spark.Core.Reactive; + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Dynamic; +using System.Linq; +using System.Reactive; +using System.Reactive.Linq; +using System.Runtime.CompilerServices; +using System.Windows.Input; + +using AlgoDef = bts.api.orderman.CustomOrderDefinition; +using AlgoDefi = bts.api.orderman.CustomOrderDefinitionImmutable; +using AlgoType = bts.api.orderman.CustomOrderDefinition.CustomOneofCase; + +namespace mbts.spark { + enum AlgoEditingPermissions { + None = 0, + AllowEditValues = 1, + AllowEditStructure = 1 << 1, + AllowSaveValues = 1 << 2, + AllowSaveStructure = 1 << 3, + } + + static partial class OrderTypeVMFactory { + public const AlgoEditingPermissions default_editing_permissions = AlgoEditingPermissions.AllowEditValues | AlgoEditingPermissions.AllowEditStructure; + + public static IAlgoVM market() => new MarketOrderVM(); + public static IAlgoVM limit() => new LimitOrderVM(); + public static IAlgoVM stop(AlgoKey key, string display_name) => new StopOrderVM(key, display_name, default_editing_permissions); + public static IAlgoVM stop_limit(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new StopLimitOrderVM(key, display_name, editing_permissions); + public static IAlgoVM time_box(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new TimeBoxOrderVM(key, display_name, editing_permissions); + public static IAlgoVM tick(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new TickOrderVM(key, display_name, editing_permissions); + public static IAlgoVM lean(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new LeanOrderVM(key, display_name, editing_permissions); + public static IAlgoVM join(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new JoinOrderVM(key, display_name, editing_permissions); + public static IAlgoVM top(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new TopOrderVM(key, display_name, editing_permissions); + public static IAlgoVM cover(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new CoverOrderVM(key, display_name, editing_permissions); + public static IAlgoVM oco(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new OCOOrderVM(key, display_name, editing_permissions); + public static IAlgoVM pricer(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new PricerOrderVM(key, display_name, editing_permissions); + public static IAlgoVM offset(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new OffsetOrderVM(key, display_name, editing_permissions); + public static IAlgoVM trigger(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new TriggerOrderVM(key, display_name, editing_permissions); + public static IAlgoVM glbx_iceberg(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new GLBXIcebergOrderVM(key, display_name, editing_permissions); + public static IAlgoVM iceberg(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new IcebergOrderVM(key, display_name, editing_permissions); + public static IAlgoVM spreader(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new SpreaderOrderVM(key, display_name, editing_permissions); + public static IAlgoVM dynamic(AlgoKey key, string display_name, string dynamic_type, AlgoEditingPermissions editing_permissions) => new DynamicOrderVM(key, dynamic_type, display_name, editing_permissions); + public static IAlgoVM splitter(AlgoKey key, string display_name, AlgoEditingPermissions permissions) => new SplitterAlgoVM(key, display_name, permissions); + public static IAlgoVM generic(AlgoKey key, string display_name, AlgoType algo_type, AlgoEditingPermissions editing_permissions) => GenericOrderFactory.create_vm(key, algo_type, display_name, editing_permissions); + public static IAlgoVM composite(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new CompositeAlgoVM(key, display_name, editing_permissions); + + public static IAlgoVM create(AlgoData def_data, AlgoEditingPermissions editing_permissions = default_editing_permissions, bool is_expanded = false) { + var vm = def_data.key.is_persisted ? + new CompositeAlgoVM(def_data.key, def_data.name, editing_permissions) : + create(def_data.key, def_data.name, def_data.value.CustomCase, editing_permissions, is_expanded); + vm.load_from(def_data.value); + return vm; + } + + public static IAlgoVM create(AlgoKey key, string name, AlgoType algo_type, AlgoEditingPermissions editing_permissions = default_editing_permissions, bool is_expanded = false) { + IAlgoVM vm; + switch (algo_type) { + case AlgoType.Market: vm = new MarketOrderVM(key, name); break; + case AlgoType.Limit: vm = new LimitOrderVM(key, name); break; + case AlgoType.Stop: vm = stop(key, name); break; + case AlgoType.StopLimit: vm = stop_limit(key, name, editing_permissions); break; + case AlgoType.TimeBox: vm = time_box(key, name, editing_permissions); break; + case AlgoType.Tick: vm = tick(key, name, editing_permissions); break; + case AlgoType.Lean: vm = lean(key, name, editing_permissions); break; + case AlgoType.Join: vm = join(key, name, editing_permissions); break; + case AlgoType.Top: vm = top(key, name, editing_permissions); break; + case AlgoType.Cover: vm = cover(key, name, editing_permissions); break; + case AlgoType.Oco: return oco(key, name, editing_permissions); + case AlgoType.Pricer: return pricer(key, name, editing_permissions); + case AlgoType.Offset: vm = offset(key, name, editing_permissions); break; + case AlgoType.Trigger: vm = trigger(key, name, editing_permissions); break; + case AlgoType.GlbxIceberg: vm = glbx_iceberg(key, name, editing_permissions); break; + case AlgoType.Iceberg: vm = iceberg(key, name, editing_permissions); break; + case AlgoType.Spreader: vm = spreader(key, name, editing_permissions); break; + case AlgoType.Dynamic: vm = dynamic(key, name, name, editing_permissions); break; + case AlgoType.Splitter: vm = splitter(key, name, editing_permissions); break; + case AlgoType.Composite: vm = composite(key, name, editing_permissions); break; + case AlgoType.None: vm = new DefaultAlgoVM(); break; + default: vm = generic(key, name, algo_type, editing_permissions); break; + } + vm.is_expanded = is_expanded && vm.can_expand; + return vm; + } + + static class OrderTypeVMUtils { + static readonly IReadOnlyDictionary _algo_type_index = + AlgoDef.Descriptor.Fields.InFieldNumberOrder() + .ToDictionary(fd => fd.MessageType.ClrType); + + public static FieldDescriptor find_descriptor() => + _algo_type_index.TryGetValue(typeof(T), out FieldDescriptor fd) ? + fd : throw new NotSupportedException($"No {nameof(AlgoDef)} {nameof(FieldDescriptor)} exists for type '{typeof(T)}.'"); + } + + #region OrderTypeVM Base Classes + abstract class OrderTypeVMBase : DisposableViewModelBase, IAlgoVM, + IObserver, + IObserver, + IObserver, + IObserver where TMutable : class, IMessage, new() where TImmutable : struct, IImmutableMessage { + static readonly FieldDescriptor _descriptor = OrderTypeVMUtils.find_descriptor(); + readonly IDictionary _children_vm = new ExpandoObject(); + protected List _resources = new(); + + readonly ObservableKeyedCollection _auto_props = new ObservableKeyedCollection(t => t.name); + readonly ObservableKeyedCollection + _algo_params = new ObservableKeyedCollection(pvm => pvm.id), + _child_algo_params = new ObservableKeyedCollection(pvm => pvm.id); + readonly ObservableCollectionEx _algo_params_combo = new ObservableCollectionEx(); + readonly ObservableKeyedCollection _child_algo_selector_data = new ObservableKeyedCollection(sd => sd.prop_name); + readonly ObservableAutoWrapper _child_algo_selectors; + readonly Property _is_expanded; + readonly DeferrableAction _def_change_notifier; + string _display_name; + bool _is_initialized; + SecurityInput _security_input; + AlgoEditingPermissions _editing_permissions; + IDisposable _pending_load; + + protected OrderTypeVMBase(AlgoKey id, string display_name, AlgoEditingPermissions editing_permissions) { + this.id = id; + _display_name = display_name; + _editing_permissions = editing_permissions; + _child_algo_selectors = new ObservableAutoWrapper(_child_algo_selector_data, sd => sd.selector); + _is_expanded = backing(nameof(is_expanded)); + _def_change_notifier = new DeferrableAction(() => definition_changed?.Invoke()); + PropertyChanged += (s, e) => { + switch (e.PropertyName) { + // ignore props that don't affect the resultant AlgoDef + case nameof(is_expanded): + case nameof(editing_permissions): + return; + default: + _def_change_notifier.Invoke(); + return; + } + }; + _resources.AddRange( + ObservableAutoWrapper.dispose_on_removed(_auto_props.AsCollection(), true), + ObservableAutoWrapper.connect_item_hooks(_child_algo_selector_data, sd => { + ImmutableDisposable def_sub = null; + sd.selector.selected_algo_changed += subscribe_new_algo; + return new ImmutableDisposable( + sd.hooks ?? Disposable.empty, + ObservableAutoWrapper.try_dispose_on_removed(sd.selector.algos, true)) + + new Action(() => { + sd.selector.selected_algo_changed -= subscribe_new_algo; + Disposable.dispose(ref def_sub); + }); + + void subscribe_new_algo(IAlgoVM old_algo, IAlgoVM new_algo) { + RaisePropertyChanged(sd.prop_name); + Disposable.dispose(ref def_sub); + def_sub = new ImmutableDisposable(); + if (assert(new_algo != null, sd.prop_name, "No algo specified.")) { + def_sub += new_algo.subscribe_definition().Subscribe( + _ => _def_change_notifier.Invoke()); + if (new_algo is INotifyDataErrorInfo ndei) + def_sub += ndei.subscribe_has_errors().Subscribe( + he => assert(!he, sd.prop_name, "Algo has invalid parameters.")); + } + } + }, true)); + } + + public event Action definition_changed; + event Action _security_changed; + // core + public AlgoDefi definition => new AlgoDefi(this.created_assigned()); + public AlgoType order_type => OrderDataHelper.get_order_type(new TMutable()); + public AlgoKey id { get; } + public IReadOnlyObservableCollection algo_params => _algo_params; + // display + public string display_name { get => _display_name; protected set => Set(ref _display_name, value); } + public virtual string abbreviation => model == null ? display_name : model.factory.abbreviate_algo(new OneOf(order_type)); + public virtual AlgoDisplayGroup group => order_type.is_bts_algo_type() ? AlgoDisplayGroup.BTS : AlgoDisplayGroup.Exchange; + public OrdersModel orders_model => model; + public virtual OrderMetadata meta => OrderMetadataStore.get_metadata(order_type); + // child algos + [EditorBrowsable(EditorBrowsableState.Never)] + public dynamic children_vm { + get { + ensure_init(); + return _children_vm; + } + } + public ObservableCollection child_algo_selectors => _child_algo_selectors; + [EditorBrowsable(EditorBrowsableState.Never)] + public ObservableCollection child_algo_selectors_view { + get { + ensure_init(); + return _child_algo_selectors; + } + } + // editing permissions + public AlgoEditingPermissions editing_permissions { get => _editing_permissions; private set => Set(ref _editing_permissions, value); } + // expand + public virtual bool can_expand => !meta.NoProps; + public virtual bool is_expanded { get => _is_expanded.Value; set => _is_expanded.Value = value; } + // protected (observed props) + protected OrdersModel model { get; private set; } + protected SecurityMD? security_md => _security_input.security_md; + protected SecurityImmutable? security => _security_input.security; + + public virtual void assign_to(AlgoDef value) { + if (!(_descriptor.Accessor.GetValue(value) is TMutable algo)) + _descriptor.Accessor.SetValue(value, algo = new TMutable()); + ensure_init(); + foreach (var p in _auto_props) + p.assign(algo); + foreach (var sd in _child_algo_selector_data) { + if (sd.selector.selected_algo != null) { + if (!(sd.get_mutable_from_impl(algo) is AlgoDef child_algo)) { + child_algo = new AlgoDef(); + sd.set_order(value, child_algo); + } + sd.selector.selected_algo.assign_to(child_algo); + } + } + } + + public void ensure_init() { + if (!_is_initialized) { + _is_initialized = true; + sync_selectors(); + } + } + + public bool key_match(KeyEventArgs key) => + !string.IsNullOrEmpty(display_name) && key.Key == (Key.A + display_name[0] - 'A'); + + public void load_from(AlgoDefi value) { + if (value.CustomCase != order_type) { + value = value.actual(); + if (value.CustomCase != order_type) + return; + } + using (_def_change_notifier.defer()) { + var algom = _descriptor.Accessor.GetValue(value.CloneToMutable()) as TMutable ?? new TMutable(); + var security_src = Observable.Create(o => { + o.OnNext(security); + _security_changed += o.OnNext; + return Disposable.Create(() => _security_changed -= o.OnNext); + }); + Disposable.dispose(ref _pending_load); + _pending_load = Disposable.Create( + // load children + ObservableAutoWrapper.connect_item_hooks( + _child_algo_selector_data.AsCollection(), + sd => security_src.SubscribeEach(_ => ObservableAutoWrapper.connect_item_actions(_child_algo_selector_data.AsCollection(), selector_load_impl))), + // load regular props + ObservableAutoWrapper.connect_item_actions(_auto_props.AsCollection(), p => p.load(algom))); + } + + void selector_load_impl(AlgoSelectorData sd) { + var inner_def = sd.get_order(value); + if (inner_def.HasValue && inner_def.Value.CustomCase != AlgoType.None) { + var ival = inner_def.Value; + var vm = sd.selector.algos.GetOrAdd( + AlgoKey.from_custom_def(ival), + k => create(k, ival.display_name(), ival.CustomCase, is_expanded: is_expanded)); + vm.load_from(inner_def.Value); + sd.selector.selected_algo = vm; + } + } + } + + public void load_many(IEnumerable values) { + var value_list = values as IList ?? values.ToList(); + switch (value_list.Count) { + case 0: return; + case 1: + // **do not remove this case (as of 04/04/2019, some code below assumes that value_list has more than 1 element) + load_from(value_list[0]); + return; + } + var algos = value_list.Select(value => _descriptor.Accessor.GetValue(value.CloneToMutable()) as TMutable ?? new TMutable()).ToList(); + var security_src = Observable.Create(o => { + o.OnNext(security); + _security_changed += o.OnNext; + return Disposable.Create(() => _security_changed -= o.OnNext); + }); + Disposable.dispose(ref _pending_load); + _pending_load = Disposable.Create( + ObservableAutoWrapper.connect_item_hooks( + _child_algo_selector_data.AsCollection(), + sd => security_src.Subscribe(_ => ObservableAutoWrapper.connect_item_actions(_child_algo_selector_data.AsCollection(), selector_load_impl))), + ObservableAutoWrapper.connect_item_actions(_auto_props.AsCollection(), p => p.load_many(algos))); + + void selector_load_impl(AlgoSelectorData sd) { + // **assume that algos has more than 1 element + var child_list = new List(2); + var init = sd.get_from_impl(algos[0]); + if (!init.HasValue) { + // this method loads common values, if any child is null, there is no common value (i.e., the common value is null) + return; + } + AlgoKey key; + if (security.HasValue) { + key = AlgoKey.from_custom_def(init.Value); + child_list.Add(init.Value); + for (int i = 1; i < algos.Count; i++) { + var child = sd.get_from_impl(algos[i]); + if (!child.HasValue || key != AlgoKey.from_custom_def(child.Value)) + return; + child_list.Add(child.Value); + } + } else { + key = AlgoKey.from_custom_def(init.Value); + child_list.Add(init.Value); + for (int i = 1; i < algos.Count; i++) { + var child = sd.get_from_impl(algos[i]); + if (!child.HasValue || key != AlgoKey.from_custom_def(child.Value)) + return; + child_list.Add(child.Value); + } + } + var vm = sd.selector.algos.GetOrAdd(key, k => create(k, init.Value.display_name(), init.Value.CustomCase, is_expanded: is_expanded)); + vm.load_many(child_list); + sd.selector.selected_algo = vm; + } + } + + protected void raise_definition_changed() => + _def_change_notifier.Invoke(); + + protected virtual void validate() { } + + protected override void Dispose(bool disposing) => + _resources.DisposeAll(true); + + #region Child Algo Selectors + protected virtual IEnumerable get_selector_data() => + OrderDataHelper.get_child_algo_data(order_type); + + protected void sync_selectors() { + if (!_is_initialized) + return; + using (reset()) { + foreach (var c in get_selector_data()) { + _children_vm[c.name] = mk_selector(c.name, c.get_child_from_impl, new Func(defi => { + var mchild = c.get_child(defi.CloneToMutable()); + if (mchild != null) + return new AlgoDefi(mchild); + return null; + }), + c.assign_child); + } + } + // local methods + IDisposable reset() { + var to_remove = _child_algo_selector_data.Keys.ToList(); + _child_algo_selector_data.CollectionChanged += on_change; + void on_change(object sender, NotifyCollectionChangedEventArgs e) { + switch (e.Action) { + case NotifyCollectionChangedAction.Reset: + throw new InvalidOperationException($"{nameof(_child_algo_selector_data)} was reset; unable to continue processing incremental changes."); + default: + // catches Replace/Remove/Add ops (Add ops account for cases where the item was effectively replaced by a remove/re-add) + if (e.NewItems != null) { + foreach (AlgoSelectorData sd in e.NewItems) + to_remove.Remove(sd.prop_name); + } + break; + } + } + return Disposable.Create(() => { + _child_algo_selector_data.CollectionChanged -= on_change; + foreach (var id in to_remove) + _child_algo_selector_data.Remove(id); + }); + } + IAlgoSelector mk_selector(string prop_name, Func get_mutable_from_impl, Func get_order, Action set_order) { + string prop_display_name = DisplayNameHelper.snake_to_title_case(prop_name); + var rv = new AlgoSelector(prop_name, prop_display_name); + var param = new AlgoParamVM(prop_name, prop_display_name); + var hook = Disposable.Create( + rv.subscribe_selected_algo().Subscribe(avm => { + if (avm != param.value) + param.value = avm; + }), + param.subscribe_value().Subscribe(child_vm => rv.selected_algo = child_vm)); + _child_algo_selector_data[prop_name] = new AlgoSelectorData(prop_name, rv, get_mutable_from_impl, get_order, set_order, hook); + _child_algo_params.Add(param); + return rv; + } + } + #endregion + + #region Auto-Properties (non-child-algo params) + protected Property add_property( + string prop_name, + int target_field_number, + T init_value = default, + T non_uniform_value = default, + bool validate_on_changed = false, + AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite, + Func to_display_value = null, + Func from_display_value = null, + IObservable refresh_display_value = null) { + // + var prop = backing(prop_name, init_value); + _on_property_added(prop_name, target_field_number, prop, prop.set, non_uniform_value, validate_on_changed, permissions, to_display_value, from_display_value, refresh_display_value); + return prop; + } + + protected Property add_nullable_property( + string prop_name, + int target_field_number, + T init_value = default, + bool validate_on_changed = false, + AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite, + IObservable refresh_display_value = null) where T : struct { + var prop = backing(prop_name, init_value); + _on_nullable_property_added( + prop_name, + target_field_number, + prop, + prop.set, + validate_on_changed, + permissions, + refresh_display_value); + return prop; + } + + protected Property add_property(string prop_name, int[] target_field_number_path, T init_value = default, T non_uniform_value = default, bool validate_on_changed = false, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) { + var prop = backing(prop_name, init_value); + _on_property_added(prop_name, prop_name, DisplayNameHelper.snake_to_title_case(prop_name), target_field_number_path, prop, prop.set, non_uniform_value, validate_on_changed, permissions); + return prop; + } + + protected UserProperty add_user_property(string prop_name, int target_field_number, T init_value = default, T non_uniform_value = default, bool validate_on_changed = false) { + var prop = user_backing(prop_name, init_value); + _on_property_added(prop_name, target_field_number, prop, prop.bypass_setter, non_uniform_value, validate_on_changed, AlgoParamPermissions.ReadWrite); + return prop; + } + + protected UserProperty add_nullable_user_property(string prop_name, int target_field_number, T init_value = default, bool validate_on_changed = false) where T : struct { + var prop = user_backing(prop_name, init_value); + _on_nullable_property_added(prop_name, target_field_number, prop, prop.bypass_setter, validate_on_changed, AlgoParamPermissions.ReadWrite); + return prop; + } + + protected UserProperty add_user_property(string prop_name, int target_field_number, OneofDescriptor oneof_descriptor, T init_value = default, T non_uniform_value = default, bool validate_on_changed = false, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) where T : struct { + var prop = user_backing(prop_name, init_value); + _on_property_added(prop_name, target_field_number, oneof_descriptor, prop, prop.bypass_setter, non_uniform_value, validate_on_changed, permissions); + return prop; + } + + protected UserProperty add_user_property(string prop_name, int[] target_field_number_path, T init_value = default, T non_uniform_value = default, bool validate_on_changed = false, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) { + var prop = user_backing(prop_name, init_value); + _on_property_added(prop_name, prop_name, DisplayNameHelper.snake_to_title_case(prop_name), target_field_number_path, prop, prop.bypass_setter, non_uniform_value, validate_on_changed, permissions); + return prop; + } + + protected UserProperty add_nullable_user_property(string prop_name, int[] target_field_number_path, T init_value = default, bool validate_on_changed = false, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) where T : struct { + var prop = user_backing(prop_name, init_value); + _on_nullable_property_added(prop_name, prop_name, DisplayNameHelper.snake_to_title_case(prop_name), target_field_number_path, prop, prop.bypass_setter, validate_on_changed, permissions); + return prop; + } + + protected UserProperty add_nullable_user_property(string prop_name, string display_name, int[] target_field_number_path, T init_value = default, bool validate_on_changed = false, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) where T : struct { + var prop = user_backing(prop_name, init_value); + _on_nullable_property_added(prop_name, prop_name, display_name, target_field_number_path, prop, prop.bypass_setter, validate_on_changed, permissions); + return prop; + } + + protected UserProperty add_user_property(string prop_name, string display_name, int[] target_field_number_path, T init_value = default, T non_uniform_value = default, bool validate_on_changed = false) { + var prop = user_backing(prop_name, init_value); + _on_property_added(prop_name, prop_name, display_name, target_field_number_path, prop, prop.bypass_setter, non_uniform_value, validate_on_changed); + return prop; + } + + protected Property add_property(string prop_name, int target_field_number, TImmutableValue? init_value = null, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) where TMutableValue : class, IMessage, new() where TImmutableValue : struct, IImmutableMessage { + var prop = backing(prop_name, init_value); + var field_desc = new TMutable().Descriptor.FindFieldByNumber(target_field_number); + var param = new AlgoParamVM(prop_name, DisplayNameHelper.snake_to_title_case(prop_name), init_value) { permissions = permissions }; + _algo_params.Add(param); + _auto_props.Add(new AutoProp( + prop_name, + algo => { + if (param.has_value) + field_desc.Accessor.SetValue(algo, prop.Value.HasValue ? ((dynamic)prop.Value.Value).CloneToMutable() : null); + }, + algo => assign_to_prop_and_commit(get_from_algo(algo)), + algos => assign_to_prop_and_commit(algos.Select(get_from_algo).Distinct().SafeSingleOrDefault()), + _link_props(param, prop))); + return prop; + TImmutableValue? get_from_algo(TMutable algo) => + field_desc.Accessor.GetValue(algo) is TMutableValue mval ? ProtoHelper.immutable_factory(mval) : (TImmutableValue?)null; + void assign_to_prop_and_commit(TImmutableValue? value) { + prop.set(value); + param.mark_committed(); + } + } + + protected Property add_property(string prop_name, Func get_from_def, Action assign_to_def, TValue init_value = default, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) => + add_property(prop_name, get_from_def, assign_to_def, out AlgoParamVM param, init_value, permissions); + + protected Property add_property(string prop_name, Func get_from_def, Action assign_to_def, out AlgoParamVM param, TValue init_value = default, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) { + var prop = backing(prop_name, init_value); + var local_param = new AlgoParamVM(prop_name, prop_name, init_value) { permissions = permissions }; + param = local_param; + _link_props(local_param, prop); + _algo_params.Add(local_param); + _auto_props.Add(new AutoProp( + prop_name, + def => { + if (local_param.has_value) + assign_to_def(def, prop.Value); + }, + def => assign_to_prop_and_commit(get_from_def(def)), + algos => assign_to_prop_and_commit(algos.Select(get_from_def).Distinct().SafeSingleOrDefault()), + _link_props(local_param, prop))); + return prop; + void assign_to_prop_and_commit(TValue value) { + prop.set(value); + local_param.mark_committed(); + } + } + + protected Property add_property(string prop_name, Func get_from_def, Action assign_to_def, Action set_local, Func get_local, string local_prop = null, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) { + var init_val = get_local(); + var prop = backing(prop_name, init_val); + var param = new AlgoParamVM(prop_name, prop_name, init_val) { permissions = permissions }; + _link_props(param, prop); + _algo_params.Add(param); + _auto_props.Add(new AutoProp( + prop_name, + def => { + if (param.has_value) + assign_to_def(def, get_local()); + }, + def => set_local_and_commit(get_from_def(def)), + algos => set_local_and_commit(algos.Select(get_from_def).Distinct().SafeSingleOrDefault()), + _link_props(param, prop))); + return prop; + void set_local_and_commit(TValue value) { + set_local(value); + param.mark_committed(); + } + } + + protected void add_property( + string prop_name, + Func get_from_def, + Action assign_to_def, + Func get_local, + Action set_local, + IObservable subscribe_local, + TValue non_uniform_value = default, + AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite, + string template_key = null) { + var param = new AlgoParamVM(prop_name, DisplayNameHelper.snake_to_title_case(prop_name), get_local(), template_key) { + permissions = permissions + }; + _algo_params.Add(param); + _auto_props[prop_name] = new AutoProp(prop_name, + def => { + if (param.has_value) + assign_to_def(def, get_local()); + }, + def => set_local_and_commit(get_from_def(def)), + defs => set_local_and_commit(defs.Select(get_from_def).Distinct().SafeSingleOrDefault(non_uniform_value)), + _link_props(param, subscribe_local, set_local, EqualityComparer.Default, non_uniform_value, false)); + void set_local_and_commit(TValue value) { + set_local(value); + param.mark_committed(); + } + } + + protected void remove_property(string prop_name) { + _algo_params.Remove(prop_name); + _auto_props.Remove(prop_name); + } + + protected void link_enabled(string source_prop_name, string target_prop_name) => + link_enabled(source_prop_name, target_prop_name, _ => _); + + protected void link_enabled(string source_prop_name, string target_prop_name, Func get_enabled) { + if (_algo_params.TryGetValue(source_prop_name, out IAlgoParamVM sp) && _algo_params.TryGetValue(target_prop_name, out IAlgoParamVM target)) { + if (sp is IAlgoParamVM source) { + target.is_enabled = get_enabled(source.value); + source.value_changed += on_source_changed; + _resources.Add(Disposable.Create(() => source.value_changed -= on_source_changed)); + void on_source_changed(TSource oldval, TSource newval) => target.is_enabled = get_enabled(newval); + } + } + } + + void _on_property_added(string prop_name, int target_field_number, IProperty prop, Action assign_to_prop, T non_uniform_value, bool validate_on_changed, AlgoParamPermissions permissions, Func to_display_value = null, Func from_display_value = null, IObservable refresh_display_value = null) { + var field_desc = new TMutable().Descriptor.FindFieldByNumber(target_field_number); + var param = new AlgoParamVM(prop_name, DisplayNameHelper.snake_to_title_case(prop_name), prop.Value, EqualityComparer.Default, null, to_display_value, from_display_value) { + permissions = permissions + }; + _algo_params.Add(param); + var prop_hook = _link_props(param, prop, assign_to_prop, non_uniform_value, validate_on_changed); + if (refresh_display_value != null) { + prop_hook = Disposable.Create( + refresh_display_value.Subscribe(_ => param.refresh_display_value()), + prop_hook); + } + _auto_props.Add(new AutoProp(prop_name, mval => { + if (mval != null && param.has_value) + field_desc.Accessor.SetValue(mval, prop.Value); + }, + mval => assign_to_prop_and_commit(mval == null ? default : ConvertUtils.try_convert(field_desc.Accessor.GetValue(mval))), + mvals => assign_to_prop_and_commit(mvals.Select(v => ConvertUtils.try_convert(field_desc.Accessor.GetValue(v))).Distinct().SafeSingleOrDefault(non_uniform_value)), + prop_hook)); + void assign_to_prop_and_commit(T value) { + assign_to_prop(value); + param.mark_committed(); + } + } + + void _on_nullable_property_added( + string prop_name, + int target_field_number, + IProperty prop, + Action assign_to_prop, + bool validate_on_changed, + AlgoParamPermissions permissions, + IObservable refresh_display_value = null) where T : struct { + var field_desc = new TMutable().Descriptor.FindFieldByNumber(target_field_number); + var param = new AlgoParamVM(prop_name, DisplayNameHelper.snake_to_title_case(prop_name), prop.Value) { permissions = permissions }; + _algo_params.Add(param); + + var prop_hook = _link_props(param, prop, assign_to_prop, null, validate_on_changed); + if (refresh_display_value != null) { + prop_hook = Disposable.Create( + refresh_display_value.Subscribe(_ => param.refresh_display_value()), + prop_hook); + } + + _auto_props.Add(new AutoProp( + prop_name, + mval => { + if (mval != null && prop.Value.HasValue) + field_desc.Accessor.SetValue(mval, prop.Value.Value); + }, + mval => assign_to_prop_and_commit(mval is null ? + default : ConvertUtils.try_convert(field_desc.Accessor.GetValue(mval))), + mvals => assign_to_prop_and_commit(mvals + .Select(v => ConvertUtils.try_convert(field_desc.Accessor.GetValue(v))) + .Distinct() + .TryGetSingle(out var dv) ? dv : null), + prop_hook)); + + void assign_to_prop_and_commit(T? value) { + assign_to_prop(value); + param.mark_committed(); + } + } + + void _on_property_added(string prop_name, int target_field_number, OneofDescriptor oneof_descriptor, IProperty prop, Action assign_to_prop, T non_uniform_value, bool validate_on_changed, AlgoParamPermissions permissions) where T : struct { + var target_field_desc = ProtoHelper.Descriptor().FindFieldByNumber(target_field_number); + var param = new AlgoParamVM(prop_name, DisplayNameHelper.snake_to_title_case(prop_name), prop.Value) { permissions = permissions }; + var oneof_index = ProtoHelper.get_oneof_descriptor_index(oneof_descriptor); + _algo_params.Add(param); + _auto_props.Add(new AutoProp(prop_name, mval => { + if (mval == null || !param.has_value) + return; + if (!(target_field_desc.Accessor.GetValue(mval) is IMessage msg)) { + var type = ProtoHelper.get_field_type(target_field_desc); + target_field_desc.Accessor.SetValue(mval, msg = (IMessage)Activator.CreateInstance(type)); + } + var field_desc = ProtoHelper.get_oneof_field_descriptor(prop.Value); + var curr_field_desc = oneof_descriptor.Accessor.GetCaseFieldDescriptor(msg); + if (field_desc != curr_field_desc) { + if (field_desc == null) { + oneof_descriptor.Accessor.Clear(msg); + } else { + var t = ProtoHelper.get_field_type(field_desc); + if (t != null) + field_desc.Accessor.SetValue(msg, Activator.CreateInstance(t)); + } + } + }, mval => { + if (mval != null && target_field_desc.Accessor.GetValue(mval) is IMessage msg) + assign_to_prop_and_commit(ProtoHelper.get_oneof_case(oneof_descriptor, msg)); + }, + mvals => assign_to_prop_and_commit(mvals.Select(v => ConvertUtils.try_convert(target_field_desc.Accessor.GetValue(v))).Distinct().SafeSingleOrDefault()), + _link_props(param, prop, assign_to_prop, non_uniform_value, validate_on_changed))); + void assign_to_prop_and_commit(T value) { + assign_to_prop(value); + param.mark_committed(); + } + } + + void _on_property_added(string id, string prop_name, string display_name, int[] target_field_number_path, IProperty prop, Action assign_to_prop, T non_uniform_value = default, bool validate_on_changed = false, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) { + IMessage seed = new TMutable(); + var field_descs = Array.ConvertAll(target_field_number_path, n => { + var fd = seed.Descriptor.FindFieldByNumber(n); + var next_type = ProtoHelper.get_field_type(fd); + seed = Activator.CreateInstance(next_type) as IMessage; + return fd; + }); + var param = new AlgoParamVM(id, display_name, prop.Value) { permissions = permissions }; + _algo_params.Add(param); + _auto_props.Add(new AutoProp(prop_name, mval => { + if (mval != null && param.has_value) { + IMessage src = mval; + int i = 0; + do { + if (!(field_descs[i].Accessor.GetValue(src) is IMessage val)) { + var type = ProtoHelper.get_field_type(field_descs[i]); + val = Activator.CreateInstance(type) as IMessage; + if (val == null) return; + field_descs[i].Accessor.SetValue(src, val); + } + src = val; + } while (++i < field_descs.Length - 1); + field_descs[field_descs.Length - 1].Accessor.SetValue(src, prop.Value); + } + }, mval => assign_to_prop_and_commit(get_from_def(mval)), + mvals => assign_to_prop_and_commit(mvals.Select(get_from_def).Distinct().SafeSingleOrDefault(non_uniform_value)), + _link_props(param, prop, assign_to_prop, non_uniform_value, validate_on_changed))); + + T get_from_def(TMutable mval) { + var v = mval as IMessage; + for (int i = 0; i < field_descs.Length - 1 && v != null; i++) + v = field_descs[i].Accessor.GetValue(v) as IMessage; + return v == null ? default : ConvertUtils.try_convert(field_descs[field_descs.Length - 1].Accessor.GetValue(v)); + } + void assign_to_prop_and_commit(T value) { + assign_to_prop(value); + param.mark_committed(); + } + } + + void _on_nullable_property_added(string id, string prop_name, string display_name, int[] target_field_number_path, IProperty prop, Action assign_to_prop, bool validate_on_changed, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) where T : struct { + IMessage seed = new TMutable(); + var field_descs = Array.ConvertAll(target_field_number_path, n => { + var fd = seed.Descriptor.FindFieldByNumber(n); + var next_type = ProtoHelper.get_field_type(fd); + seed = Activator.CreateInstance(next_type) as IMessage; + return fd; + }); + var param = new AlgoParamVM(id, display_name, prop.Value) { permissions = permissions }; + _algo_params.Add(param); + _auto_props.Add(new AutoProp(prop_name, mval => { + if (mval != null && param.has_value) { + IMessage src = mval; + int i = 0; + do { + if (!(field_descs[i].Accessor.GetValue(src) is IMessage val)) { + var type = ProtoHelper.get_field_type(field_descs[i]); + val = Activator.CreateInstance(type) as IMessage; + if (val == null) return; + field_descs[i].Accessor.SetValue(src, val); + } + src = val; + } while (++i < field_descs.Length - 1); + if (prop.Value.HasValue) + field_descs[field_descs.Length - 1].Accessor.SetValue(src, prop.Value.Value); + } + }, mval => assign_to_prop_and_commit(get_from_def(mval)), + mvals => assign_to_prop_and_commit(mvals.Select(get_from_def).Distinct().TryGetSingle(out T dv) ? dv : (T?)null), + _link_props(param, prop, assign_to_prop, null, validate_on_changed))); + + T get_from_def(TMutable mval) { + var v = mval as IMessage; + for (int i = 0; i < field_descs.Length - 1 && v != null; i++) + v = field_descs[i].Accessor.GetValue(v) as IMessage; + return v == null ? default : ConvertUtils.try_convert(field_descs[field_descs.Length - 1].Accessor.GetValue(v)); + } + void assign_to_prop_and_commit(T? value) { + assign_to_prop(value); + param.mark_committed(); + } + } + + IDisposable _link_props(AlgoParamVM param, Property prop) => + _link_props(param, prop, prop.set, EqualityComparer.Default, default, false); + + IDisposable _link_props(AlgoParamVM param, IProperty prop, Action assign_to_prop, T invalid_value, bool validate_on_changed) => + _link_props(param, prop, assign_to_prop, EqualityComparer.Default, default, validate_on_changed); + + IDisposable _link_props(AlgoParamVM param, IProperty prop, Action assign_to_prop, IEqualityComparer comparer, T invalid_value = default, bool validate_on_changed = false) => + _link_props(param, prop.SubscribeValue(), assign_to_prop, comparer, invalid_value, validate_on_changed); + + IDisposable _link_props(AlgoParamVM param, IObservable prop_value_source, Action assign_to_prop, IEqualityComparer comparer, T invalid_value = default, bool validate_on_changed = false) { + param.has_value = !comparer.Equals(param.value, invalid_value); + return Disposable.Create( + prop_value_source.Subscribe(on_value_changed), + param.subscribe_value().Subscribe(assign_to_prop)); + void on_value_changed(T value) { + if (validate_on_changed) + validate(); + param.value = value; + param.has_value = !comparer.Equals(value, invalid_value); + } + } + #endregion + + protected virtual void on_model_internal() { } + protected virtual void on_security_md_internal() { } + protected virtual void on_security_internal() { } + + // model + void IObserver.OnNext(OrdersModel model) { + if (this.model != null) { + // this is not expected to happen, if it does just log and continue. + // it should be investigated at some point, bc it is a redundant update, but there is no need to sound the alarm and crash. + bts.Log.Ui.warn("Redundant OrdersModel update detected."); + return; + } + this.model = model; + RaisePropertyChanged(nameof(abbreviation)); + using (_def_change_notifier.defer()) { + on_model_internal(); + sync_selectors(); + } + } + void IObserver.OnError(Exception error) { } + void IObserver.OnCompleted() { } + // security md + void IObserver.OnNext(SecurityMD? security_md) { + using (_def_change_notifier.defer()) + using (_update_sec_input()) + _security_input = _security_input.with_security_md(security_md); + } + void IObserver.OnError(Exception error) { } + void IObserver.OnCompleted() { } + // security + void IObserver.OnNext(SecurityImmutable? security) { + using (_def_change_notifier.defer()) + using (_update_sec_input()) + _security_input = _security_input.with_security(security); + } + + void IObserver.OnError(Exception error) { } + void IObserver.OnCompleted() { } + // editing permissions + void IObserver.OnNext(AlgoEditingPermissions editing_permissions) => this.editing_permissions = editing_permissions; + void IObserver.OnError(Exception error) { } + void IObserver.OnCompleted() { } + + IDisposable _update_sec_input() { + var old_sec = security; + var old_sec_md = security_md; + return Disposable.Create(() => { + if (security != old_sec) { + on_security_internal(); + _security_changed?.Invoke(security); + } + if (security_md != old_sec_md) + on_security_md_internal(); + }); + } + + class AutoProp : IDisposable { + public readonly string name; + public readonly Action assign, load; + public readonly Action> assign_many, load_many; + IDisposable _dispose; + + public AutoProp(string name, Action assign, Action load, Action> load_many, IDisposable dispose) + : this(name, assign, load, algos => algos.ForEach(assign), load_many, dispose) { } + + public AutoProp(string name, Action assign, Action load, Action> assign_many, Action> load_many, IDisposable dispose) { + this.name = name; + this.assign = assign; + this.load = load; + this.load_many = load_many; + this.assign_many = assign_many; + _dispose = dispose; + } + + public void Dispose() => + Disposable.dispose(ref _dispose); + } + } + + // security input may come in 2 forms: + // 1) SecurityImmutable? + // 2) SecurityMD? + // This structure resolves conflicts that may arise from the different inputs + struct SecurityInput { + readonly SecurityMD? _raw_security_md; + readonly SecurityImmutable? _raw_security; + + public readonly SecurityMD? security_md; + public readonly SecurityImmutable? security; + + SecurityInput(SecurityImmutable? raw_security, SecurityMD? raw_security_md, SecurityImmutable? security, SecurityMD? security_md) { + _raw_security = raw_security; + _raw_security_md = raw_security_md; + this.security_md = security_md; + this.security = security; + } + + public SecurityInput with_security(SecurityImmutable? security) => + new SecurityInput( + security, + _raw_security_md, + security, + security.HasValue && _raw_security_md.HasValue && _raw_security_md.Value.security.Id != security.Value.Id ? + null : _raw_security_md); + + public SecurityInput with_security_md(SecurityMD? security_md) => + new SecurityInput( + _raw_security, + security_md, + security_md?.security ?? _raw_security, + security_md); + } + + struct AlgoSelectorData : IDisposable { + public readonly string prop_name; + public readonly AlgoSelector selector; + public readonly Func get_order; + public readonly Func get_mutable_from_impl; + public readonly Action set_order; + public readonly IDisposable hooks; + + public AlgoSelectorData(string id, AlgoSelector selector, Func get_mutable_from_impl, Func get_order, Action set_order, IDisposable hooks = null) { + this.prop_name = id; + this.selector = selector; + this.get_mutable_from_impl = get_mutable_from_impl; + this.get_order = get_order; + this.set_order = set_order; + this.hooks = hooks; + } + public AlgoDefi? get_from_impl(IMessage msg) { + var mchild = get_mutable_from_impl(msg); + return mchild != null ? new AlgoDefi(mchild) : (AlgoDefi?)null; + } + public void Dispose() => + hooks.Dispose(); + } + + class AlgoSelector : IAlgoSelector, INotifyPropertyChanged { + IAlgoVM _algo; + AlgoParamPermissions _permissions = AlgoParamPermissions.ReadWrite; + IReadOnlyDictionary _pending_data; + AlgoKey? _pending_default; + IDisposable _loaded_data_hook; + + public AlgoSelector(string id, string display_name) { + this.id = id; + this.display_name = display_name; + algos_view = ObservableAutoWrapper.create_sorted_wrapper(algos, AlgoCollectionHelper.algo_vm_comparer); + selected_algo_changed += (o, n) => _raise_property_changed(nameof(selected_algo)); + } + + public void load_algo_data(IReadOnlyDictionary algo_data, AlgoKey? default_algo) { + _pending_data = algo_data; + _pending_default = default_algo; + _sync_formats(); + } + + public event PropertyChange selected_algo_changed; + public event PropertyChange permissions_changed; + public event PropertyChangedEventHandler PropertyChanged; + + public string id { get; } + public string display_name { get; } + public bool is_enabled { get; set; } = true; + + public bool initialized { get; private set; } + + public ObservableKeyedCollection algos { get; } = + new ObservableKeyedCollection(vm => vm.id); + + public IReadOnlyObservableCollection algos_view { get; } + + public AlgoParamPermissions permissions { + get => _permissions; + set { + if (_set(ref _permissions, value, out var oldval)) + permissions_changed?.Invoke(oldval, value); + } + } + + public IAlgoVM selected_algo { + get { + if (!initialized) { + initialized = true; + _sync_formats(); + if (_algo != null && _algo.can_expand) + _algo.is_expanded = true; + } + return _algo; + } + set { + // this is a hack around a wpf snafu: in the AlgoStudio, the ComboBox bound to order_types/value, does not have a stable DataContext. + // Its DataContext is bound to the selected-definition/template. When this changes, the ItemsSource changes, and the [ComboBox]view always sets its SelectedItem to null. + // We must do something to prevent this, it isn't a mere annoyance that forces the user to re-select the ordertype after they select another template. + // In AlgoStudio, the ComboBox is only enabled for definining a new algo-structure, for templates it is disabled, so the user can't even open the dropdown! + // There is probably a better solution/workaround for this problem, but in the meantime this does the trick. + if (value == null && _algo != null && algos.Contains(_algo)) + return; + _select_algo(value); + } + } + + #region IAlgoParamVM + IAlgoVM IAlgoParamVM.value { get => selected_algo; set => selected_algo = value; } + IAlgoVM IAlgoParamVM.display_value { get => selected_algo; set => selected_algo = value; } + event PropertyChange IAlgoParamVM.value_changed { add => selected_algo_changed += value; remove => selected_algo_changed -= value; } + object IAlgoParamVM.value { get => selected_algo; set => selected_algo = (IAlgoVM)value; } + object IAlgoParamVM.display_value { get => selected_algo; set => selected_algo = (IAlgoVM)value; } + bool IAlgoParamVM.has_value => _algo != null; + // changing child algos is not allowed, so an algo selector is never dirty + bool IAlgoParamVM.is_dirty => false; + event Action IAlgoParamVM.is_dirty_changed { add { } remove { } } + + void IAlgoParamVM.revert() { } + void IAlgoParamVM.mark_committed() { } + #endregion + + public IObservable subscribe_selected_algo() { + return Observable.Create(o => { + if (initialized && _algo != null) { + o.OnNext(_algo); + } + selected_algo_changed += on_property_change; + return Disposable.Create(() => selected_algo_changed -= on_property_change); + void on_property_change(IAlgoVM oldval, IAlgoVM newval) => + o.OnNext(newval); + }); + } + + void _select_algo(IAlgoVM new_algo) { + if (new_algo != _algo) { + var old_algo = _algo; + _algo = new_algo; + selected_algo_changed?.Invoke(old_algo, new_algo); + } + } + + void _sync_formats() { + if (initialized && _pending_data != null) { + Disposable.dispose(ref _loaded_data_hook); + var data = _pending_data; + algos.SyncWithDictionary(data, d => create(d, is_expanded: true)); + _loaded_data_hook = ObservableAutoWrapper.connect_item_hooks(algos, vm => + ObservableAutoWrapper.connect_item_actions(vm.child_algo_selectors, s => s.load_algo_data(data, null))); + if (_algo == null || !algos.ContainsKey(_algo.id)) { + if (_pending_default.HasValue && algos.TryGetValue(_pending_default.Value, out IAlgoVM match)) + selected_algo = match; + } + } + } + + bool _set(ref T backing, T new_value, [CallerMemberName] string prop = "") => + _set(ref backing, new_value, out T _, EqualityComparer.Default, prop); + + bool _set(ref T backing, T new_value, out T old_value, [CallerMemberName] string prop = "") => + _set(ref backing, new_value, out old_value, EqualityComparer.Default, prop); + + bool _set(ref T backing, T new_value, out T old_value, IEqualityComparer comparer, [CallerMemberName] string prop = "") { + if (!comparer.Equals(new_value, backing)) { + old_value = backing; + backing = new_value; + return true; + } + old_value = backing; + return false; + } + + void _raise_property_changed([CallerMemberName] string prop = "") => + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop)); + + void IObserver<(IReadOnlyDictionary algo_data, AlgoKey? default_algo)>.OnNext((IReadOnlyDictionary algo_data, AlgoKey? default_algo) value) => + load_algo_data(value.algo_data, value.default_algo); + void IObserver<(IReadOnlyDictionary algo_data, AlgoKey? default_algo)>.OnCompleted() { } + void IObserver<(IReadOnlyDictionary algo_data, AlgoKey? default_algo)>.OnError(Exception error) { } + } + #endregion + } +} diff --git a/src/client/spark/view/Converters/Numeric/NumericSignBrushConverter.cs b/src/client/spark/view/Converters/Numeric/NumericSignBrushConverter.cs index fec25d68c..a5e65de72 100644 --- a/src/client/spark/view/Converters/Numeric/NumericSignBrushConverter.cs +++ b/src/client/spark/view/Converters/Numeric/NumericSignBrushConverter.cs @@ -1,74 +1,74 @@ -using bts.utils; - -using Spark.Core.Math; - -using System; -using System.Globalization; -using System.Windows.Data; -using System.Windows.Media; - -namespace mbts.ui.converters { - struct SignedDataStore { - public readonly T positive, neutral, negative, error; - - public SignedDataStore(T positive, T neutral, T negative, T error) { - this.positive = positive; - this.neutral = neutral; - this.negative = negative; - this.error = error; - } - } - - static class SignedDataStoreExtensions { - public static T get(this SignedDataStore store, double value) { - if (double.IsNaN(value)) return store.error; - else if (value > 0) return store.positive; - else if (value < 0) return store.negative; - else return store.neutral; - } - - public static SignedDataStore with_positive(this SignedDataStore store, T positive) => new SignedDataStore(positive, store.neutral, store.negative, store.error); - public static SignedDataStore with_neutral(this SignedDataStore store, T neutral) => new SignedDataStore(store.positive, neutral, store.negative, store.error); - public static SignedDataStore with_negative(this SignedDataStore store, T negative) => new SignedDataStore(store.positive, store.neutral, negative, store.error); - public static SignedDataStore with_error(this SignedDataStore store, T error) => new SignedDataStore(store.positive, store.neutral, store.negative, error); - } - - class NumericSignBrushConverter : IValueConverter { - SignedDataStore _brushes = new SignedDataStore( - BTSCoreColors.very_light_malachite_green.to_brush(true), - BTSColors.UI.default_text.to_brush(true), - BTSCoreColors.tulip.to_brush(true), - Brushes.Gray); - - public Color PositiveColor { get => _brushes.positive.Color; set => _brushes = _brushes.with_positive(new SolidColorBrush(value) { Opacity = _opacity }.frozen()); } - public Color NeutralColor { get => _brushes.neutral.Color; set => _brushes = _brushes.with_neutral(new SolidColorBrush(value) { Opacity = _opacity }.frozen()); } - public Color NegativeColor { get => _brushes.negative.Color; set => _brushes = _brushes.with_negative(new SolidColorBrush(value) { Opacity = _opacity }.frozen()); } - public Color ErrorColor { get => _brushes.error.Color; set => _brushes = _brushes.with_error(new SolidColorBrush(value) { Opacity = _opacity }.frozen()); } - - double _opacity = 1.0; - public double Opacity { - get => _opacity; - set { - _opacity = value; - _brushes = new SignedDataStore( - _brushes.positive.Clone().with(value).frozen(), - _brushes.neutral.Clone().with(value).frozen(), - _brushes.negative.Clone().with(value).frozen(), - _brushes.error.Clone().with(value).frozen()); - } - } - public IComparable Zero { get; set; } = new NumericOneof(0.0); - - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - var comparable = value as IComparable; - if (comparable == null || comparable is double && double.IsNaN((double)value)) - return _brushes.error; - /// [reverse]compare with bc it is the , and supports comparisons with most numeric types. - int comp = -Zero.CompareTo(comparable); - return comp == 0 ? _brushes.neutral : comp > 0 ? _brushes.positive : _brushes.negative; - } - - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => - throw new NotImplementedException(); - } -} +using bts.utils; + +using Spark.Core.Math; + +using System; +using System.Globalization; +using System.Windows.Data; +using System.Windows.Media; + +namespace mbts.ui.converters { + struct SignedDataStore { + public readonly T positive, neutral, negative, error; + + public SignedDataStore(T positive, T neutral, T negative, T error) { + this.positive = positive; + this.neutral = neutral; + this.negative = negative; + this.error = error; + } + } + + static class SignedDataStoreExtensions { + public static T get(this SignedDataStore store, double value) { + if (double.IsNaN(value)) return store.error; + else if (value > 0) return store.positive; + else if (value < 0) return store.negative; + else return store.neutral; + } + + public static SignedDataStore with_positive(this SignedDataStore store, T positive) => new SignedDataStore(positive, store.neutral, store.negative, store.error); + public static SignedDataStore with_neutral(this SignedDataStore store, T neutral) => new SignedDataStore(store.positive, neutral, store.negative, store.error); + public static SignedDataStore with_negative(this SignedDataStore store, T negative) => new SignedDataStore(store.positive, store.neutral, negative, store.error); + public static SignedDataStore with_error(this SignedDataStore store, T error) => new SignedDataStore(store.positive, store.neutral, store.negative, error); + } + + class NumericSignBrushConverter : IValueConverter { + SignedDataStore _brushes = new SignedDataStore( + BTSCoreColors.very_light_malachite_green.to_brush(true), + BTSColors.UI.default_text.to_brush(true), + BTSCoreColors.tulip.to_brush(true), + Brushes.Gray); + + public Color PositiveColor { get => _brushes.positive.Color; set => _brushes = _brushes.with_positive(new SolidColorBrush(value) { Opacity = _opacity }.frozen()); } + public Color NeutralColor { get => _brushes.neutral.Color; set => _brushes = _brushes.with_neutral(new SolidColorBrush(value) { Opacity = _opacity }.frozen()); } + public Color NegativeColor { get => _brushes.negative.Color; set => _brushes = _brushes.with_negative(new SolidColorBrush(value) { Opacity = _opacity }.frozen()); } + public Color ErrorColor { get => _brushes.error.Color; set => _brushes = _brushes.with_error(new SolidColorBrush(value) { Opacity = _opacity }.frozen()); } + + double _opacity = 1.0; + public double Opacity { + get => _opacity; + set { + _opacity = value; + _brushes = new SignedDataStore( + _brushes.positive.Clone().with(value).frozen(), + _brushes.neutral.Clone().with(value).frozen(), + _brushes.negative.Clone().with(value).frozen(), + _brushes.error.Clone().with(value).frozen()); + } + } + public IComparable Zero { get; set; } = new NumericOneof(0.0); + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { + var comparable = value as IComparable; + if (comparable == null || comparable is double && double.IsNaN((double)value)) + return _brushes.error; + /// [reverse]compare with bc it is the , and supports comparisons with most numeric types. + int comp = -Zero.CompareTo(comparable); + return comp == 0 ? _brushes.neutral : comp > 0 ? _brushes.positive : _brushes.negative; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => + throw new NotImplementedException(); + } +} diff --git a/src/client/spark_api/Orders/OrderDataHelper.cs b/src/client/spark_api/Orders/OrderDataHelper.cs index 787217559..2423b18d6 100644 --- a/src/client/spark_api/Orders/OrderDataHelper.cs +++ b/src/client/spark_api/Orders/OrderDataHelper.cs @@ -1,680 +1,680 @@ -using bts.api; -using bts.api.core; -using bts.api.orderman; -using bts.collections; -using bts.spark; -using bts.utils; - -using Google.Protobuf; -using Google.Protobuf.Reflection; -using Google.Protobuf.WellKnownTypes; - -using mbts.ui.utility; -using mbts.utils; - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reactive.Linq; -using System.Reflection; - -using OrderState = bts.api.orderman.OrderState; - -namespace mbts.spark.utilities { - public readonly struct ChildAlgoData { - public readonly string name; - public readonly Func get_child_from_impl; - public readonly Action assign_child_to_impl; - public readonly Func get_child; - public readonly Action assign_child; - - public ChildAlgoData( - string name, - Func get_child_from_impl, - Action assign_child_to_impl, - Func get_child, - Action assign_child) { - // - this.name = name; - this.get_child = get_child; - this.assign_child = assign_child; - this.get_child_from_impl = get_child_from_impl; - this.assign_child_to_impl = assign_child_to_impl; - } - } - - public class AlgoTypeCaseDescriptorData { - public readonly IReadOnlyList child_algo_data; - public readonly IReadOnlyList value_descriptors; - public readonly FieldDescriptor type_case_descriptor; - - public AlgoTypeCaseDescriptorData( - FieldDescriptor type_case_descriptor, - IReadOnlyList child_algo_data, - IReadOnlyList value_descriptors - ) { - this.type_case_descriptor = type_case_descriptor; - this.child_algo_data = child_algo_data; - this.value_descriptors = value_descriptors; - } - } - - public static class OrderDataHelper { - const string _primary_child_field = "child"; - // algo-type-case maps - // Note: obv this will break if we change the name of the 'CustomOneofCase' field - static readonly OneofDescriptor _oneof_desc = CustomOrderDefinition.Descriptor.Oneofs.FirstOrDefault(fd => fd.Name == "custom"); - static readonly IReadOnlyDictionary _algo_type_case_index; - static readonly IReadOnlyDictionary _algo_type_case_descriptor_data; - - static OrderDataHelper() { - var algo_type_case_index = new Dictionary(); - var algo_type_case_descriptor_data = new Dictionary(); - var child_algo_index = new Dictionary>(); - foreach (var fd in _oneof_desc.Fields) { - var type_case = EnumHelper.parse(fd.Name.Replace("_", "")); - algo_type_case_index.Add(fd.MessageType.ClrType, type_case); - var child_algo_data = new List(0); - var value_descriptors = new List(0); - foreach (var f in fd.MessageType.Fields.InDeclarationOrder()) { - if (is_child_algo_field(f)) { - child_algo_data.Add(new ChildAlgoData(f.Name, - msg => f.Accessor.GetValue(msg) as CustomOrderDefinition, - (msg, child) => f.Accessor.SetValue(msg, child), - def => { - var type_def = fd.Accessor.GetValue(def) as IMessage; - return f.Accessor.GetValue(type_def) as CustomOrderDefinition; - }, - (def, child) => { - if (fd.Accessor.GetValue(def) is IMessage m) - f.Accessor.SetValue(m, child); - })); - } else { - value_descriptors.Add(f); - } - } - algo_type_case_descriptor_data.Add(type_case, new AlgoTypeCaseDescriptorData(fd, child_algo_data, value_descriptors)); - } - _algo_type_case_index = algo_type_case_index; - _algo_type_case_descriptor_data = algo_type_case_descriptor_data; - // local methods - bool is_child_algo_field(FieldDescriptor f) => - f.FieldType == FieldType.Message && f.MessageType.ClrType == typeof(CustomOrderDefinition); - } - - #region Algo Structure/Hierarchy - public static AlgoTypeCaseDescriptorData get_algo_type_descriptor( - CustomOrderDefinition.CustomOneofCase algo_type) => - _algo_type_case_descriptor_data.TryGetValue(algo_type, out var d) ? d : - throw new ArgumentException( - $"Failed to find descriptor data for algo type '{algo_type}'", nameof(algo_type)); - - public static IEnumerable<(CustomOrderDefinition.CustomOneofCase type, string dyn, uint studio, uint spreader_sec)> enumerate_algo_structure(CustomOrderDefinitionImmutable custom_defi) { - string dyn = null; - uint studio = 0, spreader_sec = 0; - foreach (var cd in enumerate_algo_hierarchy(custom_defi.CloneToMutable())) { - switch (cd.CustomCase) { - case CustomOrderDefinition.CustomOneofCase.Composite: studio = cd.Composite.AlgoTemplateKey; break; - case CustomOrderDefinition.CustomOneofCase.Dynamic: dyn = cd.Dynamic.DynamicOrderType; break; - case CustomOrderDefinition.CustomOneofCase.Spreader: spreader_sec = cd.Spreader.Security?.Id ?? 0; break; - } - yield return (cd.CustomCase, dyn, studio, spreader_sec); - } - } - - /// - /// Enumerates through every algo member immediately defined (i.e., no recursion, just the first level of children). - /// - /// The root algo, from which enumeration begins. - /// An IEnumerable of each algo member contained in - public static IEnumerable enumerate_algo_children(CustomOrderDefinition custom_def) { - switch (custom_def.CustomCase) { - case CustomOrderDefinition.CustomOneofCase.Dynamic: - foreach (var kv in custom_def.Dynamic.OrderParams) { - if (kv.Value.ValueCase == DynamicOrderParam.ValueOneofCase.AsOrderDef) - yield return kv.Value.AsOrderDef ?? new CustomOrderDefinition(); - } - break; - default: - var child_algo_data = get_child_algo_data(custom_def); - if (child_algo_data.Count > 0) { - // need to convert to underlying proto type to use the [reflection-based]generated child selectors - for (int i = 0; i < child_algo_data.Count; i++) { - // don't skip undefined children (this normalizes the structure). - // each algo type should always yield the same number of children. - yield return child_algo_data[i].get_child(custom_def) ?? new CustomOrderDefinition(); - } - } - break; - } - } - - /// - /// Enumerates through every algo member contained in , excluding itself. - /// - /// The root algo, from which enumeration begins. - /// An IEnumerable of each algo member contained in - public static IEnumerable enumerate_algo_descendents(CustomOrderDefinition custom_def) { - foreach (var child in enumerate_algo_children(custom_def)) { - yield return child; - foreach (var grand_child in enumerate_algo_descendents(child)) - yield return grand_child; - } - } - - /// - /// Enumerates through every algo member contained in , including itself. - /// - /// The root algo, from which enumeration begins. - /// An IEnumerable of each algo member contained in - public static IEnumerable enumerate_algo_hierarchy(CustomOrderDefinition custom_def) { - yield return custom_def; - foreach (var d in enumerate_algo_descendents(custom_def)) - yield return d; - } - - public static IReadOnlyList get_child_algo_data(CustomOrderDefinitionImmutable defi) => - get_child_algo_data(defi.CloneToMutable()); - - public static IReadOnlyList get_child_algo_data(CustomOrderDefinition algo) { - switch (algo.CustomCase) { - case CustomOrderDefinition.CustomOneofCase.Dynamic: - return algo.Dynamic.OrderParams - .Where(kv => kv.Value.ValueCase == DynamicOrderParam.ValueOneofCase.AsOrderDef) - .Select(kv => new ChildAlgoData(kv.Key, def => - def is DynamicOrderDefinition dyn && - dyn.OrderParams.TryGetValue(kv.Key, out var p) && - p.ValueCase == DynamicOrderParam.ValueOneofCase.AsOrderDef ? - p.AsOrderDef : null, - (msg, child) => { - if (msg is DynamicOrderDefinition dyn) - dyn.OrderParams.GetOrAdd(kv.Key, k => new DynamicOrderParam()).AsOrderDef = child; - }, - def => def.Dynamic.OrderParams.TryGetValue(kv.Key, out DynamicOrderParam param) && param.ValueCase == DynamicOrderParam.ValueOneofCase.AsOrderDef ? param.AsOrderDef : null, - (def, child) => def.Dynamic.OrderParams.GetOrAdd(kv.Key, k => new DynamicOrderParam()).AsOrderDef = child)) - .ToList(); - default: - return get_child_algo_data(algo.CustomCase); - } - } - - public static ChildAlgoData? get_primary_child_algo_data(CustomOrderDefinition algo) { - var child_data = get_child_algo_data(algo); - return child_data.TryGetFirst(cad => cad.name == _primary_child_field, out ChildAlgoData best_match) ? best_match : - child_data.TryGetFirst(out best_match) ? best_match : (ChildAlgoData?)null; - } - - public static IReadOnlyList get_child_algo_data(CustomOrderDefinition.CustomOneofCase algo_type) => - _algo_type_case_descriptor_data.TryGetValue(algo_type, out AlgoTypeCaseDescriptorData d) ? d.child_algo_data : Array.Empty(); - #endregion - - public static string abbreviate_algo_type(CustomOrderDefinition.CustomOneofCase algo_type) { - switch (algo_type) { - case CustomOrderDefinition.CustomOneofCase.Limit: return "LM"; - case CustomOrderDefinition.CustomOneofCase.Cover: return "CV"; - case CustomOrderDefinition.CustomOneofCase.GlbxIceberg: return "GB"; - case CustomOrderDefinition.CustomOneofCase.Iceberg: return "IB"; - case CustomOrderDefinition.CustomOneofCase.Lean: return "LN"; - case CustomOrderDefinition.CustomOneofCase.Market: return "MA"; - case CustomOrderDefinition.CustomOneofCase.Oco: return "OC"; - case CustomOrderDefinition.CustomOneofCase.Offset: return "OF"; - case CustomOrderDefinition.CustomOneofCase.Pricer: return "PR"; - case CustomOrderDefinition.CustomOneofCase.Stop: return "SP"; - case CustomOrderDefinition.CustomOneofCase.StopLimit: return "SL"; - case CustomOrderDefinition.CustomOneofCase.Tick: return "TI"; - case CustomOrderDefinition.CustomOneofCase.TimeBox: return "TB"; - case CustomOrderDefinition.CustomOneofCase.Top: return "TP"; - case CustomOrderDefinition.CustomOneofCase.Trigger: return "TG"; - case CustomOrderDefinition.CustomOneofCase.Join: return "JN"; - case CustomOrderDefinition.CustomOneofCase.Spreader: return "SR"; - case CustomOrderDefinition.CustomOneofCase.Composite: return "COMP"; - default: return algo_type.ToString(); - } - } - - public static CustomOrderDefinition.CustomOneofCase get_default_algo(Security.ContractOneofCase security_type) { - switch (security_type) { - case Security.ContractOneofCase.Synthetic: return CustomOrderDefinition.CustomOneofCase.Spreader; - default: return CustomOrderDefinition.CustomOneofCase.Limit; - } - } - - public static readonly CustomOrderDefinition.CustomOneofCase[] - - // exchange_order_types are the types which can be submitted on an exchange security - exchange_order_types = new[] { - CustomOrderDefinition.CustomOneofCase.Market, - CustomOrderDefinition.CustomOneofCase.Limit, - CustomOrderDefinition.CustomOneofCase.Stop, - CustomOrderDefinition.CustomOneofCase.StopLimit, - CustomOrderDefinition.CustomOneofCase.GlbxIceberg, - CustomOrderDefinition.CustomOneofCase.Iceberg, - CustomOrderDefinition.CustomOneofCase.Lean, - CustomOrderDefinition.CustomOneofCase.Join, - CustomOrderDefinition.CustomOneofCase.Cover, - CustomOrderDefinition.CustomOneofCase.Top, - CustomOrderDefinition.CustomOneofCase.Offset, - CustomOrderDefinition.CustomOneofCase.Splitter, - CustomOrderDefinition.CustomOneofCase.Scratch, - CustomOrderDefinition.CustomOneofCase.Prorata, - }, - spreader_order_types = new[] { - CustomOrderDefinition.CustomOneofCase.Spreader, - CustomOrderDefinition.CustomOneofCase.Iceberg, - CustomOrderDefinition.CustomOneofCase.Lean, - CustomOrderDefinition.CustomOneofCase.Join, - CustomOrderDefinition.CustomOneofCase.Cover, - CustomOrderDefinition.CustomOneofCase.Top, - CustomOrderDefinition.CustomOneofCase.Splitter, - CustomOrderDefinition.CustomOneofCase.Scratch, - CustomOrderDefinition.CustomOneofCase.Prorata, - }, - attachable_order_types = new[] { - CustomOrderDefinition.CustomOneofCase.Iceberg, - CustomOrderDefinition.CustomOneofCase.Lean, - CustomOrderDefinition.CustomOneofCase.Join, - CustomOrderDefinition.CustomOneofCase.Cover, - CustomOrderDefinition.CustomOneofCase.Top, - CustomOrderDefinition.CustomOneofCase.Offset, - CustomOrderDefinition.CustomOneofCase.Scratch, - CustomOrderDefinition.CustomOneofCase.Prorata, - }, - outright_order_types = new[] { - CustomOrderDefinition.CustomOneofCase.Market, - CustomOrderDefinition.CustomOneofCase.Limit, - CustomOrderDefinition.CustomOneofCase.Stop, - CustomOrderDefinition.CustomOneofCase.StopLimit, - CustomOrderDefinition.CustomOneofCase.GlbxIceberg, - }; - public static readonly CustomOrderDefinition.CustomOneofCase[] all_order_types = exchange_order_types.Union(spreader_order_types).ToArray(); - - public static void copy_values(CustomOrderDefinitionImmutable source, ref CustomOrderDefinition target) => - copy_values(source.CloneToMutable(), ref target); - - public static void copy_values(CustomOrderDefinition source, ref CustomOrderDefinition target) { - if (source == null || target == null || source.CustomCase != target.CustomCase) - return; - var desc_data = _algo_type_case_descriptor_data[source.CustomCase]; - var src_type_def = desc_data.type_case_descriptor.Accessor.GetValue(source) as IMessage; - var tgt_type_def = desc_data.type_case_descriptor.Accessor.GetValue(target) as IMessage; - foreach (var fd in desc_data.value_descriptors) { - fd.Accessor.SetValue(tgt_type_def, fd.Accessor.GetValue(src_type_def)); - } - foreach (var cad in desc_data.child_algo_data) { - var src_child = cad.get_child_from_impl(src_type_def); - var tgt_child = cad.get_child_from_impl(tgt_type_def); - copy_values(src_child, ref tgt_child); - } - } - - public static CustomOrderDefinition.CustomOneofCase get_order_type(IMessage order_type_def) => - order_type_def != null && _algo_type_case_index.TryGetValue(order_type_def.Descriptor.ClrType, out CustomOrderDefinition.CustomOneofCase algo_case) ? - algo_case : CustomOrderDefinition.CustomOneofCase.None; - - public static void setup_generic_custom_order( - CustomOrderDefinition custom, CustomOrderDefinition.CustomOneofCase type) { - var prop = typeof(CustomOrderDefinition).GetProperty(type.ToString(), - BindingFlags.Instance | BindingFlags.Public); - var rt = prop.PropertyType; - var rtt = Activator.CreateInstance(rt); - - var ci = rt.GetProperties().Where(x => x.PropertyType == typeof(CustomOrderDefinition)); - foreach (var cid in ci) - cid.SetValue(rtt, new CustomOrderDefinition { Limit = new LimitOrderDefinition() }); - prop.SetValue(custom, rtt); - } - - #region Private Members - // get child - static CustomOrderDefinitionImmutable? _get_iceberg_child(IcebergOrderDefinitionImmutable iceberg) => iceberg.HasChild ? iceberg.Child : (CustomOrderDefinitionImmutable?)null; - static CustomOrderDefinitionImmutable? _get_time_box_child(TimeBoxOrderDefinitionImmutable time_box) => time_box.HasChild ? time_box.Child : (CustomOrderDefinitionImmutable?)null; - static CustomOrderDefinitionImmutable? _get_tick_child(TickOrderDefinitionImmutable tick) => tick.HasChild ? tick.Child : (CustomOrderDefinitionImmutable?)null; - static CustomOrderDefinitionImmutable? _get_lean_child(LeanOrderDefinitionImmutable lean) => lean.HasChild ? lean.Child : (CustomOrderDefinitionImmutable?)null; - static CustomOrderDefinitionImmutable? _get_join_child(JoinOrderDefinitionImmutable join) => join.HasChild ? join.Child : (CustomOrderDefinitionImmutable?)null; - static CustomOrderDefinitionImmutable? _get_top_child(TopOrderDefinitionImmutable top) => top.HasChild ? top.Child : (CustomOrderDefinitionImmutable?)null; - static CustomOrderDefinitionImmutable? _get_cover_child(CoverOrderDefinitionImmutable cover) => cover.HasChild ? cover.Child : (CustomOrderDefinitionImmutable?)null; - static CustomOrderDefinitionImmutable? _get_oco_child(OCOOrderDefinitionImmutable oco) => oco.HasChild ? oco.Child : (CustomOrderDefinitionImmutable?)null; - static CustomOrderDefinitionImmutable? _get_pricer_child(PricerOrderDefinitionImmutable pricer) => pricer.HasChild ? pricer.Child : (CustomOrderDefinitionImmutable?)null; - static CustomOrderDefinitionImmutable? _get_offset_child(OffsetOrderDefinitionImmutable offset) => offset.HasChild ? offset.Child : (CustomOrderDefinitionImmutable?)null; - static CustomOrderDefinitionImmutable? _get_trigger_child(TriggerOrderDefinitionImmutable trigger) => trigger.HasChild ? trigger.Child : (CustomOrderDefinitionImmutable?)null; - - // get hedge - static CustomOrderDefinitionImmutable? _get_cover_hedge(CoverOrderDefinitionImmutable cover) => cover.HasHedge ? cover.Hedge : (CustomOrderDefinitionImmutable?)null; - - // assign hedge - static void _assign_cover_hedge(ref CoverOrderDefinition cover, CustomOrderDefinition child) => cover.Child = child; - - // get other - static CustomOrderDefinitionImmutable? _get_oco_stop(OCOOrderDefinitionImmutable oco) => oco.HasOther ? oco.Other : (CustomOrderDefinitionImmutable?)null; - - // assign other - static void _assign_oco_hedge(ref OCOOrderDefinition oco, CustomOrderDefinition other) => oco.Other = other; - #endregion - - public static class EqualsHelpers { - // Unfortunately, the generated Equals method compares doubles with the '==' operator. - // That causes problems in some usages (e.g., AlgoStudio, and the Ladder/Ticket algo popup), bc double.NaN != double.NaN. - // These equality comparers should be user in such cases, as they use the actual double.Equals method, not the == operator. - // https://github.com/protocolbuffers/protobuf/issues/3725 - public static readonly IEqualityComparer - custom_order_defi_comparer = new CustomDefinitionComparer(), - custom_order_defi_structure_comparer = new CustomDefinitionStructureComparer(); - - public static bool equals(CustomOrderDefinitionImmutable a, CustomOrderDefinitionImmutable b) => custom_order_defi_comparer.Equals(a, b); - - public static bool iceberg_equals(IcebergOrderDefinitionImmutable a, IcebergOrderDefinitionImmutable b) => - a.ShowQuantity.Equals(b.ShowQuantity) && a.HasChild ? b.HasChild && equals(a.Child, b.Child) : !b.HasChild; - - public static bool join_equals(JoinOrderDefinitionImmutable a, JoinOrderDefinitionImmutable b) => - (a.HasJoinThreshold ? - b.HasJoinThreshold && quantity_measure_equals(a.JoinThreshold, b.JoinThreshold) : - !b.HasJoinThreshold) && - (a.HasChild ? - b.HasChild && equals(a.Child, b.Child) : - !b.HasChild); - - public static bool top_equals(TopOrderDefinitionImmutable a, TopOrderDefinitionImmutable b) => - a.TicksOff == b.TicksOff && - (a.HasTopThreshold ? - b.HasTopThreshold && quantity_measure_equals(a.TopThreshold, b.TopThreshold) : - !b.HasTopThreshold) && - (a.HasChild ? - b.HasChild && equals(a.Child, b.Child) : - !b.HasChild); - - public static bool lean_equals(LeanOrderDefinitionImmutable a, LeanOrderDefinitionImmutable b) => - a.MaxChaseTicks == b.MaxChaseTicks && - a.TradeTowardBehavior == b.TradeTowardBehavior && - (a.HasCrossThreshold ? - b.HasCrossThreshold && quantity_measure_equals(a.CrossThreshold, b.CrossThreshold) : - !b.HasCrossThreshold) && - (a.HasChild ? - b.HasChild && equals(a.Child, b.Child) : - !b.HasChild); - - public static bool stop_limit_equals(StopLimitOrderDefinitionImmutable a, StopLimitOrderDefinitionImmutable b) => - a.StopPrice.Equals(b.StopPrice); - - public static bool cover_equals(CoverOrderDefinitionImmutable a, CoverOrderDefinitionImmutable b) => - a.HedgeTicks == b.HedgeTicks && - (a.HasChild ? - b.HasChild && equals(a.Child, b.Child) : - !b.HasChild) && - (a.HasHedge ? - b.HasHedge && equals(a.Hedge, b.Hedge) : - !b.HasHedge); - - public static bool oco_equals(OCOOrderDefinitionImmutable a, OCOOrderDefinitionImmutable b) => - a.OtherTicks == b.OtherTicks && - (a.HasChild ? - b.HasChild && equals(a.Child, b.Child) : - !b.HasChild) && - (a.HasOther ? - b.HasOther && equals(a.Other, b.Other) : - !b.HasOther); - - public static bool pricer_equals(PricerOrderDefinitionImmutable a, PricerOrderDefinitionImmutable b) => - a.PriceFactor.Equals(b.PriceFactor) && a.HasChild ? b.HasChild && equals(a.Child, b.Child) : !b.HasChild; - - public static bool tick_equals(TickOrderDefinitionImmutable a, TickOrderDefinitionImmutable b) => - a.MaxChaseTicks == b.MaxChaseTicks && - a.TickOffsetOnDeploy == b.TickOffsetOnDeploy && - a.DetachOnToward == b.DetachOnToward && - (a.HasCrossThreshold ? - b.HasCrossThreshold && quantity_measure_equals(a.CrossThreshold, b.CrossThreshold) : - !b.HasCrossThreshold) && - (a.HasChild ? - b.HasChild && equals(a.Child, b.Child) : - !b.HasChild); - - public static bool trigger_equals(TriggerOrderDefinitionImmutable a, TriggerOrderDefinitionImmutable b) { - // TriggerAction - if (a.HasTriggerAction) { - if (!b.HasTriggerAction || !trigger_action_equals(a.TriggerAction, b.TriggerAction)) - return false; - } else if (b.HasTriggerAction) - return false; - // ExitCondition - if (a.HasExitCondition) { - if (!b.HasExitCondition || !trigger_exit_condition_equals(a.ExitCondition, b.ExitCondition)) - return false; - } else if (b.HasExitCondition) - return false; - if (a.HasTriggerCondition) { - if (!b.HasTriggerCondition || !trigger_condition_equals(a.TriggerCondition, b.TriggerCondition)) - return false; - } else if (b.HasTriggerCondition) - return false; - return a.HasChild ? b.HasChild && equals(a.Child, b.Child) : !b.HasChild; - } - - public static bool trigger_action_equals(TriggerActionImmutable a, TriggerActionImmutable b) { - if (a.OrderpriceCase != b.OrderpriceCase) - return false; - if (a.HasPayup) { - if (!b.HasPayup || !trigger_payup_price_equals(a.Payup, b.Payup)) - return false; - } else if (b.HasPayup) { - return false; - } - if (!a.Price.Equals(b.Price)) - return false; - return true; - } - - public static bool trigger_condition_equals(TriggerConditionImmutable a, TriggerConditionImmutable b) { - if (a.TriggerCase != b.TriggerCase || a.PriceType != b.PriceType) - return false; - switch (a.TriggerCase) { - case TriggerCondition.TriggerOneofCase.AbsolutePriceTrigger: return absolute_price_trigger_equals(a.AbsolutePriceTrigger, b.AbsolutePriceTrigger); - case TriggerCondition.TriggerOneofCase.TrailingTrigger: return trailing_trigger_equals(a.TrailingTrigger, b.TrailingTrigger); - case TriggerCondition.TriggerOneofCase.None: return true; - default: throw ExceptionBuilder.Argument.unexpected_case(a.TriggerCase, "TriggerCase"); - } - } - - public static bool trailing_trigger_equals(bts.api.orderman.TrailingTriggerImmutable a, bts.api.orderman.TrailingTriggerImmutable b) => - a.TriggerType == b.TriggerType && a.NumberOfTicks == b.NumberOfTicks; - - public static bool trigger_payup_price_equals(TriggerPayupPriceImmutable a, TriggerPayupPriceImmutable b) => - a.PayupPriceType == b.PayupPriceType && a.PriceType == b.PriceType && a.PayupTicks == b.PayupTicks; - - public static bool trigger_exit_condition_equals(TriggerExitConditionImmutable a, TriggerExitConditionImmutable b) => - a.TimeoutEnabled == b.TimeoutEnabled && a.TimeoutSeconds == b.TimeoutSeconds; - - public static bool absolute_price_trigger_equals(bts.api.orderman.AbsolutePriceTriggerImmutable a, bts.api.orderman.AbsolutePriceTriggerImmutable b) => - a.HasTriggerQuantity ? b.HasTriggerQuantity && trigger_quantity_equals(a.TriggerQuantity, b.TriggerQuantity) : !b.HasTriggerQuantity; - - public static bool trigger_quantity_equals(TriggerQuantityImmutable a, TriggerQuantityImmutable b) => - a.HasQuantityMeasure ? b.HasQuantityMeasure && quantity_measure_equals(a.QuantityMeasure, b.QuantityMeasure) : !b.HasQuantityMeasure; - - public static bool quantity_measure_equals(QuantityMeasureImmutable a, QuantityMeasureImmutable b) { - if (a.QuantityCase != b.QuantityCase) - return false; - switch (a.QuantityCase) { - case QuantityMeasure.QuantityOneofCase.Absolute: return a.Absolute == b.Absolute; - case QuantityMeasure.QuantityOneofCase.Ratio: return a.Ratio.Equals(b.Ratio); - case QuantityMeasure.QuantityOneofCase.None: return true; - default: throw ExceptionBuilder.Argument.unexpected_case(a.QuantityCase, "QuantityCase"); - } - } - - class CustomDefinitionComparer : IEqualityComparer { - public bool Equals(CustomOrderDefinitionImmutable a, CustomOrderDefinitionImmutable b) { - if (a.CustomCase != b.CustomCase) return false; - switch (a.CustomCase) { - case CustomOrderDefinition.CustomOneofCase.Cover: return cover_equals(a.Cover, b.Cover); - case CustomOrderDefinition.CustomOneofCase.Oco: return oco_equals(a.Oco, b.Oco); - case CustomOrderDefinition.CustomOneofCase.Pricer: return pricer_equals(a.Pricer, b.Pricer); - case CustomOrderDefinition.CustomOneofCase.Iceberg: return iceberg_equals(a.Iceberg, b.Iceberg); - case CustomOrderDefinition.CustomOneofCase.Join: return join_equals(a.Join, b.Join); - case CustomOrderDefinition.CustomOneofCase.Lean: return lean_equals(a.Lean, b.Lean); - case CustomOrderDefinition.CustomOneofCase.Limit: return true; - case CustomOrderDefinition.CustomOneofCase.StopLimit: return stop_limit_equals(a.StopLimit, b.StopLimit); - case CustomOrderDefinition.CustomOneofCase.Tick: return tick_equals(a.Tick, b.Tick); - case CustomOrderDefinition.CustomOneofCase.Top: return top_equals(a.Top, b.Top); - case CustomOrderDefinition.CustomOneofCase.Trigger: return trigger_equals(a.Trigger, b.Trigger); - default: return a.Equals(b); - } - } - - public int GetHashCode(CustomOrderDefinitionImmutable def) { - int hash = (int)def.CustomCase; - int phase_mult = 1; - switch (def.CustomCase) { - case CustomOrderDefinition.CustomOneofCase.Cover: - add_component(def.Cover.HedgeTicks.GetHashCode()); - add_component(_get_hash(_get_cover_child(def.Cover))); - add_component(_get_hash(_get_cover_hedge(def.Cover))); - break; - case CustomOrderDefinition.CustomOneofCase.Oco: - add_component(def.Oco.OtherTicks); - add_component(_get_hash(_get_oco_child(def.Oco))); - add_component(_get_hash(_get_oco_stop(def.Oco))); - break; - case CustomOrderDefinition.CustomOneofCase.Pricer: - add_component(def.Pricer.PriceFactor.GetHashCode()); - add_component(_get_hash(_get_pricer_child(def.Pricer))); - break; - case CustomOrderDefinition.CustomOneofCase.Iceberg: - add_component(def.Iceberg.ShowQuantity.GetHashCode()); - add_component(_get_hash(_get_iceberg_child(def.Iceberg))); - break; - case CustomOrderDefinition.CustomOneofCase.Join: - add_component(def.Join.HasJoinThreshold ? def.Join.JoinThreshold.GetHashCode() : 0); - add_component(_get_hash(_get_join_child(def.Join))); - break; - case CustomOrderDefinition.CustomOneofCase.Lean: - add_component(def.Lean.HasCrossThreshold ? def.Lean.CrossThreshold.GetHashCode() : 0); - add_component(_get_hash(_get_lean_child(def.Lean))); - break; - case CustomOrderDefinition.CustomOneofCase.StopLimit: - add_component(def.StopLimit.StopPrice.GetHashCode()); - break; - case CustomOrderDefinition.CustomOneofCase.Tick: - var tick = def.Tick; - add_component(tick.CrossTicks.GetHashCode()); - add_component(tick.MaxChaseTicks.GetHashCode()); - add_component(tick.TickOffsetOnDeploy.GetHashCode()); - add_component(tick.DetachOnToward.GetHashCode()); - add_component(tick.HasCrossThreshold ? def.Tick.CrossThreshold.GetHashCode() : 0); - add_component(_get_hash(_get_tick_child(tick))); - break; - case CustomOrderDefinition.CustomOneofCase.Top: - add_component(def.Top.TicksOff.GetHashCode()); - add_component(def.Top.HasTopThreshold ? def.Top.TopThreshold.GetHashCode() : 0); - add_component(_get_top_child(def.Top).GetHashCode()); - break; - case CustomOrderDefinition.CustomOneofCase.Trigger: - var trigger = def.Trigger; - add_component(trigger.HasExitCondition ? def.Trigger.ExitCondition.GetHashCode() : 0); - add_component(trigger.HasTriggerAction ? def.Trigger.TriggerAction.GetHashCode() : 0); - add_component(trigger.HasTriggerCondition ? def.Trigger.TriggerCondition.GetHashCode() : 0); - add_component(_get_hash(_get_trigger_child(trigger))); - break; - case CustomOrderDefinition.CustomOneofCase.Offset: - add_component(def.Offset.TickOffsetOnDeploy.GetHashCode()); - add_component(_get_hash(_get_offset_child(def.Offset))); - break; - } - return hash; - void add_component(int component_hash) => - _add_component(ref hash, ref phase_mult, component_hash); - } - - void _add_component(ref int hash, ref int phase_mult, int component_hash) => - hash += EqualityComparer.phase_hash(component_hash, phase_mult++, MathUtils.Primes.P_1087); - - int _get_hash(CustomOrderDefinitionImmutable? a) => a.HasValue ? GetHashCode(a.Value) : 0; - } - - class CustomDefinitionStructureComparer : IEqualityComparer { - public bool Equals(CustomOrderDefinitionImmutable def1, CustomOrderDefinitionImmutable def2) => - enumerate_algo_structure(def1).SequenceEqual(enumerate_algo_structure(def2)); - - public int GetHashCode(CustomOrderDefinitionImmutable def) => - EqualityComparer.auto_phase(enumerate_algo_structure(def)); - } - } - - public static class CompareUtils { - public static readonly IEqualityComparer order_record_id_eq_comparer = - EqualityComparer.Create(o => o.Key); - - public static readonly IComparer bid_price_comparer = - Comparer.Create((x, y) => MathUtils.epsilon_equals(x, y) ? 0 : y.CompareTo(x)); - - public static readonly IComparer ask_price_comparer = - Comparer.Create((x, y) => MathUtils.epsilon_equals(x, y) ? 0 : x.CompareTo(y)); - } - - public static class Defaults { - // param types - public static QuantityMeasure QuantityMeasure => new QuantityMeasure { Absolute = 1 }; - // core data types - public static AlgoData AlgoData() => spark.AlgoData.from_custom_def(CustomOrderDefinitionImmutable()); - public static AlgoData AlgoData(CustomOrderDefinition.CustomOneofCase algo_type) => spark.AlgoData.from_custom_def(CustomOrderDefinitionImmutable(algo_type)); - - public static OrderDefinition OrderDefinition => new OrderDefinition { CustomDef = new CustomOrderDefinition() }; - public static OrderRecord OrderRecord => new OrderRecord { - Def = OrderDefinition, - State = new OrderState { - LastChange = Timestamp.FromDateTime(DateTime.UtcNow) - } - }; - - public static OrderRecordImmutable OrderRecordImmutable { get; } = new OrderRecordImmutable(OrderRecord); - - public static CustomOrderDefinition CustomOrderDefinition() => new CustomOrderDefinition { Limit = LimitOrderDefinition() }; - public static CustomOrderDefinition CustomOrderDefinition(CustomOrderDefinition.CustomOneofCase order_type) { - var rv = new CustomOrderDefinition(); - switch (order_type) { - case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Market: rv.Market = MarketOrderDefinition(); break; - case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Limit: rv.Limit = LimitOrderDefinition(); break; - case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Stop: rv.Stop = StopOrderDefinition(); break; - case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.StopLimit: rv.StopLimit = StopLimitOrderDefinition(); break; - case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Iceberg: rv.Iceberg = IcebergOrderDefinition(); break; - case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.GlbxIceberg: rv.GlbxIceberg = GLBXIcebergOrderDefinition(); break; - case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.TimeBox: rv.TimeBox = TimeBoxOrderDefinition(); break; - case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Tick: rv.Tick = TickOrderDefinition(); break; - case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Lean: rv.Lean = LeanOrderDefinition(); break; - case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Join: rv.Join = JoinOrderDefinition(); break; - case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Top: rv.Top = TopOrderDefinition(); break; - case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Cover: rv.Cover = CoverOrderDefinition(); break; - case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Oco: rv.Oco = OCOOrderDefinition(); break; - case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Pricer: rv.Pricer = PricerOrderDefinition(); break; - case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Offset: rv.Offset = OffsetOrderDefinition(); break; - case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Trigger: rv.Trigger = TriggerOrderDefinition(); break; - case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Spreader: rv.Spreader = SpreaderOrderDefinition(); break; - case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Dynamic: rv.Dynamic = DynamicOrderDefinition(); break; - default: - setup_generic_custom_order(rv, order_type); - break; - } - return rv; - } - - public static CustomOrderDefinitionImmutable CustomOrderDefinitionImmutable() => new CustomOrderDefinitionImmutable(CustomOrderDefinition()); - public static CustomOrderDefinitionImmutable CustomOrderDefinitionImmutable(CustomOrderDefinition.CustomOneofCase order_type) => new CustomOrderDefinitionImmutable(CustomOrderDefinition(order_type)); - - public static MarketOrderDefinition MarketOrderDefinition() => new MarketOrderDefinition { }; - public static LimitOrderDefinition LimitOrderDefinition() => new LimitOrderDefinition { }; - public static StopOrderDefinition StopOrderDefinition() => new StopOrderDefinition { }; - public static StopLimitOrderDefinition StopLimitOrderDefinition() => new StopLimitOrderDefinition { }; - public static GLBXIcebergOrderDefinition GLBXIcebergOrderDefinition() => new GLBXIcebergOrderDefinition { MaxShowQuantity = 1 }; - public static IcebergOrderDefinition IcebergOrderDefinition() => new IcebergOrderDefinition { Child = CustomOrderDefinition(), ShowQuantity = 1 }; - public static TimeBoxOrderDefinition TimeBoxOrderDefinition() => new TimeBoxOrderDefinition { Child = CustomOrderDefinition(), Start = Timestamp.FromDateTime(DateTime.UtcNow), Stop = Timestamp.FromDateTime(DateTime.UtcNow) }; - public static TickOrderDefinition TickOrderDefinition() => new TickOrderDefinition { Child = CustomOrderDefinition(), CrossThreshold = QuantityMeasure }; - public static LeanOrderDefinition LeanOrderDefinition() => new LeanOrderDefinition { Child = CustomOrderDefinition(), CrossThreshold = QuantityMeasure, MaxChaseTicks = 2 }; - public static JoinOrderDefinition JoinOrderDefinition() => new JoinOrderDefinition { Child = CustomOrderDefinition(), JoinThreshold = QuantityMeasure }; - public static TopOrderDefinition TopOrderDefinition() => new TopOrderDefinition { Child = CustomOrderDefinition(), TopThreshold = QuantityMeasure }; - public static CoverOrderDefinition CoverOrderDefinition() => new CoverOrderDefinition { Child = CustomOrderDefinition(), Hedge = CustomOrderDefinition(), HedgeTicks = 1 }; - public static OCOOrderDefinition OCOOrderDefinition() => new OCOOrderDefinition { Child = CustomOrderDefinition(), Other = CustomOrderDefinition(), OtherSide = RelativeSide.Same }; - public static PricerOrderDefinition PricerOrderDefinition() => new PricerOrderDefinition { Child = CustomOrderDefinition() }; - public static OffsetOrderDefinition OffsetOrderDefinition() => new OffsetOrderDefinition { Child = CustomOrderDefinition(), }; - public static TriggerOrderDefinition TriggerOrderDefinition() => new TriggerOrderDefinition { Child = CustomOrderDefinition(), TriggerCondition = new TriggerCondition(), TriggerAction = new TriggerAction(), }; - public static DynamicOrderDefinition DynamicOrderDefinition() => new DynamicOrderDefinition(); - public static SpreaderOrderDefinition SpreaderOrderDefinition() => new SpreaderOrderDefinition { ExecutionStrategy = new ExecutionStrategy() }; - } - } -} +using bts.api; +using bts.api.core; +using bts.api.orderman; +using bts.collections; +using bts.spark; +using bts.utils; + +using Google.Protobuf; +using Google.Protobuf.Reflection; +using Google.Protobuf.WellKnownTypes; + +using mbts.ui.utility; +using mbts.utils; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Linq; +using System.Reflection; + +using OrderState = bts.api.orderman.OrderState; + +namespace mbts.spark.utilities { + public readonly struct ChildAlgoData { + public readonly string name; + public readonly Func get_child_from_impl; + public readonly Action assign_child_to_impl; + public readonly Func get_child; + public readonly Action assign_child; + + public ChildAlgoData( + string name, + Func get_child_from_impl, + Action assign_child_to_impl, + Func get_child, + Action assign_child) { + // + this.name = name; + this.get_child = get_child; + this.assign_child = assign_child; + this.get_child_from_impl = get_child_from_impl; + this.assign_child_to_impl = assign_child_to_impl; + } + } + + public class AlgoTypeCaseDescriptorData { + public readonly IReadOnlyList child_algo_data; + public readonly IReadOnlyList value_descriptors; + public readonly FieldDescriptor type_case_descriptor; + + public AlgoTypeCaseDescriptorData( + FieldDescriptor type_case_descriptor, + IReadOnlyList child_algo_data, + IReadOnlyList value_descriptors + ) { + this.type_case_descriptor = type_case_descriptor; + this.child_algo_data = child_algo_data; + this.value_descriptors = value_descriptors; + } + } + + public static class OrderDataHelper { + const string _primary_child_field = "child"; + // algo-type-case maps + // Note: obv this will break if we change the name of the 'CustomOneofCase' field + static readonly OneofDescriptor _oneof_desc = CustomOrderDefinition.Descriptor.Oneofs.FirstOrDefault(fd => fd.Name == "custom"); + static readonly IReadOnlyDictionary _algo_type_case_index; + static readonly IReadOnlyDictionary _algo_type_case_descriptor_data; + + static OrderDataHelper() { + var algo_type_case_index = new Dictionary(); + var algo_type_case_descriptor_data = new Dictionary(); + var child_algo_index = new Dictionary>(); + foreach (var fd in _oneof_desc.Fields) { + var type_case = EnumHelper.parse(fd.Name.Replace("_", "")); + algo_type_case_index.Add(fd.MessageType.ClrType, type_case); + var child_algo_data = new List(0); + var value_descriptors = new List(0); + foreach (var f in fd.MessageType.Fields.InDeclarationOrder()) { + if (is_child_algo_field(f)) { + child_algo_data.Add(new ChildAlgoData(f.Name, + msg => f.Accessor.GetValue(msg) as CustomOrderDefinition, + (msg, child) => f.Accessor.SetValue(msg, child), + def => { + var type_def = fd.Accessor.GetValue(def) as IMessage; + return f.Accessor.GetValue(type_def) as CustomOrderDefinition; + }, + (def, child) => { + if (fd.Accessor.GetValue(def) is IMessage m) + f.Accessor.SetValue(m, child); + })); + } else { + value_descriptors.Add(f); + } + } + algo_type_case_descriptor_data.Add(type_case, new AlgoTypeCaseDescriptorData(fd, child_algo_data, value_descriptors)); + } + _algo_type_case_index = algo_type_case_index; + _algo_type_case_descriptor_data = algo_type_case_descriptor_data; + // local methods + bool is_child_algo_field(FieldDescriptor f) => + f.FieldType == FieldType.Message && f.MessageType.ClrType == typeof(CustomOrderDefinition); + } + + #region Algo Structure/Hierarchy + public static AlgoTypeCaseDescriptorData get_algo_type_descriptor( + CustomOrderDefinition.CustomOneofCase algo_type) => + _algo_type_case_descriptor_data.TryGetValue(algo_type, out var d) ? d : + throw new ArgumentException( + $"Failed to find descriptor data for algo type '{algo_type}'", nameof(algo_type)); + + public static IEnumerable<(CustomOrderDefinition.CustomOneofCase type, string dyn, uint studio, uint spreader_sec)> enumerate_algo_structure(CustomOrderDefinitionImmutable custom_defi) { + string dyn = null; + uint studio = 0, spreader_sec = 0; + foreach (var cd in enumerate_algo_hierarchy(custom_defi.CloneToMutable())) { + switch (cd.CustomCase) { + case CustomOrderDefinition.CustomOneofCase.Composite: studio = cd.Composite.AlgoTemplateKey; break; + case CustomOrderDefinition.CustomOneofCase.Dynamic: dyn = cd.Dynamic.DynamicOrderType; break; + case CustomOrderDefinition.CustomOneofCase.Spreader: spreader_sec = cd.Spreader.Security?.Id ?? 0; break; + } + yield return (cd.CustomCase, dyn, studio, spreader_sec); + } + } + + /// + /// Enumerates through every algo member immediately defined (i.e., no recursion, just the first level of children). + /// + /// The root algo, from which enumeration begins. + /// An IEnumerable of each algo member contained in + public static IEnumerable enumerate_algo_children(CustomOrderDefinition custom_def) { + switch (custom_def.CustomCase) { + case CustomOrderDefinition.CustomOneofCase.Dynamic: + foreach (var kv in custom_def.Dynamic.OrderParams) { + if (kv.Value.ValueCase == DynamicOrderParam.ValueOneofCase.AsOrderDef) + yield return kv.Value.AsOrderDef ?? new CustomOrderDefinition(); + } + break; + default: + var child_algo_data = get_child_algo_data(custom_def); + if (child_algo_data.Count > 0) { + // need to convert to underlying proto type to use the [reflection-based]generated child selectors + for (int i = 0; i < child_algo_data.Count; i++) { + // don't skip undefined children (this normalizes the structure). + // each algo type should always yield the same number of children. + yield return child_algo_data[i].get_child(custom_def) ?? new CustomOrderDefinition(); + } + } + break; + } + } + + /// + /// Enumerates through every algo member contained in , excluding itself. + /// + /// The root algo, from which enumeration begins. + /// An IEnumerable of each algo member contained in + public static IEnumerable enumerate_algo_descendents(CustomOrderDefinition custom_def) { + foreach (var child in enumerate_algo_children(custom_def)) { + yield return child; + foreach (var grand_child in enumerate_algo_descendents(child)) + yield return grand_child; + } + } + + /// + /// Enumerates through every algo member contained in , including itself. + /// + /// The root algo, from which enumeration begins. + /// An IEnumerable of each algo member contained in + public static IEnumerable enumerate_algo_hierarchy(CustomOrderDefinition custom_def) { + yield return custom_def; + foreach (var d in enumerate_algo_descendents(custom_def)) + yield return d; + } + + public static IReadOnlyList get_child_algo_data(CustomOrderDefinitionImmutable defi) => + get_child_algo_data(defi.CloneToMutable()); + + public static IReadOnlyList get_child_algo_data(CustomOrderDefinition algo) { + switch (algo.CustomCase) { + case CustomOrderDefinition.CustomOneofCase.Dynamic: + return algo.Dynamic.OrderParams + .Where(kv => kv.Value.ValueCase == DynamicOrderParam.ValueOneofCase.AsOrderDef) + .Select(kv => new ChildAlgoData(kv.Key, def => + def is DynamicOrderDefinition dyn && + dyn.OrderParams.TryGetValue(kv.Key, out var p) && + p.ValueCase == DynamicOrderParam.ValueOneofCase.AsOrderDef ? + p.AsOrderDef : null, + (msg, child) => { + if (msg is DynamicOrderDefinition dyn) + dyn.OrderParams.GetOrAdd(kv.Key, k => new DynamicOrderParam()).AsOrderDef = child; + }, + def => def.Dynamic.OrderParams.TryGetValue(kv.Key, out DynamicOrderParam param) && param.ValueCase == DynamicOrderParam.ValueOneofCase.AsOrderDef ? param.AsOrderDef : null, + (def, child) => def.Dynamic.OrderParams.GetOrAdd(kv.Key, k => new DynamicOrderParam()).AsOrderDef = child)) + .ToList(); + default: + return get_child_algo_data(algo.CustomCase); + } + } + + public static ChildAlgoData? get_primary_child_algo_data(CustomOrderDefinition algo) { + var child_data = get_child_algo_data(algo); + return child_data.TryGetFirst(cad => cad.name == _primary_child_field, out ChildAlgoData best_match) ? best_match : + child_data.TryGetFirst(out best_match) ? best_match : (ChildAlgoData?)null; + } + + public static IReadOnlyList get_child_algo_data(CustomOrderDefinition.CustomOneofCase algo_type) => + _algo_type_case_descriptor_data.TryGetValue(algo_type, out AlgoTypeCaseDescriptorData d) ? d.child_algo_data : Array.Empty(); + #endregion + + public static string abbreviate_algo_type(CustomOrderDefinition.CustomOneofCase algo_type) { + switch (algo_type) { + case CustomOrderDefinition.CustomOneofCase.Limit: return "LM"; + case CustomOrderDefinition.CustomOneofCase.Cover: return "CV"; + case CustomOrderDefinition.CustomOneofCase.GlbxIceberg: return "GB"; + case CustomOrderDefinition.CustomOneofCase.Iceberg: return "IB"; + case CustomOrderDefinition.CustomOneofCase.Lean: return "LN"; + case CustomOrderDefinition.CustomOneofCase.Market: return "MA"; + case CustomOrderDefinition.CustomOneofCase.Oco: return "OC"; + case CustomOrderDefinition.CustomOneofCase.Offset: return "OF"; + case CustomOrderDefinition.CustomOneofCase.Pricer: return "PR"; + case CustomOrderDefinition.CustomOneofCase.Stop: return "SP"; + case CustomOrderDefinition.CustomOneofCase.StopLimit: return "SL"; + case CustomOrderDefinition.CustomOneofCase.Tick: return "TI"; + case CustomOrderDefinition.CustomOneofCase.TimeBox: return "TB"; + case CustomOrderDefinition.CustomOneofCase.Top: return "TP"; + case CustomOrderDefinition.CustomOneofCase.Trigger: return "TG"; + case CustomOrderDefinition.CustomOneofCase.Join: return "JN"; + case CustomOrderDefinition.CustomOneofCase.Spreader: return "SR"; + case CustomOrderDefinition.CustomOneofCase.Composite: return "COMP"; + default: return algo_type.ToString(); + } + } + + public static CustomOrderDefinition.CustomOneofCase get_default_algo(Security.ContractOneofCase security_type) { + switch (security_type) { + case Security.ContractOneofCase.Synthetic: return CustomOrderDefinition.CustomOneofCase.Spreader; + default: return CustomOrderDefinition.CustomOneofCase.Limit; + } + } + + public static readonly CustomOrderDefinition.CustomOneofCase[] + + // exchange_order_types are the types which can be submitted on an exchange security + exchange_order_types = new[] { + CustomOrderDefinition.CustomOneofCase.Market, + CustomOrderDefinition.CustomOneofCase.Limit, + CustomOrderDefinition.CustomOneofCase.Stop, + CustomOrderDefinition.CustomOneofCase.StopLimit, + CustomOrderDefinition.CustomOneofCase.GlbxIceberg, + CustomOrderDefinition.CustomOneofCase.Iceberg, + CustomOrderDefinition.CustomOneofCase.Lean, + CustomOrderDefinition.CustomOneofCase.Join, + CustomOrderDefinition.CustomOneofCase.Cover, + CustomOrderDefinition.CustomOneofCase.Top, + CustomOrderDefinition.CustomOneofCase.Offset, + CustomOrderDefinition.CustomOneofCase.Splitter, + CustomOrderDefinition.CustomOneofCase.Scratch, + CustomOrderDefinition.CustomOneofCase.Prorata, + }, + spreader_order_types = new[] { + CustomOrderDefinition.CustomOneofCase.Spreader, + CustomOrderDefinition.CustomOneofCase.Iceberg, + CustomOrderDefinition.CustomOneofCase.Lean, + CustomOrderDefinition.CustomOneofCase.Join, + CustomOrderDefinition.CustomOneofCase.Cover, + CustomOrderDefinition.CustomOneofCase.Top, + CustomOrderDefinition.CustomOneofCase.Splitter, + CustomOrderDefinition.CustomOneofCase.Scratch, + CustomOrderDefinition.CustomOneofCase.Prorata, + }, + attachable_order_types = new[] { + CustomOrderDefinition.CustomOneofCase.Iceberg, + CustomOrderDefinition.CustomOneofCase.Lean, + CustomOrderDefinition.CustomOneofCase.Join, + CustomOrderDefinition.CustomOneofCase.Cover, + CustomOrderDefinition.CustomOneofCase.Top, + CustomOrderDefinition.CustomOneofCase.Offset, + CustomOrderDefinition.CustomOneofCase.Scratch, + CustomOrderDefinition.CustomOneofCase.Prorata, + }, + outright_order_types = new[] { + CustomOrderDefinition.CustomOneofCase.Market, + CustomOrderDefinition.CustomOneofCase.Limit, + CustomOrderDefinition.CustomOneofCase.Stop, + CustomOrderDefinition.CustomOneofCase.StopLimit, + CustomOrderDefinition.CustomOneofCase.GlbxIceberg, + }; + public static readonly CustomOrderDefinition.CustomOneofCase[] all_order_types = exchange_order_types.Union(spreader_order_types).ToArray(); + + public static void copy_values(CustomOrderDefinitionImmutable source, ref CustomOrderDefinition target) => + copy_values(source.CloneToMutable(), ref target); + + public static void copy_values(CustomOrderDefinition source, ref CustomOrderDefinition target) { + if (source == null || target == null || source.CustomCase != target.CustomCase) + return; + var desc_data = _algo_type_case_descriptor_data[source.CustomCase]; + var src_type_def = desc_data.type_case_descriptor.Accessor.GetValue(source) as IMessage; + var tgt_type_def = desc_data.type_case_descriptor.Accessor.GetValue(target) as IMessage; + foreach (var fd in desc_data.value_descriptors) { + fd.Accessor.SetValue(tgt_type_def, fd.Accessor.GetValue(src_type_def)); + } + foreach (var cad in desc_data.child_algo_data) { + var src_child = cad.get_child_from_impl(src_type_def); + var tgt_child = cad.get_child_from_impl(tgt_type_def); + copy_values(src_child, ref tgt_child); + } + } + + public static CustomOrderDefinition.CustomOneofCase get_order_type(IMessage order_type_def) => + order_type_def != null && _algo_type_case_index.TryGetValue(order_type_def.Descriptor.ClrType, out CustomOrderDefinition.CustomOneofCase algo_case) ? + algo_case : CustomOrderDefinition.CustomOneofCase.None; + + public static void setup_generic_custom_order( + CustomOrderDefinition custom, CustomOrderDefinition.CustomOneofCase type) { + var prop = typeof(CustomOrderDefinition).GetProperty(type.ToString(), + BindingFlags.Instance | BindingFlags.Public); + var rt = prop.PropertyType; + var rtt = Activator.CreateInstance(rt); + + var ci = rt.GetProperties().Where(x => x.PropertyType == typeof(CustomOrderDefinition)); + foreach (var cid in ci) + cid.SetValue(rtt, new CustomOrderDefinition { Limit = new LimitOrderDefinition() }); + prop.SetValue(custom, rtt); + } + + #region Private Members + // get child + static CustomOrderDefinitionImmutable? _get_iceberg_child(IcebergOrderDefinitionImmutable iceberg) => iceberg.HasChild ? iceberg.Child : (CustomOrderDefinitionImmutable?)null; + static CustomOrderDefinitionImmutable? _get_time_box_child(TimeBoxOrderDefinitionImmutable time_box) => time_box.HasChild ? time_box.Child : (CustomOrderDefinitionImmutable?)null; + static CustomOrderDefinitionImmutable? _get_tick_child(TickOrderDefinitionImmutable tick) => tick.HasChild ? tick.Child : (CustomOrderDefinitionImmutable?)null; + static CustomOrderDefinitionImmutable? _get_lean_child(LeanOrderDefinitionImmutable lean) => lean.HasChild ? lean.Child : (CustomOrderDefinitionImmutable?)null; + static CustomOrderDefinitionImmutable? _get_join_child(JoinOrderDefinitionImmutable join) => join.HasChild ? join.Child : (CustomOrderDefinitionImmutable?)null; + static CustomOrderDefinitionImmutable? _get_top_child(TopOrderDefinitionImmutable top) => top.HasChild ? top.Child : (CustomOrderDefinitionImmutable?)null; + static CustomOrderDefinitionImmutable? _get_cover_child(CoverOrderDefinitionImmutable cover) => cover.HasChild ? cover.Child : (CustomOrderDefinitionImmutable?)null; + static CustomOrderDefinitionImmutable? _get_oco_child(OCOOrderDefinitionImmutable oco) => oco.HasChild ? oco.Child : (CustomOrderDefinitionImmutable?)null; + static CustomOrderDefinitionImmutable? _get_pricer_child(PricerOrderDefinitionImmutable pricer) => pricer.HasChild ? pricer.Child : (CustomOrderDefinitionImmutable?)null; + static CustomOrderDefinitionImmutable? _get_offset_child(OffsetOrderDefinitionImmutable offset) => offset.HasChild ? offset.Child : (CustomOrderDefinitionImmutable?)null; + static CustomOrderDefinitionImmutable? _get_trigger_child(TriggerOrderDefinitionImmutable trigger) => trigger.HasChild ? trigger.Child : (CustomOrderDefinitionImmutable?)null; + + // get hedge + static CustomOrderDefinitionImmutable? _get_cover_hedge(CoverOrderDefinitionImmutable cover) => cover.HasHedge ? cover.Hedge : (CustomOrderDefinitionImmutable?)null; + + // assign hedge + static void _assign_cover_hedge(ref CoverOrderDefinition cover, CustomOrderDefinition child) => cover.Child = child; + + // get other + static CustomOrderDefinitionImmutable? _get_oco_stop(OCOOrderDefinitionImmutable oco) => oco.HasOther ? oco.Other : (CustomOrderDefinitionImmutable?)null; + + // assign other + static void _assign_oco_hedge(ref OCOOrderDefinition oco, CustomOrderDefinition other) => oco.Other = other; + #endregion + + public static class EqualsHelpers { + // Unfortunately, the generated Equals method compares doubles with the '==' operator. + // That causes problems in some usages (e.g., AlgoStudio, and the Ladder/Ticket algo popup), bc double.NaN != double.NaN. + // These equality comparers should be user in such cases, as they use the actual double.Equals method, not the == operator. + // https://github.com/protocolbuffers/protobuf/issues/3725 + public static readonly IEqualityComparer + custom_order_defi_comparer = new CustomDefinitionComparer(), + custom_order_defi_structure_comparer = new CustomDefinitionStructureComparer(); + + public static bool equals(CustomOrderDefinitionImmutable a, CustomOrderDefinitionImmutable b) => custom_order_defi_comparer.Equals(a, b); + + public static bool iceberg_equals(IcebergOrderDefinitionImmutable a, IcebergOrderDefinitionImmutable b) => + a.ShowQuantity.Equals(b.ShowQuantity) && a.HasChild ? b.HasChild && equals(a.Child, b.Child) : !b.HasChild; + + public static bool join_equals(JoinOrderDefinitionImmutable a, JoinOrderDefinitionImmutable b) => + (a.HasJoinThreshold ? + b.HasJoinThreshold && quantity_measure_equals(a.JoinThreshold, b.JoinThreshold) : + !b.HasJoinThreshold) && + (a.HasChild ? + b.HasChild && equals(a.Child, b.Child) : + !b.HasChild); + + public static bool top_equals(TopOrderDefinitionImmutable a, TopOrderDefinitionImmutable b) => + a.TicksOff == b.TicksOff && + (a.HasTopThreshold ? + b.HasTopThreshold && quantity_measure_equals(a.TopThreshold, b.TopThreshold) : + !b.HasTopThreshold) && + (a.HasChild ? + b.HasChild && equals(a.Child, b.Child) : + !b.HasChild); + + public static bool lean_equals(LeanOrderDefinitionImmutable a, LeanOrderDefinitionImmutable b) => + a.MaxChaseTicks == b.MaxChaseTicks && + a.TradeTowardBehavior == b.TradeTowardBehavior && + (a.HasCrossThreshold ? + b.HasCrossThreshold && quantity_measure_equals(a.CrossThreshold, b.CrossThreshold) : + !b.HasCrossThreshold) && + (a.HasChild ? + b.HasChild && equals(a.Child, b.Child) : + !b.HasChild); + + public static bool stop_limit_equals(StopLimitOrderDefinitionImmutable a, StopLimitOrderDefinitionImmutable b) => + a.StopPrice.Equals(b.StopPrice); + + public static bool cover_equals(CoverOrderDefinitionImmutable a, CoverOrderDefinitionImmutable b) => + a.HedgeTicks == b.HedgeTicks && + (a.HasChild ? + b.HasChild && equals(a.Child, b.Child) : + !b.HasChild) && + (a.HasHedge ? + b.HasHedge && equals(a.Hedge, b.Hedge) : + !b.HasHedge); + + public static bool oco_equals(OCOOrderDefinitionImmutable a, OCOOrderDefinitionImmutable b) => + a.OtherTicks == b.OtherTicks && + (a.HasChild ? + b.HasChild && equals(a.Child, b.Child) : + !b.HasChild) && + (a.HasOther ? + b.HasOther && equals(a.Other, b.Other) : + !b.HasOther); + + public static bool pricer_equals(PricerOrderDefinitionImmutable a, PricerOrderDefinitionImmutable b) => + a.PriceFactor.Equals(b.PriceFactor) && a.HasChild ? b.HasChild && equals(a.Child, b.Child) : !b.HasChild; + + public static bool tick_equals(TickOrderDefinitionImmutable a, TickOrderDefinitionImmutable b) => + a.MaxChaseTicks == b.MaxChaseTicks && + a.TickOffsetOnDeploy == b.TickOffsetOnDeploy && + a.DetachOnToward == b.DetachOnToward && + (a.HasCrossThreshold ? + b.HasCrossThreshold && quantity_measure_equals(a.CrossThreshold, b.CrossThreshold) : + !b.HasCrossThreshold) && + (a.HasChild ? + b.HasChild && equals(a.Child, b.Child) : + !b.HasChild); + + public static bool trigger_equals(TriggerOrderDefinitionImmutable a, TriggerOrderDefinitionImmutable b) { + // TriggerAction + if (a.HasTriggerAction) { + if (!b.HasTriggerAction || !trigger_action_equals(a.TriggerAction, b.TriggerAction)) + return false; + } else if (b.HasTriggerAction) + return false; + // ExitCondition + if (a.HasExitCondition) { + if (!b.HasExitCondition || !trigger_exit_condition_equals(a.ExitCondition, b.ExitCondition)) + return false; + } else if (b.HasExitCondition) + return false; + if (a.HasTriggerCondition) { + if (!b.HasTriggerCondition || !trigger_condition_equals(a.TriggerCondition, b.TriggerCondition)) + return false; + } else if (b.HasTriggerCondition) + return false; + return a.HasChild ? b.HasChild && equals(a.Child, b.Child) : !b.HasChild; + } + + public static bool trigger_action_equals(TriggerActionImmutable a, TriggerActionImmutable b) { + if (a.OrderpriceCase != b.OrderpriceCase) + return false; + if (a.HasPayup) { + if (!b.HasPayup || !trigger_payup_price_equals(a.Payup, b.Payup)) + return false; + } else if (b.HasPayup) { + return false; + } + if (!a.Price.Equals(b.Price)) + return false; + return true; + } + + public static bool trigger_condition_equals(TriggerConditionImmutable a, TriggerConditionImmutable b) { + if (a.TriggerCase != b.TriggerCase || a.PriceType != b.PriceType) + return false; + switch (a.TriggerCase) { + case TriggerCondition.TriggerOneofCase.AbsolutePriceTrigger: return absolute_price_trigger_equals(a.AbsolutePriceTrigger, b.AbsolutePriceTrigger); + case TriggerCondition.TriggerOneofCase.TrailingTrigger: return trailing_trigger_equals(a.TrailingTrigger, b.TrailingTrigger); + case TriggerCondition.TriggerOneofCase.None: return true; + default: throw ExceptionBuilder.Argument.unexpected_case(a.TriggerCase, "TriggerCase"); + } + } + + public static bool trailing_trigger_equals(bts.api.orderman.TrailingTriggerImmutable a, bts.api.orderman.TrailingTriggerImmutable b) => + a.TriggerType == b.TriggerType && a.NumberOfTicks == b.NumberOfTicks; + + public static bool trigger_payup_price_equals(TriggerPayupPriceImmutable a, TriggerPayupPriceImmutable b) => + a.PayupPriceType == b.PayupPriceType && a.PriceType == b.PriceType && a.PayupTicks == b.PayupTicks; + + public static bool trigger_exit_condition_equals(TriggerExitConditionImmutable a, TriggerExitConditionImmutable b) => + a.TimeoutEnabled == b.TimeoutEnabled && a.TimeoutSeconds == b.TimeoutSeconds; + + public static bool absolute_price_trigger_equals(bts.api.orderman.AbsolutePriceTriggerImmutable a, bts.api.orderman.AbsolutePriceTriggerImmutable b) => + a.HasTriggerQuantity ? b.HasTriggerQuantity && trigger_quantity_equals(a.TriggerQuantity, b.TriggerQuantity) : !b.HasTriggerQuantity; + + public static bool trigger_quantity_equals(TriggerQuantityImmutable a, TriggerQuantityImmutable b) => + a.HasQuantityMeasure ? b.HasQuantityMeasure && quantity_measure_equals(a.QuantityMeasure, b.QuantityMeasure) : !b.HasQuantityMeasure; + + public static bool quantity_measure_equals(QuantityMeasureImmutable a, QuantityMeasureImmutable b) { + if (a.QuantityCase != b.QuantityCase) + return false; + switch (a.QuantityCase) { + case QuantityMeasure.QuantityOneofCase.Absolute: return a.Absolute == b.Absolute; + case QuantityMeasure.QuantityOneofCase.Ratio: return a.Ratio.Equals(b.Ratio); + case QuantityMeasure.QuantityOneofCase.None: return true; + default: throw ExceptionBuilder.Argument.unexpected_case(a.QuantityCase, "QuantityCase"); + } + } + + class CustomDefinitionComparer : IEqualityComparer { + public bool Equals(CustomOrderDefinitionImmutable a, CustomOrderDefinitionImmutable b) { + if (a.CustomCase != b.CustomCase) return false; + switch (a.CustomCase) { + case CustomOrderDefinition.CustomOneofCase.Cover: return cover_equals(a.Cover, b.Cover); + case CustomOrderDefinition.CustomOneofCase.Oco: return oco_equals(a.Oco, b.Oco); + case CustomOrderDefinition.CustomOneofCase.Pricer: return pricer_equals(a.Pricer, b.Pricer); + case CustomOrderDefinition.CustomOneofCase.Iceberg: return iceberg_equals(a.Iceberg, b.Iceberg); + case CustomOrderDefinition.CustomOneofCase.Join: return join_equals(a.Join, b.Join); + case CustomOrderDefinition.CustomOneofCase.Lean: return lean_equals(a.Lean, b.Lean); + case CustomOrderDefinition.CustomOneofCase.Limit: return true; + case CustomOrderDefinition.CustomOneofCase.StopLimit: return stop_limit_equals(a.StopLimit, b.StopLimit); + case CustomOrderDefinition.CustomOneofCase.Tick: return tick_equals(a.Tick, b.Tick); + case CustomOrderDefinition.CustomOneofCase.Top: return top_equals(a.Top, b.Top); + case CustomOrderDefinition.CustomOneofCase.Trigger: return trigger_equals(a.Trigger, b.Trigger); + default: return a.Equals(b); + } + } + + public int GetHashCode(CustomOrderDefinitionImmutable def) { + int hash = (int)def.CustomCase; + int phase_mult = 1; + switch (def.CustomCase) { + case CustomOrderDefinition.CustomOneofCase.Cover: + add_component(def.Cover.HedgeTicks.GetHashCode()); + add_component(_get_hash(_get_cover_child(def.Cover))); + add_component(_get_hash(_get_cover_hedge(def.Cover))); + break; + case CustomOrderDefinition.CustomOneofCase.Oco: + add_component(def.Oco.OtherTicks); + add_component(_get_hash(_get_oco_child(def.Oco))); + add_component(_get_hash(_get_oco_stop(def.Oco))); + break; + case CustomOrderDefinition.CustomOneofCase.Pricer: + add_component(def.Pricer.PriceFactor.GetHashCode()); + add_component(_get_hash(_get_pricer_child(def.Pricer))); + break; + case CustomOrderDefinition.CustomOneofCase.Iceberg: + add_component(def.Iceberg.ShowQuantity.GetHashCode()); + add_component(_get_hash(_get_iceberg_child(def.Iceberg))); + break; + case CustomOrderDefinition.CustomOneofCase.Join: + add_component(def.Join.HasJoinThreshold ? def.Join.JoinThreshold.GetHashCode() : 0); + add_component(_get_hash(_get_join_child(def.Join))); + break; + case CustomOrderDefinition.CustomOneofCase.Lean: + add_component(def.Lean.HasCrossThreshold ? def.Lean.CrossThreshold.GetHashCode() : 0); + add_component(_get_hash(_get_lean_child(def.Lean))); + break; + case CustomOrderDefinition.CustomOneofCase.StopLimit: + add_component(def.StopLimit.StopPrice.GetHashCode()); + break; + case CustomOrderDefinition.CustomOneofCase.Tick: + var tick = def.Tick; + add_component(tick.CrossTicks.GetHashCode()); + add_component(tick.MaxChaseTicks.GetHashCode()); + add_component(tick.TickOffsetOnDeploy.GetHashCode()); + add_component(tick.DetachOnToward.GetHashCode()); + add_component(tick.HasCrossThreshold ? def.Tick.CrossThreshold.GetHashCode() : 0); + add_component(_get_hash(_get_tick_child(tick))); + break; + case CustomOrderDefinition.CustomOneofCase.Top: + add_component(def.Top.TicksOff.GetHashCode()); + add_component(def.Top.HasTopThreshold ? def.Top.TopThreshold.GetHashCode() : 0); + add_component(_get_top_child(def.Top).GetHashCode()); + break; + case CustomOrderDefinition.CustomOneofCase.Trigger: + var trigger = def.Trigger; + add_component(trigger.HasExitCondition ? def.Trigger.ExitCondition.GetHashCode() : 0); + add_component(trigger.HasTriggerAction ? def.Trigger.TriggerAction.GetHashCode() : 0); + add_component(trigger.HasTriggerCondition ? def.Trigger.TriggerCondition.GetHashCode() : 0); + add_component(_get_hash(_get_trigger_child(trigger))); + break; + case CustomOrderDefinition.CustomOneofCase.Offset: + add_component(def.Offset.TickOffsetOnDeploy.GetHashCode()); + add_component(_get_hash(_get_offset_child(def.Offset))); + break; + } + return hash; + void add_component(int component_hash) => + _add_component(ref hash, ref phase_mult, component_hash); + } + + void _add_component(ref int hash, ref int phase_mult, int component_hash) => + hash += EqualityComparer.phase_hash(component_hash, phase_mult++, MathUtils.Primes.P_1087); + + int _get_hash(CustomOrderDefinitionImmutable? a) => a.HasValue ? GetHashCode(a.Value) : 0; + } + + class CustomDefinitionStructureComparer : IEqualityComparer { + public bool Equals(CustomOrderDefinitionImmutable def1, CustomOrderDefinitionImmutable def2) => + enumerate_algo_structure(def1).SequenceEqual(enumerate_algo_structure(def2)); + + public int GetHashCode(CustomOrderDefinitionImmutable def) => + EqualityComparer.auto_phase(enumerate_algo_structure(def)); + } + } + + public static class CompareUtils { + public static readonly IEqualityComparer order_record_id_eq_comparer = + EqualityComparer.Create(o => o.Key); + + public static readonly IComparer bid_price_comparer = + Comparer.Create((x, y) => MathUtils.epsilon_equals(x, y) ? 0 : y.CompareTo(x)); + + public static readonly IComparer ask_price_comparer = + Comparer.Create((x, y) => MathUtils.epsilon_equals(x, y) ? 0 : x.CompareTo(y)); + } + + public static class Defaults { + // param types + public static QuantityMeasure QuantityMeasure => new QuantityMeasure { Absolute = 1 }; + // core data types + public static AlgoData AlgoData() => spark.AlgoData.from_custom_def(CustomOrderDefinitionImmutable()); + public static AlgoData AlgoData(CustomOrderDefinition.CustomOneofCase algo_type) => spark.AlgoData.from_custom_def(CustomOrderDefinitionImmutable(algo_type)); + + public static OrderDefinition OrderDefinition => new OrderDefinition { CustomDef = new CustomOrderDefinition() }; + public static OrderRecord OrderRecord => new OrderRecord { + Def = OrderDefinition, + State = new OrderState { + LastChange = Timestamp.FromDateTime(DateTime.UtcNow) + } + }; + + public static OrderRecordImmutable OrderRecordImmutable { get; } = new OrderRecordImmutable(OrderRecord); + + public static CustomOrderDefinition CustomOrderDefinition() => new CustomOrderDefinition { Limit = LimitOrderDefinition() }; + public static CustomOrderDefinition CustomOrderDefinition(CustomOrderDefinition.CustomOneofCase order_type) { + var rv = new CustomOrderDefinition(); + switch (order_type) { + case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Market: rv.Market = MarketOrderDefinition(); break; + case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Limit: rv.Limit = LimitOrderDefinition(); break; + case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Stop: rv.Stop = StopOrderDefinition(); break; + case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.StopLimit: rv.StopLimit = StopLimitOrderDefinition(); break; + case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Iceberg: rv.Iceberg = IcebergOrderDefinition(); break; + case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.GlbxIceberg: rv.GlbxIceberg = GLBXIcebergOrderDefinition(); break; + case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.TimeBox: rv.TimeBox = TimeBoxOrderDefinition(); break; + case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Tick: rv.Tick = TickOrderDefinition(); break; + case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Lean: rv.Lean = LeanOrderDefinition(); break; + case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Join: rv.Join = JoinOrderDefinition(); break; + case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Top: rv.Top = TopOrderDefinition(); break; + case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Cover: rv.Cover = CoverOrderDefinition(); break; + case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Oco: rv.Oco = OCOOrderDefinition(); break; + case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Pricer: rv.Pricer = PricerOrderDefinition(); break; + case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Offset: rv.Offset = OffsetOrderDefinition(); break; + case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Trigger: rv.Trigger = TriggerOrderDefinition(); break; + case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Spreader: rv.Spreader = SpreaderOrderDefinition(); break; + case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Dynamic: rv.Dynamic = DynamicOrderDefinition(); break; + default: + setup_generic_custom_order(rv, order_type); + break; + } + return rv; + } + + public static CustomOrderDefinitionImmutable CustomOrderDefinitionImmutable() => new CustomOrderDefinitionImmutable(CustomOrderDefinition()); + public static CustomOrderDefinitionImmutable CustomOrderDefinitionImmutable(CustomOrderDefinition.CustomOneofCase order_type) => new CustomOrderDefinitionImmutable(CustomOrderDefinition(order_type)); + + public static MarketOrderDefinition MarketOrderDefinition() => new MarketOrderDefinition { }; + public static LimitOrderDefinition LimitOrderDefinition() => new LimitOrderDefinition { }; + public static StopOrderDefinition StopOrderDefinition() => new StopOrderDefinition { }; + public static StopLimitOrderDefinition StopLimitOrderDefinition() => new StopLimitOrderDefinition { }; + public static GLBXIcebergOrderDefinition GLBXIcebergOrderDefinition() => new GLBXIcebergOrderDefinition { MaxShowQuantity = 1 }; + public static IcebergOrderDefinition IcebergOrderDefinition() => new IcebergOrderDefinition { Child = CustomOrderDefinition(), ShowQuantity = 1 }; + public static TimeBoxOrderDefinition TimeBoxOrderDefinition() => new TimeBoxOrderDefinition { Child = CustomOrderDefinition(), Start = Timestamp.FromDateTime(DateTime.UtcNow), Stop = Timestamp.FromDateTime(DateTime.UtcNow) }; + public static TickOrderDefinition TickOrderDefinition() => new TickOrderDefinition { Child = CustomOrderDefinition(), CrossThreshold = QuantityMeasure }; + public static LeanOrderDefinition LeanOrderDefinition() => new LeanOrderDefinition { Child = CustomOrderDefinition(), CrossThreshold = QuantityMeasure, MaxChaseTicks = 2 }; + public static JoinOrderDefinition JoinOrderDefinition() => new JoinOrderDefinition { Child = CustomOrderDefinition(), JoinThreshold = QuantityMeasure }; + public static TopOrderDefinition TopOrderDefinition() => new TopOrderDefinition { Child = CustomOrderDefinition(), TopThreshold = QuantityMeasure }; + public static CoverOrderDefinition CoverOrderDefinition() => new CoverOrderDefinition { Child = CustomOrderDefinition(), Hedge = CustomOrderDefinition(), HedgeTicks = 1 }; + public static OCOOrderDefinition OCOOrderDefinition() => new OCOOrderDefinition { Child = CustomOrderDefinition(), Other = CustomOrderDefinition(), OtherSide = RelativeSide.Same }; + public static PricerOrderDefinition PricerOrderDefinition() => new PricerOrderDefinition { Child = CustomOrderDefinition() }; + public static OffsetOrderDefinition OffsetOrderDefinition() => new OffsetOrderDefinition { Child = CustomOrderDefinition(), }; + public static TriggerOrderDefinition TriggerOrderDefinition() => new TriggerOrderDefinition { Child = CustomOrderDefinition(), TriggerCondition = new TriggerCondition(), TriggerAction = new TriggerAction(), }; + public static DynamicOrderDefinition DynamicOrderDefinition() => new DynamicOrderDefinition(); + public static SpreaderOrderDefinition SpreaderOrderDefinition() => new SpreaderOrderDefinition { ExecutionStrategy = new ExecutionStrategy() }; + } + } +} diff --git a/src/lib/api/md/CboeMarketDataConfig.proto b/src/lib/api/md/CboeMarketDataConfig.proto index 81bc3887b..2cf87fa0b 100644 --- a/src/lib/api/md/CboeMarketDataConfig.proto +++ b/src/lib/api/md/CboeMarketDataConfig.proto @@ -1,6 +1,7 @@ syntax = "proto3"; import "lib/api/domain/SecurityCriteria.proto"; +import "lib/api/md/DatabentoMarketDataConfig.proto"; package bts.api.md; @@ -9,16 +10,7 @@ option csharp_namespace = "bts.api.md"; message CboeMarketDataConfig { uint32 unique_check_value = 1; - bool use_databento = 10; - bool read_from_file = 20; - //uint32 num_depth_levels = 1; - //uint32 depth_throttle_ms = 2; bts.api.domain.SecurityCriteria security_criteria = 3; - // Market data isn't subscribed for securities listed here (even if they are - // included by 'security_criteria'). There are some securities that don't - // fit into our system just yet, such as 'BTCBIDR', which trades in prices - // larger than our cpp 'domain::Price' class supports. - //repeated string excluded_securities = 4; - //string url_rest_base = 5; - //string url_ws_base = 6; + bool use_databento = 10; + DatabentoMarketDataConfig databento_settings = 20; } diff --git a/src/lib/api/md/DatabentoMarketDataConfig.proto b/src/lib/api/md/DatabentoMarketDataConfig.proto new file mode 100644 index 000000000..cea25526c --- /dev/null +++ b/src/lib/api/md/DatabentoMarketDataConfig.proto @@ -0,0 +1,17 @@ +syntax = "proto3"; + +package bts.api.md; + +option csharp_namespace = "bts.api.md"; +option cc_enable_arenas = true; + +message DatabentoMarketDataConfig { + uint32 unique_check_value = 1; + bool read_from_file = 20; + string contracts_file_name = 30; + string bbo_file_name = 40; + double replay_sleep_timer_sec = 50; + string key = 60; + string dataset = 70; + bool filter_securities_one_year= 80; +} diff --git a/src/lib/api/md/GlbxMarketDataConfig.proto b/src/lib/api/md/GlbxMarketDataConfig.proto index ee7b6ee98..486fd6cbc 100644 --- a/src/lib/api/md/GlbxMarketDataConfig.proto +++ b/src/lib/api/md/GlbxMarketDataConfig.proto @@ -1,7 +1,7 @@ syntax = "proto3"; import "lib/api/domain/SecurityCriteria.proto"; - +import "lib/api/md/DatabentoMarketDataConfig.proto"; package bts.api.md; option csharp_namespace = "bts.api.md"; @@ -9,9 +9,9 @@ option csharp_namespace = "bts.api.md"; message GlbxMarketDataConfig { uint32 unique_check_value = 1; - bool use_databento = 10; - bool read_from_file = 20; bts.api.domain.SecurityCriteria security_criteria = 3; + bool use_databento = 10; + DatabentoMarketDataConfig databento_settings =20; //uint32 num_depth_levels = 1; //uint32 depth_throttle_ms = 2; // Market data isn't subscribed for securities listed here (even if they are diff --git a/src/lib/api/md/TaifexMarketDataConfig.proto b/src/lib/api/md/TaifexMarketDataConfig.proto index 519777008..d31a3d4ac 100644 --- a/src/lib/api/md/TaifexMarketDataConfig.proto +++ b/src/lib/api/md/TaifexMarketDataConfig.proto @@ -5,19 +5,24 @@ import "lib/api/domain/SecurityCriteria.proto"; package bts.api.md; option csharp_namespace = "bts.api.md"; - +message TaifexConnectionDetails{ + string live_data_ip = 30; + string reference_data_ip = 31; + string refresh_data_ip = 32; + string live_data_port = 40; + string reference_data_port = 41; + string refresh_data_port = 42; + string interface_ip = 50; +} message TaifexMarketDataConfig { uint32 unique_check_value = 1; bool read_from_file = 20; - //uint32 num_depth_levels = 1; - //uint32 depth_throttle_ms = 2; + string ref_data_file_name = 21; + string realtime_data_file_name = 22; + TaifexConnectionDetails regular_hours_connection_details = 30; + TaifexConnectionDetails after_hours_connection_details = 31; + bool use_after_hours = 40; bts.api.domain.SecurityCriteria security_criteria = 3; - // Market data isn't subscribed for securities listed here (even if they are - // included by 'security_criteria'). There are some securities that don't - // fit into our system just yet, such as 'BTCBIDR', which trades in prices - // larger than our cpp 'domain::Price' class supports. - //repeated string excluded_securities = 4; - //string url_rest_base = 5; - //string url_ws_base = 6; + } diff --git a/src/lib/cmake/GetLinuxServerLinkLibraries.cmake b/src/lib/cmake/GetLinuxServerLinkLibraries.cmake index 84fee5adf..a2dc6991d 100644 --- a/src/lib/cmake/GetLinuxServerLinkLibraries.cmake +++ b/src/lib/cmake/GetLinuxServerLinkLibraries.cmake @@ -25,6 +25,7 @@ function(get_link_libraries dest) Packet++ Common++ ssh2 + onixs-fix-engine -lrt -ldl -lpcap diff --git a/src/lib/config/profiles/default/jetfix.conf b/src/lib/config/profiles/default/jetfix.conf index aad2eec51..3e007a57a 100644 --- a/src/lib/config/profiles/default/jetfix.conf +++ b/src/lib/config/profiles/default/jetfix.conf @@ -4028,5 +4028,17 @@ JetFIX { name: "deribit_1" venue: VENUE_DERIBIT } + # CME EXECUTION NEEDS TO BE UPDATED, probably below + # connection { + # name: "onixs_sim" + # venue: VENUE_GLBX + # } } -} \ No newline at end of file +} +# NotSimExecution { +# value { +# entries { +# venue: VENUE_CBOE +# } +# } +# } \ No newline at end of file diff --git a/src/lib/config/protos/jetfix.proto b/src/lib/config/protos/jetfix.proto index 0a8ba56e9..46e8083da 100644 --- a/src/lib/config/protos/jetfix.proto +++ b/src/lib/config/protos/jetfix.proto @@ -105,10 +105,10 @@ message CMECannedSecureLogon { } -message SimExecution{ - message SimExecutionEntry { +message NotSimExecution{ + message NotSimExecutionEntry { bts.api.Venue venue = 100; bool incorporate_crosses_into_book = 200; } - repeated SimExecutionEntry entries = 100; + repeated NotSimExecutionEntry entries = 100; } diff --git a/src/lib/md/GeneralMarketDataListener.cpp b/src/lib/md/GeneralMarketDataListener.cpp index 3552f3b01..cccc71273 100644 --- a/src/lib/md/GeneralMarketDataListener.cpp +++ b/src/lib/md/GeneralMarketDataListener.cpp @@ -21,6 +21,7 @@ #include "lib/domain/TradeRecord.h" #include "lib/domain_model/Security.pb.h" #include "lib/logging/logging.h" +#include "lib/md/IMarketDataListener.h" #include "lib/md/IntPrice.h" #include "lib/md/MDProducer.h" #include "lib/md/MDProducerHandle.h" @@ -73,6 +74,98 @@ struct CCSecSearchResult { bool exists_now; }; +struct IncrementalBookData { + std::map book_map; + + bool update_incremental(const IMarketDataListener::BookOp & op) { + // TODO: Arham/Adeel, implement this + // retreive the Book from the map and udpate it. domain::Book has a lot of functions + // already, add more if you want to. but the idea is to update the book in place, ie + // if a level needs to be added push the lower levels out + + //getting book + domain::Book* book = get_book(op.id); + if(book == nullptr) + return false; + + //checking if side is Buy or Sell + auto& book_side = (op.side == api::Side::SIDE_BUY) ? book->bids() : book->asks(); + + size_t insert_level = 0; + bool level_found = false; + + if(op.side == api::Side::SIDE_BUY) + { + //going through book + while(insert_level < book_side.size()) + { + //op.price_size? + if(op.price == book_side[insert_level].price) + { + level_found = true; + break; + } + //if its not equal and its not larger, we go to next level + if(op.price > book_side[insert_level].price) + { + break; + } + //moving to next level + insert_level++; + } + }else{ + while(insert_level < book_side.size()) + { + if(op.price == book_side[insert_level].price) + { + level_found = true; + break; + } + if (op.price < book_side[insert_level].price) + { + break; + } + insert_level++; + } + } + + //inserting and pushing levels + if(!level_found) + { + // shift all lower levels down + for (size_t i = book_side.size() - 1; i > insert_level; i--) + { + book_side[i] = book_side[i - 1]; + } + // insert the new level with its price + //book_side[insert_level].price.to_double() = op.price_size.price(); + + } + book_side[insert_level].price =op.price; + book_side[insert_level].direct_quantity =op.quantity; + return true; + } + domain::Book const *get_const_book(domain::SecurityID id) const { + auto it = book_map.find(id); + if (it == book_map.end()) { + return nullptr; + } + return &(it->second); + } + domain::Book *get_book(domain::SecurityID id) { + auto it = book_map.find(id); + if (it == book_map.end()) { + return nullptr; + } + return &(it->second); + } + + void overwrite_book(const domain::Book &book) { + domain::SecurityID id = book.security_id(); + book_map[id] = book; + } +}; + struct GeneralMarketDataListener::PImpl { // if this is set to true, then the security key passed on in the // on_securities function is used. If this is not set to true, then a new key @@ -94,6 +187,7 @@ struct GeneralMarketDataListener::PImpl { std::unordered_map cc_sec_id_map = {}; MDArray bids = {}; MDArray asks = {}; + IncrementalBookData inc_book_data = {}; explicit PImpl( GeneralSecurityIndex &index, MDProducer &md_producer, @@ -234,7 +328,8 @@ void GeneralMarketDataListener::on_security_statistics( auto handle = _find_handle(sec_stats.security_id); bts_assert_msgf( handle != nullptr, - "GeneralMarketDataListener::on_security_statistics null handle. id: {}", + "GeneralMarketDataListener::on_security_statistics null handle. id: " + "{}", sec_stats.security_id); auto now = utils::TimeStamp::now(); bts::datetime::Date date_temp = {}; @@ -246,31 +341,23 @@ void GeneralMarketDataListener::on_security_statistics( handle->handle.set_total_volume(sec_stats.volume.value()); } -void GeneralMarketDataListener::on_book(const bts::domain::Book &book, std::optional time) { +void GeneralMarketDataListener::on_book( + const bts::domain::Book &book, std::optional time) { LOG(md, Diag, "GeneralMarketDataListener::on_book sec_id: {}", book.security_id()); - if(!time.has_value()){ - time = utils::TimeStamp::now(); - } - me->n_bk_updates++; - auto handle = _find_handle(book.security_id()); - if (handle == nullptr) { - LOG(md, Error, - "GeneralMarketDataListener::on_book, could not find sec_id: {}", - book.security_id()); + // in case this is called externally in conjunction iwth inc book udpates + me->inc_book_data.overwrite_book(book); + _on_book(book, time); +} + +void GeneralMarketDataListener::on_book_increment( + const IMarketDataListener::BookOp &book_op) { + if(!me->inc_book_data.update_incremental(book_op)){ return; } - copy_books(book, me->bids, bts::domain::Side::Value::Buy); - copy_books(book, me->asks, bts::domain::Side::Value::Sell); - _possibly_match_with_sim_orders( - bts::md::SecurityKey(book.security_id().value())); - LOG(md, Diag, - "GeneralMarketDataListener::on_book post id: {} bid: {}/{}/{} ask: " - "{}/{}/{}", - handle->id, me->bids.at(0).price(), me->bids.at(0).direct_size(), - me->bids.at(0).size(), me->asks.at(0).price(), - me->asks.at(0).direct_size(), me->asks.at(0).size()); - handle->handle.update_direct(time.value(), me->bids, me->asks); + domain::Book const *book_ptr = me->inc_book_data.get_const_book(book_op.id); + bts_assert(book_ptr != nullptr); + _on_book(*book_ptr); } void GeneralMarketDataListener::on_trades( @@ -351,7 +438,8 @@ void GeneralMarketDataListener::_add_future(const bts::domain::Security &sec) { const auto &f_sec = std::get(sec.security); get_date_from_epoch_nanos(f_sec.expiration.nanos(), year, month, day); LOG(md, Info, - "GeneralMarketDataListener::_add_future nanos: {} yy: {} mm: {} dd: {}", + "GeneralMarketDataListener::_add_future nanos: {} yy: {} mm: {} dd: " + "{}", f_sec.expiration.nanos(), year, month, day); ff_sec.expiration_year = year; ff_sec.expiration_month = month; @@ -394,7 +482,8 @@ void GeneralMarketDataListener::_add_spread(const bts::domain::Security &sec) { auto it = me->cc_sec_id_map.find(l.security_id); if (it == me->cc_sec_id_map.end()) { LOG(md, Error, - "GeneralMarketDataListener::_add_spread, could not resolve leg. " + "GeneralMarketDataListener::_add_spread, could not resolve " + "leg. " "id: {}; leg_id: {}", sec.id(), l.security_id); return; @@ -431,7 +520,8 @@ void GeneralMarketDataListener::_commit_security(const FixedSecurity &sec) { // Add it to the index so it can receive messages auto kp = me->index.add_security(sec.numeric_id, handle); LOG(md, Info, - "GeneralMarketDataListener::_add_security_to_shm added sec: {} id: {} " + "GeneralMarketDataListener::_add_security_to_shm added sec: {} id: " + "{} " "num_id: {} n_secs: {}", std::string(handle.security().security_desc()), kp->id, handle.security().numeric_id, me->index.n_secs()); @@ -468,5 +558,33 @@ void GeneralMarketDataListener::_possibly_match_with_sim_orders( } } +void GeneralMarketDataListener::_on_book( + const domain::Book &book, std::optional time) { + LOG(md, Diag, "GeneralMarketDataListener::_on_book sec_id: {}", + book.security_id()); + if (!time.has_value()) { + time = utils::TimeStamp::now(); + } + me->n_bk_updates++; + auto handle = _find_handle(book.security_id()); + if (handle == nullptr) { + LOG(md, Error, + "GeneralMarketDataListener::_on_book, could not find sec_id: {}", + book.security_id()); + return; + } + copy_books(book, me->bids, bts::domain::Side::Value::Buy); + copy_books(book, me->asks, bts::domain::Side::Value::Sell); + _possibly_match_with_sim_orders( + bts::md::SecurityKey(book.security_id().value())); + LOG(md, Diag, + "GeneralMarketDataListener::_on_book post id: {} bid: {}/{}/{} ask: " + "{}/{}/{}", + handle->id, me->bids.at(0).price(), me->bids.at(0).direct_size(), + me->bids.at(0).size(), me->asks.at(0).price(), + me->asks.at(0).direct_size(), me->asks.at(0).size()); + handle->handle.update_direct(time.value(), me->bids, me->asks); +} + } // namespace bts::md //#endif diff --git a/src/lib/md/GeneralMarketDataListener.h b/src/lib/md/GeneralMarketDataListener.h index fce00dd67..d14af272e 100644 --- a/src/lib/md/GeneralMarketDataListener.h +++ b/src/lib/md/GeneralMarketDataListener.h @@ -23,7 +23,10 @@ class GeneralMarketDataListener : public IMarketDataListener { void on_security_state(const domain::SecurityState &security_state) override; void on_security_statistics( const domain::SecurityMarketDataStatistics &security_stats) override; - void on_book(const domain::Book &book, std::optional time = std::nullopt) override; + void on_book( + const domain::Book &book, + std::optional time = std::nullopt) override; + void on_book_increment(const BookOp &) override; void on_trades( const std::vector &trades) override; void on_rfqs(const std::vector &rfqs) override; @@ -49,5 +52,8 @@ class GeneralMarketDataListener : public IMarketDataListener { FixedSecurity &to) const; uint64_t _generate_security_key(const bts::domain::Security &sec); void _possibly_match_with_sim_orders(bts::md::SecurityKey key); + void _on_book( + const domain::Book &book, + std::optional time = std::nullopt); }; } // namespace bts::md diff --git a/src/lib/md/IMarketDataListener.h b/src/lib/md/IMarketDataListener.h index 053cdf1d1..342c5eaef 100644 --- a/src/lib/md/IMarketDataListener.h +++ b/src/lib/md/IMarketDataListener.h @@ -1,6 +1,7 @@ #pragma once #include "lib/api/services/OrderService.pb.h" #include "lib/domain/Book.h" +#include "lib/domain/SecurityID.h" #include "lib/md/PriceSize.h" #include @@ -19,12 +20,15 @@ class MarketDataError; // The is the interface that registers itself to IMarketDataGateway and receives // all market data via callbacks. These callbacks are always on the same thread. class IMarketDataListener { - enum BookOpType { Add = 0, REMOVE, MODIFY }; + public: + enum BookOpType { Add = 0, MODIFY, REMOVE }; struct BookOp { + domain::SecurityID id; bts::api::Side side; BookOpType op_type; // for op == REMOVE size in price_size is no-op - PriceSize price_size; + domain::Price price; + domain::Quantity quantity; }; public: @@ -38,8 +42,10 @@ class IMarketDataListener { const domain::SecurityState &security_state) = 0; virtual void on_security_statistics( const domain::SecurityMarketDataStatistics &security_stats) = 0; - virtual void on_book(const domain::Book &book, std::optional time = std::nullopt) = 0; - virtual void on_book_increment(const BookOp &) {} + virtual void on_book( + const domain::Book &book, + std::optional time = std::nullopt) = 0; + virtual void on_book_increment(const IMarketDataListener::BookOp &) {} virtual void on_trades( const std::vector &trades) = 0; virtual void on_rfqs(const std::vector &rfqs) = 0; diff --git a/src/lib/orderman/gateways/sim/SimExecutionGatewayFactory.cpp b/src/lib/orderman/gateways/sim/SimExecutionGatewayFactory.cpp index 0e90fb0bf..2342f959a 100644 --- a/src/lib/orderman/gateways/sim/SimExecutionGatewayFactory.cpp +++ b/src/lib/orderman/gateways/sim/SimExecutionGatewayFactory.cpp @@ -61,15 +61,14 @@ SimExecutionGatewayFactory *SimExecutionGatewayFactory::get() { } bool SimExecutionGatewayFactory::is_sim_execution_on(api::Venue venue) { - // TODO: Arham, fix this ! - return true; - const auto &sim_exec = config::get(); - for (const auto &e : sim_exec.entries()) { + // return true; + const auto ¬_sim_exec = config::get(); + for (const auto &e : not_sim_exec.entries()) { if (e.venue() == venue) { - return true; + return false; } } - return false; + return true; } } // namespace bts::orderman \ No newline at end of file diff --git a/src/server/sparkd/md/MarketDataGateway.cpp b/src/server/sparkd/md/MarketDataGateway.cpp index 5ce6c87f1..48c6bea01 100644 --- a/src/server/sparkd/md/MarketDataGateway.cpp +++ b/src/server/sparkd/md/MarketDataGateway.cpp @@ -35,7 +35,7 @@ #include "server/sparkd/md/okx/OkxSubscription.h" #include "server/sparkd/md/platforms/mdp3_onixs/MDP3Main.h" #include "server/sparkd/md/recording/MDReplayer.h" -#include "server/sparkd/md/taifex/TaifexDataHandler.h" +#include "server/sparkd/md/taifex/TaifexDataGateway.h" #include #include @@ -43,6 +43,7 @@ #include #include #include +#include #include #include @@ -117,10 +118,6 @@ struct MarketDataGateway::PImpl { std::vector> replays = {}; // we create these and pass them to the cc md sources std::vector> venue_listeners = {}; - - void start_glbx(); - void start_cboe(); - void start_taifex(); }; MarketDataGateway::MarketDataGateway() @@ -142,9 +139,9 @@ void MarketDataGateway::run() { bts_assert(me_->md_config.emumba_deribit().size() == 1); _start_emumba_deribit(me_->md_config.emumba_deribit().at(0)); } - me_->start_glbx(); - me_->start_taifex(); - me_->start_cboe(); + start_glbx(me_->md_config); + start_taifex(me_->md_config); + start_cboe(me_->md_config); _start_replays(me_->md_config); while (true) { std::this_thread::sleep_for(std::chrono::seconds(1)); @@ -247,14 +244,17 @@ void MarketDataGateway::unsubscribe(MarketDataListenerID id) { } /// glbx ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// -void MarketDataGateway::PImpl::start_glbx(){ - for (const auto &glbx : md_config.glbx()) { +void MarketDataGateway::start_glbx(const bts::api::md::MarketDataConfig &cfg){ + for (const auto &glbx : cfg.glbx()) { if(glbx.use_databento()){ - auto p = venue_listeners.emplace_back( + auto p = me_->venue_listeners.emplace_back( std::make_shared(bts::api::VENUE_GLBX)); std::string tid_name = "glbx"; bts::threading::make_thread(tid_name, [&]() { - bts::md::glbx::GlbxMarketDatahandler::run(glbx.read_from_file(), p->listener,sec_id_store,api::domain::VENUE_GLBX); + api::md::glbx::GlbxMarketDatahandler::run( + p->listener, + me_->sec_id_store, + glbx); }).detach(); } else{ @@ -372,31 +372,36 @@ void MarketDataGateway::_start_replays( os::get_thread_id(), os::get_thread_name()); } -void MarketDataGateway::PImpl::start_taifex() { +void MarketDataGateway::start_taifex(const bts::api::md::MarketDataConfig &cfg) { // taifex - for (const auto &taifex : md_config.taifex()) { - auto p = venue_listeners.emplace_back( + int counter = 0; + for (const auto &taifex : cfg.taifex()) { + counter++; + auto p = me_->venue_listeners.emplace_back( std::make_shared(bts::api::VENUE_TAIFEX)); - std::string tid_name = "taifex"; + std::string tid_name = "taifex" +std::to_string(counter); bts::threading::make_thread(tid_name, [&]() { - bts::md::taifex::TaifexDatahandler::run( - taifex.read_from_file(), p->listener, sec_id_store); + bts::md::taifex::TaifexDataGateway::run( + taifex, p->listener, me_->sec_id_store); }).detach(); } } -void MarketDataGateway::PImpl::start_cboe(){ +void MarketDataGateway::start_cboe(const bts::api::md::MarketDataConfig &cfg){ // cboe - for (const auto &cboe : md_config.cboe()) { - auto p = venue_listeners.emplace_back( - std::make_shared(bts::api::VENUE_CBOE)); - std::string tid_name = "CBOE"; - bts::threading::make_thread(tid_name, [&]() { - bts::md::cboe::CboeMarketDatahandler::run(cboe.read_from_file(), p->listener,sec_id_store,api::domain::VENUE_CBOE); - }).detach(); - - UNUSED(cboe); - } + for (const api::md::CboeMarketDataConfig &cboe : cfg.cboe()) { + auto p = me_->venue_listeners.emplace_back( + std::make_shared(bts::api::VENUE_CBOE)); + std::string tid_name = "CBOE"; + bts::threading::make_thread(tid_name, [&]() { + api::md::cboe::CboeMarketDatahandler::run( + p->listener, + me_->sec_id_store, + cboe); + }).detach(); + + UNUSED(cboe); + } } diff --git a/src/server/sparkd/md/MarketDataGateway.h b/src/server/sparkd/md/MarketDataGateway.h index 410c87f51..22a88d1c6 100644 --- a/src/server/sparkd/md/MarketDataGateway.h +++ b/src/server/sparkd/md/MarketDataGateway.h @@ -36,6 +36,9 @@ class MarketDataGateway { static void _start_onix_glbx( bts::api::md::GlbxMarketDataConfig cfg); void _start_replays(const bts::api::md::MarketDataConfig &cfg); + void start_glbx(const bts::api::md::MarketDataConfig &cfg); + void start_cboe(const bts::api::md::MarketDataConfig &cfg); + void start_taifex(const bts::api::md::MarketDataConfig &cfg); }; } // namespace bts::md diff --git a/src/server/sparkd/md/cboe/CboeMarketDataHandler.cpp b/src/server/sparkd/md/cboe/CboeMarketDataHandler.cpp index a7c60cb5c..ee818d5a0 100644 --- a/src/server/sparkd/md/cboe/CboeMarketDataHandler.cpp +++ b/src/server/sparkd/md/cboe/CboeMarketDataHandler.cpp @@ -2,25 +2,35 @@ #include "lib/api/domain/Venue.pb.h" #include "lib/config/config.h" #include "lib/config/protos/system_config.pb.h" +#include "lib/utils/bts_assert.h" #include "server/sparkd/md/databento/DatabentoDataHandler.h" #include +#include #include #include #include #include #include -namespace bts::md::cboe { +namespace bts::api::md::cboe { void CboeMarketDatahandler::run( - bool use_file, - std::shared_ptr listner, - std::shared_ptr sec_id_store, - bts::api::domain::Venue venue) { - std::string contratcs_file_name = "/opra-pillar-20240815.definition.dbn.zst"; - std::string bbo_file_name = "/opra-pillar-20240815.mbp-1.dbn.zst"; - std::string base_path = - config::get().data_path(); - DatabentoHandler::DatabentoDatahandler::run(use_file, listner,sec_id_store,venue,base_path + contratcs_file_name,base_path + bbo_file_name); + std::shared_ptr<::bts::md::IMarketDataListener> listner, + std::shared_ptr sec_id_store, + const CboeMarketDataConfig &config) { + bts_assert_msg(config.use_databento(), "CboeMarketDatahandler only supports databento"); + std::string base_path = + config::get().data_path(); + bts_assert(config.has_databento_settings()); + bts::md::DatabentoHandler::DatabentoDatahandler::run( + config.databento_settings().read_from_file(), + listner, + sec_id_store, + domain::VENUE_CBOE, + base_path + config.databento_settings().contracts_file_name(), + base_path + config.databento_settings().bbo_file_name(), + config.databento_settings().key(), + config.databento_settings().dataset(), + config.databento_settings().filter_securities_one_year()); } } // namespace bts::md::cboe \ No newline at end of file diff --git a/src/server/sparkd/md/cboe/CboeMarketDataHandler.h b/src/server/sparkd/md/cboe/CboeMarketDataHandler.h index 1774e8ed0..f9db8becc 100644 --- a/src/server/sparkd/md/cboe/CboeMarketDataHandler.h +++ b/src/server/sparkd/md/cboe/CboeMarketDataHandler.h @@ -1,12 +1,12 @@ #pragma once +#include "lib/api/md/CboeMarketDataConfig.pb.h" #include "lib/md/IMarketDataListener.h" #include "lib/persistence/IDGenerator.h" -namespace bts::md::cboe { +namespace bts::api::md::cboe { class CboeMarketDatahandler { public: - static void run(bool use_file, - std::shared_ptr listner, + static void run(std::shared_ptr<::bts::md::IMarketDataListener> listner, std::shared_ptr sec_id_store, - bts::api::domain::Venue venue); + const CboeMarketDataConfig &config); }; } // namespace bts::md::cboe \ No newline at end of file diff --git a/src/server/sparkd/md/databento/DatabentoDataHanlder.cpp b/src/server/sparkd/md/databento/DatabentoDataHandler.cpp similarity index 53% rename from src/server/sparkd/md/databento/DatabentoDataHanlder.cpp rename to src/server/sparkd/md/databento/DatabentoDataHandler.cpp index 98d493d5a..a546c4a03 100644 --- a/src/server/sparkd/md/databento/DatabentoDataHanlder.cpp +++ b/src/server/sparkd/md/databento/DatabentoDataHandler.cpp @@ -1,5 +1,9 @@ #include "DatabentoDataHandler.h" #include "databento/datetime.hpp" +#include "databento/enums.hpp" +#include "databento/exceptions.hpp" +#include "databento/live_blocking.hpp" +#include "databento/log.hpp" #include "databento/timeseries.hpp" #include "lib/api/domain/Venue.pb.h" #include "lib/config/config.h" @@ -8,6 +12,8 @@ #include "lib/domain/Quantity.h" #include "lib/domain/Security.h" #include "lib/domain/SecurityID.h" +#include "lib/domain_model/Security.pb.h" +#include "lib/logging/logging.h" #include "lib/utils/TimeStamp.h" #include "lib/utils/bts_assert.h" #include "lib/utils/bts_chrono.h" @@ -16,6 +22,7 @@ #include #include #include +#include #include #include @@ -39,30 +46,47 @@ void DatabentoDatahandler::run( bts::api::domain::Venue venue, const std::string &securities_path, const std::string &books_path, + const std::string &key, + const std::string &dataset, + const bool filter_securities, const std::chrono::duration sleep_duration) { - auto client = databento::HistoricalBuilder{} - .SetKey("db-Q4eCbTQfrAHaG6sAcuFUYB9YqkF6j") - .Build(); + auto sleep_duration_updated = sleep_duration; + if (!use_file) { + sleep_duration_updated = std::chrono::duration::zero(); // Set to zero for live data + } auto process_security = [&](const databento::Record &record) { const auto &msg = record.Get(); std::string id = remove_spaces(msg.RawSymbol()); std::string symbol; - + switch (venue) { - case api::domain::Venue::VENUE_CBOE: - symbol = id.substr(0, 3); + case api::domain::Venue::VENUE_CBOE:{ + symbol = remove_spaces(std::string(msg.underlying.data(),msg.underlying.size())); break; + } case api::domain::Venue::VENUE_GLBX: if (id.length() > 5) return databento::KeepGoing::Continue; symbol = id.substr(0, 2); + // sec.security_common.cpp = msg.unit_of_measure_qty; + break; default: bts_assert_msg(false, "Exchange not supported on databento"); return databento::KeepGoing::Stop; } + if(filter_securities){ + const auto exp_nanos = msg.expiration; + std::string exp_string = databento::ToIso8601(exp_nanos); + const auto expiration_time = bts::core::TimeStamp::from_iso_string(exp_string); + if(expiration_time.seconds() < expiration_time.now().seconds() || expiration_time.seconds() > (expiration_time.now().seconds() + 60*60*24*365)){ + return databento::KeepGoing::Continue; + } + } + + bts::domain::SecurityID sec_id{sec_id_store->get_or_add( venue, std::to_string(msg.hd.instrument_id))}; bts::domain::Security sec; @@ -71,13 +95,14 @@ void DatabentoDatahandler::run( sec.security_common.id = sec_id; sec.security_common.exchange_sec_id = msg.hd.instrument_id; sec.security_common.desc = msg.RawSymbol(); - sec.security_common.symbol = symbol; - sec.security_common.asset = symbol; - sec.security_common.group = symbol; + sec.security_common.symbol = msg.Asset(); + sec.security_common.asset = msg.Asset(); + sec.security_common.group = msg.Group(); sec.security_common.min_price_increment = 0.01; sec.security_common.min_quantity = 0.01; sec.security_common.min_quantity_increment = 0.01; sec.security_common.currency = {msg.currency.data(), msg.currency.size()}; + // sec.security_common.cpp = msg.hd. const std::string_view sec_type = {msg.security_type.data(), msg.security_type.size()}; const auto exp_nanos = msg.expiration; @@ -85,8 +110,15 @@ void DatabentoDatahandler::run( const auto expiration_time = bts::core::TimeStamp::from_iso_string(exp_string); if (sec_type.find("OPT") != std::string::npos) { + auto call_put = api::domain::CallPut::PUT; + if(msg.instrument_class == 'C' ){ + call_put=api::domain::CallPut::CALL; + } + else{ + bts_assert(msg.instrument_class == 'P'); + } sec.security.emplace( - expiration_time, bts::domain::Price::from_double(msg.strike_price)); + expiration_time, bts::domain::Price(msg.strike_price, -9),call_put); } else if (sec_type.find("FUT") != std::string::npos) { sec.security.emplace(expiration_time); } else { @@ -105,7 +137,7 @@ void DatabentoDatahandler::run( if (!sec_id_opt.has_value()) return databento::KeepGoing::Continue; - sleep_for(sleep_duration); + sleep_for(sleep_duration_updated); bts::domain::SecurityID sec_id = bts::domain::SecurityID(sec_id_opt.value()); domain::Book book; book.set_security_id(sec_id); @@ -126,15 +158,81 @@ void DatabentoDatahandler::run( utils::TimeStamp{datetime::ptime_to_timestamp(recv_time.to_ptime())}); return databento::KeepGoing::Continue; }; - if (use_file) { - std::string base_path = - config::get().data_path(); + auto client = databento::HistoricalBuilder{} + .SetKey(key) + .Build(); databento::DbnFileStore dbn_file_store(securities_path); dbn_file_store.Replay(process_security); - databento::DbnFileStore dbn_file_store2(books_path); dbn_file_store2.Replay(process_bbo); + }else { + bts_assert(dataset!=""); + // auto client = databento::LiveBuilder{} + // .SetKey(key) + // .SetDataset(dataset) + // .BuildThreaded(); + auto client = databento::LiveBlocking{ + databento::ILogReceiver::Default(), + key, + dataset, + true, + databento::VersionUpgradePolicy::Upgrade, + {} + }; + //hardcoding for now will update later + switch (venue) { + case api::domain::VENUE_CBOE: + client.Subscribe({"SPX.OPT","SPXW.OPT"}, databento::Schema::Definition, databento::SType::Parent,databento::UnixNanos{}); + client.Subscribe({"SPX.OPT","SPXW.OPT"}, databento::Schema::Mbp1, databento::SType::Parent); + break; + case api::domain::VENUE_GLBX: + client.Subscribe({"ES.FUT"}, databento::Schema::Definition, databento::SType::Parent); + client.Subscribe({"ES.FUT"}, databento::Schema::Mbp1, databento::SType::Parent); + break; + default: + bts_assert_msg(false, "ONLY GLBX AND CBOE SUPPORTED FOR NOW"); + + } + client.Start(); + while (true) { + try { + auto* record = client.NextRecord(std::chrono::seconds{500}); + if (record == nullptr) { + LOG(md, Error, "Timed out waiting for data"); + break; + } + if (auto* bbo = record->GetIf()) { + process_bbo(*record); + } + if (auto* def = record->GetIf()) { + process_security(*record); + } + } catch (const databento::TcpError& error) { + std::string err = error.what(); + LOG(md, Error, "Caught TCP error: {} \nAttempting reconnect\n",err); + client.Reconnect(); + } catch(const databento::DbnResponseError& err){ + std::string msg = err.Message(); + std::string what = err.what(); + LOG(md, Error, "Caught DbnResponseError what: {} ,msg:{} \nShutting down\n",msg, what); + client.Stop(); + // bts_assert(false); + } + catch(const databento::Exception& excp){ + std::string err = excp.Message(); + std::string err2 = excp.what(); + LOG(md, Error, "Caught unknown dadtabento::exception what: {}, msg: {} \nShutting down\n",err, err2); + client.Stop(); + // bts_assert(false); + }catch (const std::exception& exc) { + std::string err = exc.what(); + LOG(md, Error, "Caught unknown exception: {} \nShutting down\n",err); + client.Stop(); + // bts_assert(false); + } + + } } } diff --git a/src/server/sparkd/md/databento/DatabentoDataHandler.h b/src/server/sparkd/md/databento/DatabentoDataHandler.h index 1db36e81b..45abb5dc7 100644 --- a/src/server/sparkd/md/databento/DatabentoDataHandler.h +++ b/src/server/sparkd/md/databento/DatabentoDataHandler.h @@ -12,6 +12,9 @@ class DatabentoDatahandler { bts::api::domain::Venue venue, const std::string& securities_path, const std::string& books_path, + const std::string &dataset="", + const std::string& key = "db-Q4eCbTQfrAHaG6sAcuFUYB9YqkF6j", + const bool filter_securities=false, const std::chrono::duration sleep_duration = 0.04s); }; } // namespace bts::md::databento \ No newline at end of file diff --git a/src/server/sparkd/md/glbx/GlbxMarketDataHandler.cpp b/src/server/sparkd/md/glbx/GlbxMarketDataHandler.cpp index 35cb0f483..fb189b901 100644 --- a/src/server/sparkd/md/glbx/GlbxMarketDataHandler.cpp +++ b/src/server/sparkd/md/glbx/GlbxMarketDataHandler.cpp @@ -1,7 +1,9 @@ #include "GlbxMarketDataHandler.h" #include "lib/api/domain/Venue.pb.h" +#include "lib/api/md/GlbxMarketDataConfig.pb.h" #include "lib/config/config.h" #include "lib/config/protos/system_config.pb.h" +#include "lib/utils/bts_assert.h" #include "server/sparkd/md/databento/DatabentoDataHandler.h" #include #include @@ -9,18 +11,27 @@ #include #include #include -namespace bts::md::glbx { +namespace bts::api::md::glbx { void GlbxMarketDatahandler::run( - bool use_file, - std::shared_ptr listner, + std::shared_ptr<::bts::md::IMarketDataListener> listner, std::shared_ptr sec_id_store, - bts::api::domain::Venue venue) { - std::string contratcs_file_name = "/glbx-mdp3-20240815.definition.dbn.zst"; - std::string bbo_file_name = "/glbx-mdp3-20240815.mbp-1.dbn.zst"; - std::string base_path = - config::get().data_path(); - DatabentoHandler::DatabentoDatahandler::run(use_file, listner,sec_id_store,venue,base_path + contratcs_file_name,base_path + bbo_file_name); + const GlbxMarketDataConfig &config) { + bts_assert_msg(config.use_databento(), + "GlbxMarketDatahandler only supports databento"); + std::string base_path = + config::get().data_path(); + bts_assert(config.has_databento_settings()); + bts::md::DatabentoHandler::DatabentoDatahandler::run( + config.databento_settings().read_from_file(), + listner, + sec_id_store, + domain::VENUE_GLBX, + base_path + config.databento_settings().contracts_file_name(), + base_path + config.databento_settings().bbo_file_name(), + config.databento_settings().key(), + config.databento_settings().dataset(), + config.databento_settings().filter_securities_one_year()); } -} // namespace bts::md::glbx \ No newline at end of file +} // namespace bts::api::md::glbx \ No newline at end of file diff --git a/src/server/sparkd/md/glbx/GlbxMarketDataHandler.h b/src/server/sparkd/md/glbx/GlbxMarketDataHandler.h index 4a4b43989..7516dc69d 100644 --- a/src/server/sparkd/md/glbx/GlbxMarketDataHandler.h +++ b/src/server/sparkd/md/glbx/GlbxMarketDataHandler.h @@ -1,12 +1,13 @@ #pragma once +#include "lib/api/md/GlbxMarketDataConfig.pb.h" #include "lib/md/IMarketDataListener.h" #include "lib/persistence/IDGenerator.h" -namespace bts::md::glbx { +namespace bts::api::md::glbx { class GlbxMarketDatahandler { public: - static void run(bool use_file, - std::shared_ptr listner, + static void run( + std::shared_ptr<::bts::md::IMarketDataListener> listner, std::shared_ptr sec_id_store, - bts::api::domain::Venue venue); + const GlbxMarketDataConfig& config); }; } // namespace bts::md::glbx \ No newline at end of file diff --git a/src/server/sparkd/md/taifex/TaifexDataGateway.cpp b/src/server/sparkd/md/taifex/TaifexDataGateway.cpp new file mode 100644 index 000000000..f50fe7120 --- /dev/null +++ b/src/server/sparkd/md/taifex/TaifexDataGateway.cpp @@ -0,0 +1,811 @@ +#include "TaifexDataGateway.h" +#include "TaifexMessages.h" +#include "TaifexSecurityDetailsMapper.h" +#include "lib/api/domain/Venue.pb.h" +#include "lib/api/md/TaifexMarketDataConfig.pb.h" +#include "lib/config/config.h" +#include "lib/config/protos/system_config.pb.h" +#include "lib/core/TimeStamp.h" +#include "lib/domain/Price.h" +#include "lib/domain/Security.h" +#include "lib/domain/SecurityID.h" +#include "lib/domain/TradeRecord.h" +#include "lib/logging/logging.h" +#include "lib/md/IMarketDataListener.h" +#include "lib/persistence/IDGenerator.h" +#include "lib/utils/bts_assert.h" +#include "lib/utils/helper_macros.h" +#include "lib/utils/thread_manager.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +namespace bts::md::taifex { + +constexpr size_t FOOTER_SIZE = 3; +constexpr size_t HEADER_SIZE = 19; +constexpr size_t FEED_BUFFER_SIZE = 1024; +std::atomic_bool stop_refresh_thread = true; +std::atomic_bool stop_reference_thread = true; +std::atomic_bool stop_live_buffer_thread = true; + +enum class LIVE_DATA_STATES { + START = 0, + WAITING_FOR_REFRESH_DATA, + REFRESH_DATA_DONE, + WAITING_TO_SYNC_LIVE, + LIVE_RUNNING // add state to shift to after hours +}; +std::atomic state; + +std::string getIP(const std::string &ipType) { + std::string regular_referenceIP = "225.0.140.141"; + std::string regular_refreshIP = "225.0.140.147"; + std::string regular_realTimeIP = "225.0.140.140"; + + std::string afterHours_referenceIP = "225.10.140.141"; + std::string afterHours_refreshIP = "225.10.140.147"; + std::string afterHours_realTimeIP = "225.10.140.140"; + + // current time + std::time_t now = std::time(0); + std::tm *localTime = std::localtime(&now); + + // current hour and minute + int hour = localTime->tm_hour; + int minute = localTime->tm_min; + + // regular trading time 8:45 AM to 1:45 PM/ after-hours trading 3:00 PM to 5:00 AM + if ((hour == 8 && minute >= 45) || (hour > 8 && hour < 14) || + (hour == 14 && minute <= 45)) { + // Regular trading hours + if (ipType == "reference") + return regular_referenceIP; + if (ipType == "refresh") + return regular_refreshIP; + if (ipType == "realtime") + return regular_realTimeIP; + } else if ((hour == 15) || (hour > 15 && hour < 24) || (hour < 5)) { + // After-hours trading + if (ipType == "reference") + return afterHours_referenceIP; + if (ipType == "refresh") + return afterHours_refreshIP; + if (ipType == "realtime") + return afterHours_realTimeIP; + } + + // If an invalid ipType is passed, return an empty string or error message + return "Invalid IP type!"; +} + +void processI083Message( + TaifexMessages::I083Data &i083_message, + std::shared_ptr listener, + std::shared_ptr security_details) { + auto sec_id = security_details->get_sec_id( + TaifexUtils::remove_spaces(i083_message.prod_id)); + auto dec_loc = security_details->get_dec_loc( + TaifexUtils::remove_spaces(i083_message.prod_id)); + if (!sec_id.has_value() || !dec_loc.has_value()) { + return; + } + domain::Book book; + auto &bids = book.bids(); + auto &asks = book.asks(); + book.set_security_id(sec_id.value()); + + for (const auto &entry : i083_message.entries) { + bts::domain::Price price( + entry.price * + pow(10, + 9 - dec_loc + .value())); // Assuming the price needs to be adjusted by a factor of -2 + bts::domain::Quantity quantity(entry.quantity); + + // Process each MD_ENTRY + if (entry.md_entry_type == '0' || + entry.md_entry_type == 'E') { // Buy or derived buy + // Update the corresponding bid level + if (entry.level <= bids.size()) { + bids[entry.level - 1].price = price; + bids[entry.level - 1].total_quantity = quantity; + } + } else if ( + entry.md_entry_type == '1' || + entry.md_entry_type == 'F') { // Sell or derived sell + // Update the corresponding ask level + if (entry.level <= asks.size()) { + asks[entry.level - 1].price = price; + asks[entry.level - 1].total_quantity = quantity; + } + } + } + + std::string book_deets = + "Top bid price: " + std::to_string(bids[0].price.to_double()) + + " Top bid size: " + std::to_string(bids[0].total_quantity.value()) + + " Top ask price: " + std::to_string(asks[0].price.to_double()) + + " Top ask size: " + std::to_string(asks[0].total_quantity.value()) + + " Bid levels: " + std::to_string(bids.size()) + + " Ask levels: " + std::to_string(asks.size()); + + listener->on_book(book); +} + +void handleReferenceDataParsedMessage( + const std::vector &buffer, + size_t position, + const TaifexMessages::Header_Fields &Header, + std::shared_ptr listener, + std::shared_ptr sec_id_store, + std::shared_ptr security_details) { + + switch (Header.message_type.identifier) { + + case TaifexMessages::MessageIdentifier::I010: { + auto i010_message = TaifexMessages::I010Data( + buffer, position + HEADER_SIZE, Header.Body_Length + FOOTER_SIZE); + + const auto id = TaifexUtils::remove_spaces(i010_message.prod_id); + const auto symbol = id.substr(0, 2); + bts::domain::SecurityID sec_id{ + sec_id_store->get_or_add(api::domain::VENUE_TAIFEX, id)}; + security_details->add_i010_mapping( + id, sec_id, i010_message.decimal_locator); + + std::vector complete_security_list; + bts::domain::Security &sec = complete_security_list.emplace_back(); + sec.security_common.venue = bts::api::domain::VENUE_TAIFEX; + sec.security_common.id = sec_id; + sec.security_common.exchange_sec_id = id; // Need to fix this + sec.security_common.desc = id; + sec.security_common.symbol = symbol; + sec.security_common.asset = id; + sec.security_common.group = id; + sec.security_common.min_price_increment = + security_details->get_min_inc(id); + sec.security_common.min_quantity = security_details->get_min_inc(id); + sec.security_common.min_quantity_increment = + security_details->get_min_inc(id); + sec.security_common.currency = security_details->get_currency(id); + switch (i010_message.parsedProductInfo.productType) { + + case TaifexMessages::I010Data::ProductInfo::ProductType::FUTURES: { + auto &t = sec.security.emplace(); + auto toISODate = [](const std::string &date) { + return date.substr(0, 4) + "-" + date.substr(4, 2) + "-" + + date.substr(6, 2); + }; + t.expiration = bts::core::TimeStamp::from_iso_string( + toISODate(i010_message.end_date)); + + break; + } + + case TaifexMessages::I010Data::ProductInfo::ProductType::OPTIONS: { + auto &t = sec.security.emplace(); + std::tm tm = {}; + std::istringstream iss(i010_message.end_date); + iss >> std::get_time(&tm, "%Y%m%d"); + std::time_t time = std::mktime(&tm); + t.expiration = bts::core::TimeStamp(static_cast(time)); + t.strike = domain::Price::from_double( + i010_message.parsedProductInfo.strikePrice); + break; + } + } + + std::vector const_security_list; + for (const auto &security : complete_security_list) { + const_security_list.push_back(&security); + } + listener->on_securities(const_security_list); + break; + } + + case TaifexMessages::MessageIdentifier::I011: { + // std::cout << "we are looking for this!" << std::endl; + auto i011_message = TaifexMessages::I011Data( + buffer, position + HEADER_SIZE, Header.Body_Length + FOOTER_SIZE); + const auto id = TaifexUtils::remove_spaces(i011_message.kind_id); + security_details->add_i011_mapping( + id, i011_message.contract_size, i011_message.getCurrencyString()); + // bts::domain::SecurityID sec_id{ + // sec_id_store->get_or_add(api::domain::VENUE_TAIFEX, i011_message.kind_id)}; + // std::vector complete_security_list; + // bts::domain::Security &sec = complete_security_list.emplace_back(); + // sec.security_common.venue = bts::api::domain::VENUE_TAIFEX; + // // sec.security_common.id = sec_id; + // sec.security_common.exchange_sec_id = i011_message.kind_id; // Need to fix this + // sec.security_common.desc = i011_message.kind_id; + // sec.security_common.symbol = i011_message.kind_id; + // sec.security_common.asset = i011_message.kind_id; + // sec.security_common.group = i011_message.kind_id; + // sec.security_common.min_price_increment = 0.1; + // sec.security_common.min_quantity = 1; + // sec.security_common.min_quantity_increment = 0.1; + // sec.security_common.currency = i011_message.getCurrencyString(); + // switch(i011_message.contract_type){ + + // case TaifexMessages::I011Data::STOCK: + // case TaifexMessages::I011Data::INDEX: + // case TaifexMessages::I011Data::INTEREST_RATE: + // case TaifexMessages::I011Data::BOND: + // case TaifexMessages::I011Data::COMMODITY: + // case TaifexMessages::I011Data::CURRENCY: + // break; + // } + // auto &t = sec.security.emplace(); + // t.expiration = exp_time; + // std::vector const_security_list; + // for (const auto &security : complete_security_list) { + // const_security_list.push_back(&security); + // } + // listner->on_securities(const_security_list); + + // std::cout << i011_message << std::endl; + break; + } + // Add more cases for other message types + default: + // Handle unknown message types + break; + } +} + +void handleLiveDataParsedMessage( + const std::vector &buffer, + size_t position, + const TaifexMessages::Header_Fields &Header, + std::shared_ptr listener, + std::shared_ptr security_details) { + + switch (Header.message_type.identifier) { + case TaifexMessages::MessageIdentifier::I024: { //trades + auto i024_message = TaifexMessages::I024Data( + buffer, position + HEADER_SIZE, Header.Body_Length + FOOTER_SIZE); + std::vector trades; + for (const auto &trade_record : i024_message.trades) { + + bts::domain::TradeRecord &record = trades.emplace_back(); + + auto has_sec_id = security_details->get_sec_id( + TaifexUtils::remove_spaces(i024_message.prod_id)); + if (!has_sec_id.has_value()) { + std::cerr << "Invalid security ID for prod_id: " + << i024_message.prod_id << std::endl; + continue; + } + record.sec_id = bts::domain::SecurityID(has_sec_id->value()); + + auto dec_loc = security_details->get_dec_loc( + TaifexUtils::remove_spaces(i024_message.prod_id)); + if (!dec_loc.has_value()) { + throw std::runtime_error( + "Invalid decimal location for prod_id: " + + i024_message.prod_id); + } + //fix this + std::string iso_time_1 = TaifexUtils::convertToISO( + i024_message.match_time, "datetime_no_timezone"); + record.time_stamp = bts::core::TimeStamp::from_iso_string(iso_time_1); + record.trade_quantity = bts::domain::Quantity(trade_record.match_qty); + + double price = trade_record.match_price; + record.trade_price = + bts::domain::Price(price * std::pow(10, 9 - dec_loc.value())); + + // TODO: Set the aggressor side (record.agg_side) + } + + std::vector trade_ptrs; + trade_ptrs.reserve(trades.size()); + for (const auto &trade : trades) { + trade_ptrs.push_back(&trade); + } + // for (const auto *trade_ptr : trade_ptrs) { + // if (trade_ptr != nullptr) { + // LOG(md, Error, "Trade Quantity: {}, Trade Price: {}", + // trade_ptr->trade_quantity.value(), + // trade_ptr->trade_price); + // } + // } + listener->on_trades(trade_ptrs); + break; + } + + case TaifexMessages::MessageIdentifier::I081: { //incremental + auto i081_message = + TaifexMessages::I081Data(buffer, position + HEADER_SIZE); + std::optional sec_id = + security_details->get_sec_id( + TaifexUtils::remove_spaces(i081_message.prod_id)); + auto dec_loc = security_details->get_dec_loc( + TaifexUtils::remove_spaces(i081_message.prod_id)); + if (!sec_id.has_value() || !dec_loc.has_value()) { + break; + } + for (const auto &entry : i081_message.entries) { + IMarketDataListener::BookOp inc; + double adjusted_price = entry.price * pow(10, 9 - dec_loc.value()); + bts::domain::Price price = bts::domain::Price(adjusted_price); + bts::domain::Quantity quantity(entry.quantity); + inc.id = domain::SecurityID(sec_id->value()); + inc.price = price; + inc.quantity = quantity; + inc.side = (entry.md_entry_type == '0' || entry.md_entry_type == 'E') + ? bts::api::Side::SIDE_BUY + : bts::api::Side::SIDE_SELL; + switch (entry.md_update_action) { + case '0': + inc.op_type = IMarketDataListener::BookOpType::Add; + break; + case '1': + inc.op_type = IMarketDataListener::BookOpType::MODIFY; + break; + case '2': + inc.op_type = IMarketDataListener::BookOpType::REMOVE; + break; + default: + continue; + } + listener->on_book_increment(inc); + } + break; + } + + case TaifexMessages::MessageIdentifier::I083: { //snapshot + auto i083_message = TaifexMessages::I083Data( + buffer, position + HEADER_SIZE, Header.Body_Length + FOOTER_SIZE); + processI083Message(i083_message, listener, security_details); + break; + } + // Add more cases for other message types + default: + // Handle unknown message types + break; + } +} +std::shared_ptr handleRefreshDataParsedMessage( + const std::vector &buffer, + size_t position, + const TaifexMessages::Header_Fields &Header) { + switch (Header.message_type.identifier) { + case TaifexMessages::MessageIdentifier::I084: + return std::make_shared( + TaifexMessages::I084Data(buffer, position)); + //handle this + break; + default: + bts_assert_msg(false, "NOT IN REFRESH DATA"); + } + bts_assert_msg(false, "Control should not reach here"); + return std::make_shared( + TaifexMessages::I084Data(buffer, position)); + ; +} + +bool readBinaryFile( + const std::string &file_name, + std::shared_ptr listener, + std::shared_ptr sec_id_store, + std::shared_ptr security_details, + TaifexDataGateway::DATA_TYPE data_type) { + const size_t BUFFER_SIZE = 1024 * 1024; + std::ifstream file(file_name, std::ios::binary); + if (!file) { + LOG(md, Error, "File not found: {}", file_name); + bts_assert(false); + } + + std::vector buffer( + BUFFER_SIZE + 1024); // Extra space for possible leftovers + std::vector prev_data(1024); // Stores leftover data + bool start = true; + size_t prev_data_len = 0; // Length of leftover data + while (file.read( + reinterpret_cast(buffer.data() + prev_data_len), BUFFER_SIZE)) { + size_t bytes_read = file.gcount(); + if (bytes_read < BUFFER_SIZE) { + break; // No more data to read + } + if (!start) { + // Move data from prev_data to the start of the buffer + std::memcpy(buffer.data(), prev_data.data(), prev_data_len); + } + + size_t position = 0; + while (position < (BUFFER_SIZE + prev_data_len - HEADER_SIZE)) { + auto Header = TaifexMessages::Header_Fields(buffer, position); + size_t message_length = Header.Body_Length + HEADER_SIZE + FOOTER_SIZE; + + // Check if the full message fits within the buffer + if ((BUFFER_SIZE + prev_data_len - position) >= message_length) { + // Handle the parsed message + switch (data_type) { + case TaifexDataGateway::DATA_TYPE::LIVE: + handleLiveDataParsedMessage( + buffer, position, Header, listener, security_details); + break; + case TaifexDataGateway::DATA_TYPE::REFERENCE: + handleReferenceDataParsedMessage( + buffer, position, Header, listener, sec_id_store, + security_details); + break; + case TaifexDataGateway::DATA_TYPE::REFRESH: + handleRefreshDataParsedMessage(buffer, position, Header); + break; + default: + bts_assert(false); + } + position += message_length; + } else { + // Incomplete message, break and handle leftover data + break; + } + } + + // Move remaining (incomplete) data from buffer into prev_data and set prev_data_len + prev_data_len = BUFFER_SIZE + prev_data_len - position; + if (prev_data_len > 0) { + std::memcpy(prev_data.data(), buffer.data() + position, prev_data_len); + } + + start = false; // Only move leftover data on subsequent iterations + } + return true; +} + +void HandleRefreshFeed( + int socket, + unsigned long seq_num, + std::vector &messages, + unsigned long &refresh_seq_num) { + LOG(md, Info, "HandleRefreshFeed looking for {}", seq_num); + + enum { + WAITING_FOR_A = 0, + WAITING_FOR_Z, + } refresh_state = WAITING_FOR_A; + + while (!stop_refresh_thread && !stop_live_buffer_thread) { + std::vector buffer(FEED_BUFFER_SIZE); + std::string desc = "Refresh Socket"; + size_t bytes_received = + TaifexUtils::recv_socket_data(socket, buffer, FEED_BUFFER_SIZE, desc); + if (bytes_received <= 0) { + continue; + } + auto Header = TaifexMessages::Header_Fields(buffer, 0); + switch (refresh_state) { + case WAITING_FOR_A: { + auto i084_message = + TaifexMessages::I084Data(buffer, HEADER_SIZE, true); + LOG(md, Info, "HandleRefreshFeed WAITING_FOR_A looking for {}, got {}", + seq_num, i084_message.last_seq); + if (i084_message.message_type == TaifexMessages::I084Data::A && + i084_message.last_seq > seq_num) { + refresh_state = WAITING_FOR_Z; + } + break; + } + case WAITING_FOR_Z: { + LOG(md, Info, "HandleRefreshFeed WAITING_FOR_Z"); + auto i084_message = TaifexMessages::I084Data(buffer, HEADER_SIZE); + // bts_assert(i084_message.last_seq > seq_num); + if (i084_message.message_type == TaifexMessages::I084Data::O) { + for (auto m : i084_message.data) { + messages.push_back(m); + } + } else if (i084_message.message_type == TaifexMessages::I084Data::Z) { + LOG(md, Info, "HandleRefreshFeed Z found"); + refresh_seq_num = i084_message.last_seq; + stop_refresh_thread = true; + return; + } + break; + } + } + } +} +void HandleReferenceFeed( + int socket, + std::shared_ptr listener, + std::shared_ptr sec_id_store, + std::shared_ptr security_details) { + std::vector buffer(FEED_BUFFER_SIZE); + LOG(md, Info, "HandleReferenceFeed"); + std::string desc = "Reference socket"; + while (!stop_reference_thread) { + size_t bytes_received = + TaifexUtils::recv_socket_data(socket, buffer, FEED_BUFFER_SIZE, desc); + if (bytes_received <= 0) { + continue; + } + auto Header = TaifexMessages::Header_Fields(buffer, 0); + size_t message_length = Header.Body_Length + HEADER_SIZE + FOOTER_SIZE; + if(bytes_received != message_length){ + LOG(md,Error,"Reference data recv: {}, should be:{}", bytes_received, + message_length); + }else{ + handleReferenceDataParsedMessage( + buffer, 0, Header, listener, sec_id_store, security_details); + + } + } + + // 6. Close the socket after done processing + close(socket); +} + +void HandleLiveBufferFeed( + int socket, + tbb::concurrent_queue> &buffered_messages, + std::string desc) { + int bytes_received = -1; + while (!stop_live_buffer_thread) { + std::vector b(FEED_BUFFER_SIZE); + // auto &b = buffered_messages.emplace(); + bytes_received = + TaifexUtils::recv_socket_data(socket, b, FEED_BUFFER_SIZE, desc); + if (bytes_received <= 0) { + state = LIVE_DATA_STATES::START; + break; + } + + if (bytes_received > 0) { + b.resize(bytes_received); + buffered_messages.push( + std::move(b)); // have to use this instea of emplace + } + } + stop_live_buffer_thread = true; +} + +void runLive( + std::shared_ptr listener, + std::shared_ptr sec_id_store, + std::shared_ptr security_details) { + + long reset_counter = -1; + state = LIVE_DATA_STATES::START; + TaifexSecurityDetailsMapper sec_details; + std::set sockets; + unsigned long last_seq_num; + tbb::concurrent_queue> + buffered_messages; // Shared concurrent queue + + // Load from config + // std::string live_data_ip = "225.0.140.140"; + const int live_data_port = 14000; + std::string futures_market_data_ip = + "192.168.201.94"; // Replace with actual IP + // std::string reference_data_ip = "225.0.140.141"; // Placeholder + const int reference_data_port = 14100; // Placeholder + // std::string refresh_data_ip = "225.0.140.147"; // Placeholder + const int refresh_data_port = 14700; // Placeholder + + // if (use_after_hours) { + // live_data_ip = "225.10.140.140"; + // reference_data_ip = "225.10.140.141"; // Placeholder + // refresh_data_ip = "225.10.140.147"; // Placeholder + // } + auto live_data_ip = getIP("realtime"); + auto reference_data_ip = getIP("reference"); + auto refresh_data_ip = getIP("refresh"); + std::vector refresh_messages; + int live_socket = -1; + int last_channel_id = -1; + + while (true) { + switch (state) { + case LIVE_DATA_STATES::START: { + reset_counter++; + LOG(md, Error, "State: START counter:{}", reset_counter); + stop_reference_thread = stop_refresh_thread = stop_live_buffer_thread = + true; + sec_details.reset(); + buffered_messages.clear(); + TaifexUtils::close_sockets(sockets); + last_seq_num = 0; + assert(reset_counter < 2); + + state = LIVE_DATA_STATES::WAITING_FOR_REFRESH_DATA; + break; + } + case LIVE_DATA_STATES::WAITING_FOR_REFRESH_DATA: { + LOG(md, Info, "State: WAITING_FOR_REFRESH_DATA"); + + auto reference_socket = TaifexUtils::create_multicast_socket_assert( + reference_data_ip, reference_data_port, futures_market_data_ip); + sockets.insert(reference_socket); + + stop_reference_thread = false; + bts::threading::make_thread("Taifex_reference_data", [&]() { + HandleReferenceFeed( + reference_socket, std::ref(listener), std::ref(sec_id_store), + std::ref(security_details)); + }).detach(); + LOG(md, Info, + "State: WAITING_FOR_REFRESH_DATA Reference thread started"); + + std::string desc = "WAITING_FOR_REFRESH_DATA Live data"; + live_socket = TaifexUtils::create_multicast_socket_assert( + live_data_ip, live_data_port, futures_market_data_ip); + sockets.insert(live_socket); + std::vector buffer(FEED_BUFFER_SIZE); + size_t bytes_received = TaifexUtils::recv_socket_data( + live_socket, buffer, FEED_BUFFER_SIZE, desc); + if (bytes_received <= 0) { + state = LIVE_DATA_STATES::START; + break; + } + + auto s = TaifexUtils::getBufferString(buffer); + LOG(md, Info, + "State: WAITING_FOR_REFRESH_DATA first live message recieved: {}", + s); + + TaifexMessages::Header_Fields Header = + TaifexMessages::Header_Fields(buffer, 0); + if (!Header.valid) { + LOG(md, Error, "Header not valid"); + state = LIVE_DATA_STATES::START; + break; + } + + last_seq_num = Header.Channel_Seq; + stop_refresh_thread = false; + stop_live_buffer_thread = false; + + bts::threading::make_thread("Taifex_live_buffer", [&]() { + HandleLiveBufferFeed( + live_socket, buffered_messages, "Taifex Live Buffer"); + }).detach(); + LOG(md, Info, + "State: WAITING_FOR_REFRESH_DATA refresh thread started"); + + auto refresh_socket = TaifexUtils::create_multicast_socket_assert( + refresh_data_ip, refresh_data_port, futures_market_data_ip); + sockets.insert(refresh_socket); + + unsigned long refresh_seq_num = 0; + HandleRefreshFeed( + refresh_socket, last_seq_num, refresh_messages, refresh_seq_num); + + last_seq_num = refresh_seq_num; + if (state != LIVE_DATA_STATES::START) + state = LIVE_DATA_STATES::REFRESH_DATA_DONE; + break; + } + case LIVE_DATA_STATES::REFRESH_DATA_DONE: { + LOG(md, Info, "State: REFRESH_DATA_DONE"); + + bts_assert(stop_refresh_thread); + for (auto &m : refresh_messages) { + processI083Message(m, listener, security_details); + } + state = LIVE_DATA_STATES::WAITING_TO_SYNC_LIVE; + break; + // stop reference data + // apply all refresh data + } + case LIVE_DATA_STATES::WAITING_TO_SYNC_LIVE: { + LOG(md, Info, "State: WAITING_TO_SYNC_LIVE"); + + while (true) { + + // Process messages from the concurrent queue + std::vector buffer; + buffered_messages.try_pop(buffer); + if (buffer.empty()) { + continue; + } + + TaifexMessages::Header_Fields Header(buffer, 0); + if (!Header.valid) { + std::cout << "Header not valid" << std::endl; + state = LIVE_DATA_STATES::START; + break; + } + + if (Header.Channel_Seq < last_seq_num) { + continue; // Skip messages with outdated sequence numbers + } else { + break; + } + // If no message was available to pop, break the outer while loop + if (buffered_messages.empty()) { + break; + } + } + + state = LIVE_DATA_STATES::LIVE_RUNNING; + break; + } + // while 1 + // process buffer: + // if seq_num > last_seq_num + 1 + // if seq_num <= last_seq_num + // skip message + // state = LIVE_RUNNING; + // break + case LIVE_DATA_STATES::LIVE_RUNNING: { + // if seq_num != last_seq_num + 1 + LOG(md, Info, "STATE: LIVE RUNNING !!"); + while (state == LIVE_DATA_STATES::LIVE_RUNNING) { + + std::vector buffer; + buffered_messages.try_pop(buffer); + if (buffer.empty()) { + continue; + } + TaifexMessages::Header_Fields Header = + TaifexMessages::Header_Fields(buffer, 0); + if (!Header.valid) { + LOG(md, Error, "Header not valid"); + state = LIVE_DATA_STATES::START; + break; + } + if (Header.Channel_Seq != last_seq_num + 1) { + LOG(md, Info, "Header.Channel_Seq != last_seq_num+1"); + LOG(md, Info, "header.channel_seq {}", Header.Channel_Seq); + LOG(md, Info, "header.channel_id {}", Header.Channel_Id); + LOG(md, Info, "last_seq_number {}", last_seq_num); + LOG(md, Info, "last channel id {}", last_channel_id); + state = LIVE_DATA_STATES::START; + break; + } + last_seq_num = Header.Channel_Seq; + last_channel_id = Header.Channel_Id; + handleLiveDataParsedMessage( + buffer, 0, Header, listener, security_details); + } + break; + } + // else + // process live + default: + bts_assert(false); + }; + } +} +//const std::string &filename, +void bts::md::taifex::TaifexDataGateway::run( + const api::md::TaifexMarketDataConfig &config, + std::shared_ptr listner, + std::shared_ptr sec_id_store) { + std::shared_ptr sec_details = + std::make_shared(); + if (config.read_from_file()) { + bts_assert(!config.ref_data_file_name().empty()); + bts_assert(!config.realtime_data_file_name().empty()); + std::string reference_file_name = + config.ref_data_file_name(); //"reference_data_20240806_1"; + std::string realtime_file_name = + config.realtime_data_file_name(); //"real_time_data_20240806_274"; + std::string base_path = + config::get().data_path(); + readBinaryFile( + base_path + reference_file_name, listner, sec_id_store, sec_details, + REFERENCE); + readBinaryFile( + base_path + realtime_file_name, listner, sec_id_store, sec_details, + LIVE); + while (1) { //confirm with taha + sleep_for(10s); + } + } else { + runLive( + listner, sec_id_store, + sec_details); //regular_hours_connection_details,after_hours_connection_details); + } +} + +} //namespace bts::md::taifex diff --git a/src/server/sparkd/md/taifex/TaifexDataHandler.h b/src/server/sparkd/md/taifex/TaifexDataGateway.h similarity index 66% rename from src/server/sparkd/md/taifex/TaifexDataHandler.h rename to src/server/sparkd/md/taifex/TaifexDataGateway.h index a81d621d6..20a81c0e1 100644 --- a/src/server/sparkd/md/taifex/TaifexDataHandler.h +++ b/src/server/sparkd/md/taifex/TaifexDataGateway.h @@ -1,5 +1,6 @@ #pragma once +#include "lib/api/md/TaifexMarketDataConfig.pb.h" #include namespace bts::persistence { @@ -12,10 +13,15 @@ class IMarketDataListener; namespace bts::md::taifex { // const std::string &filename, -class TaifexDatahandler { +class TaifexDataGateway { public: + enum DATA_TYPE{ + LIVE=0, + REFERENCE, + REFRESH + }; static void run( - bool use_file, + const api::md::TaifexMarketDataConfig &config, std::shared_ptr listner, std::shared_ptr sec_id_store); }; diff --git a/src/server/sparkd/md/taifex/TaifexDataHandler.cpp b/src/server/sparkd/md/taifex/TaifexDataHandler.cpp deleted file mode 100644 index 166ab255c..000000000 --- a/src/server/sparkd/md/taifex/TaifexDataHandler.cpp +++ /dev/null @@ -1,1399 +0,0 @@ -#include "TaifexDataHandler.h" -#include "lib/api/domain/Venue.pb.h" -#include "lib/config/config.h" -#include "lib/domain/Price.h" -#include "lib/domain/Security.h" -#include "lib/domain/SecurityID.h" -#include "lib/logging/logging.h" -#include "lib/md/IMarketDataListener.h" -#include "lib/persistence/IDGenerator.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -namespace bts::md::taifex { - -class SecurityDetailsMapper { - struct security_details{ - double min_increment; - std::string currency; - bool has_i010 = false; - bool has_i011 = false; - uint dec_loc; - bts::domain::SecurityID sec_id; -}; - -public: - - // Add a mapping from instrument_id to sec_id - void add_i010_mapping( - std::string instrument_id, - bts::domain::SecurityID sec_id, - uint decimal_locator) { - auto& details = sec_deets_map[instrument_id]; - details.sec_id = sec_id; - details.dec_loc = decimal_locator; - details.has_i010 = true; - } - - // Add a mapping for i011 - void add_i011_mapping( - std::string instrument_id, - double min_increment, - std::string currency) { - auto& details = sec_deets_map[instrument_id]; - details.min_increment = min_increment; - details.currency = currency; - details.has_i011 = true; - } - - // Find sec_id by instrument_id - std::optional get_sec_id( - std::string instrument_id) const { - auto it = sec_deets_map.find(instrument_id); - if (it != sec_deets_map.end() && it->second.has_i010) { - return it->second.sec_id; - } - return std::nullopt; - } - - // Find dec_loc by instrument_id - std::optional get_dec_loc(std::string instrument_id) const { - auto it = sec_deets_map.find(instrument_id); - if (it != sec_deets_map.end() && it->second.has_i010) { - return it->second.dec_loc; - } - return std::nullopt; - } - std::string get_currency(std::string instrument_id) const { - auto it = sec_deets_map.find(instrument_id); - if (it != sec_deets_map.end() && it->second.has_i010 && it->second.has_i011) { - return it->second.currency; - } - return "usd"; - } - - double get_min_inc(std::string instrument_id) const { - auto it = sec_deets_map.find(instrument_id); - if (it != sec_deets_map.end() && it->second.has_i010 && it->second.has_i011) { - return it->second.min_increment; - } - return 1; - } - // to_string function to print all data in both maps - std::string to_string() const { - std::stringstream ss; - for (const auto& [instrument_id, details] : sec_deets_map) { - ss << "Instrument ID: " << instrument_id << "\n" - << " Sec ID: " << details.sec_id << "\n" - << " Dec Loc: " << details.dec_loc << "\n" - << " Min Increment: " << details.min_increment << "\n" - << " Currency: " << details.currency << "\n" - << " Has I010: " << (details.has_i010 ? "Yes" : "No") << "\n" - << " Has I011: " << (details.has_i011 ? "Yes" : "No") << "\n"; - } - return ss.str(); - } - -private: - std::unordered_map sec_deets_map; -}; - - -const size_t BUFFER_SIZE = 1024 * 1024; -const size_t FOOTER_SIZE = 3; -const size_t HEADER_SIZE = 19; -void printBuffer( - const std::vector &buffer, - size_t offset = 0, - size_t length = -1) { - if ((int)length == -1) { - length = buffer.size(); - } - for (size_t i = 0; i < length; ++i) { - // Print each byte in hexadecimal format - // std::cout << std::hex << std::setw(2) << std::setfill('0') - // << (int)buffer[i]; - printf( - " offset: %zu, i: %zu, value: %.2X|", offset, i, - (unsigned int)buffer[offset + i]); - } - // std::cout << std::dec << std::endl; -} - -struct MessageIdentifier { - enum MessageID { - I010 = 1, - I030 = 2, - I011 = 3, - I050 = 4, - I060 = 5, - I120 = 6, - I130 = 7, - I064 = 8, - I012 = 9, - I083 = 10, - I140 = 11, - I110 = 12, - I014 = 13, - I024 = 14, - I025 = 15, - I100 = 16, - I081 = 17, // Add I081 - I084 = 18, // Add I084 - I072 = 19, // Add I072 - I071 = 20, // Add I071 - I073 = 21, // Add I073 - I070 = 22, - I001 = 23, - I002 = 24, - I999 = 0 // unknown - }; - static std::string messageIDToString(MessageID id) { - switch (id) { - case I010: - return "I010"; - case I030: - return "I030"; - case I011: - return "I011"; - case I050: - return "I050"; - case I060: - return "I060"; - case I120: - return "I120"; - case I130: - return "I130"; - case I064: - return "I064"; - case I012: - return "I012"; - case I083: - return "I083"; - case I140: - return "I140"; - case I110: - return "I110"; - case I014: - return "I014"; - case I024: - return "I024"; - case I025: - return "I025"; - case I100: - return "I100"; - case I081: - return "I081"; - case I084: - return "I084"; - case I072: - return "I072"; - case I071: - return "I071"; - case I073: - return "I073"; - case I070: - return "I070"; - case I001: - return "I001"; - case I002: - return "I002"; - default: - return "Unknown"; - } - } - void set_identifier_description( - const unsigned char transmissionCode, const unsigned char messageKind) { - switch (transmissionCode) { - case '0': - switch (messageKind) { - case '1': - identifier = I001; - description = "Heartbeat"; - break; - case '2': - identifier = I002; - description = "Reset message"; - break; - default: - identifier = I999; - description = "unknown"; - break; - } - break; - case '1': - switch (messageKind) { - case '1': - identifier = I010; - description = "Product basic data"; - break; - case '2': - identifier = I030; - description = "Sum of order data"; - break; - case '3': - identifier = I011; - description = "Contract basic data"; - break; - case '4': - identifier = I050; - description = "System message"; - break; - case '5': - identifier = I060; - description = "Underlying index or stock reference data"; - break; - case '6': - identifier = I120; - description = "Reference of stock or underlying index"; - break; - case '7': - identifier = I130; - description = "Contract Adjustment"; - break; - case '8': - identifier = I064; - description = - "Calculated opening and closing price for underlying stocks"; - break; - case 'A': - identifier = I012; - description = "Price limits"; - break; - default: - identifier = I999; - description = "unknown"; - break; - } - break; - case '2': - switch (messageKind) { - case 'B': - identifier = I083; - description = "Snapshot order book"; - break; - case '3': - identifier = I140; - description = "System message"; - break; - case '4': - identifier = I100; - description = "Closing market data (settlement price included)"; - break; - case 'A': - identifier = I081; - description = "Aggregated order book"; - break; - case 'C': - identifier = I084; - description = "Market data snapshot refresh"; - break; - case 'D': - identifier = I024; - description = "Matched prices and quantities"; - break; - case 'E': - identifier = I025; - description = "Closing market data"; - break; - default: - identifier = I999; - description = "unknown"; - break; - } - break; - case '3': - switch (messageKind) { - case '3': - identifier = I072; - description = "Closing market data"; - break; - case '1': - identifier = I070; - description = "Closing market data"; - break; - case '2': - identifier = I071; - description = "Closing market data with settlement price"; - break; - case '4': - identifier = I073; - description = "Combination product closing market data"; - break; - default: - identifier = I999; - description = "unknown"; - break; - } - break; - default: - identifier = I999; - description = "unknown"; - break; - } - } - MessageIdentifier( - const unsigned char transmissionCode, const unsigned char messageKind) - : transmissionCode(transmissionCode), messageKind(messageKind) { - set_identifier_description(transmissionCode, messageKind); - } - unsigned char transmissionCode; - unsigned char messageKind; - MessageID identifier; - std::string description; - friend std::ostream &operator<<( - std::ostream &os, const MessageIdentifier &MI) { - os << "TransmissionCode: " << MI.transmissionCode - << "\nMessageKind: " << MI.messageKind - << "\nDescription: " << MI.description << "\nidentifier: " - << MessageIdentifier::messageIDToString(MI.identifier); - return os; - } -}; - -// need to change parameters -std::string decodePackBCD(const unsigned char *data, size_t length) { - std::stringstream ss; - for (size_t i = 0; i < length; ++i) { - // Extract the upper and lower nibble (4 bits each) - int upper = (data[i] >> 4) & 0x0F; - int lower = data[i] & 0x0F; - - // Append both nibbles to the stringstream - ss << upper << lower; - } - - std::string result = ss.str(); - - // Remove leading zeros - result.erase(0, result.find_first_not_of('0')); - - // If the result is empty (all zeros), return "0" - return result.empty() ? "0" : result; -} - -struct Header_Fields { - uint8_t Esc_Code; // 1 byte - MessageIdentifier message_type; - std::string Information_Time; - int Channel_Id; - std::string Channel_Seq; - uint8_t Version_No; - uint Body_Length; - bool valid = false; - Header_Fields(const std::vector &buffer, const size_t &offset) - : Esc_Code(buffer[offset]), - message_type(buffer[offset + 1], buffer[offset + 2]) { - // creates header feild struct - // and populates all fields - // Header_Fields header; - // Read single-byte fields - assert(message_type.identifier != MessageIdentifier::MessageID::I999); - // Read 2 bytes for Body_Length - unsigned char bl[2] = {buffer[offset + 17], buffer[offset + 18]}; - Body_Length = std::stoul(decodePackBCD(bl, 2)); - valid = true; - } - - friend std::ostream &operator<<(std::ostream &os, const Header_Fields &hf) { - os << "Esc_Code: " << static_cast(hf.Esc_Code) << "\n" - << hf.message_type - << "\n" - // << "Information_Time: " << hf.Information_Time << "\n" - // << "Channel_Id: " << hf.Channel_Id << "\n" - // << "Channel_Seq: " << hf.Channel_Seq << "\n" - // << "Version_No: " << static_cast(hf.Version_No) << "\n" - << "Body_Length: " << hf.Body_Length << "\n" - << "Valid: " << (hf.valid ? "true" : "false"); - return os; - } -}; - -std::string extractString( - const std::vector &buffer, size_t &position, size_t length) { - // Extract the substring from the buffer - std::string result( - buffer.begin() + position, buffer.begin() + position + length); - position += length; - - // Log the raw result - return result; -} - -// Helper function to extract a BCD value from the buffer and convert to -// unsigned long -unsigned long extractBCD_STOUL( - const std::vector &buffer, size_t &position, size_t length) { - std::string bcd_str = decodePackBCD(&buffer[position], length); - position += length; - return std::stoul(bcd_str); -} -std::string extractBCD_STRING( - const std::vector &buffer, size_t &position, size_t length) { - std::string bcd_str = decodePackBCD(&buffer[position], length); - position += length; - return bcd_str; -} -// Helper function to extract a single character and convert to bool -bool extractBool(const std::vector &buffer, size_t &position) { - bool result = (buffer[position] == 'Y'); - position += 1; - return result; -} - -std::string extractBCDDate( - const std::vector &buffer, - size_t ¤t_position, - size_t size) { - if (size != 4) { - throw std::invalid_argument("BCD date must be 4 bytes long"); - } - - std::string date; - for (size_t i = 0; i < size; ++i) { - unsigned char byte = buffer[current_position++]; - char high = (byte >> 4) + '0'; - char low = (byte & 0x0F) + '0'; - date.push_back(high); - date.push_back(low); - } - - // Ensure the date is in YYYYMMDD format - if (date.length() != 8) { - throw std::runtime_error("Extracted date is not in YYYYMMDD format"); - } - - return date; -} - -struct I024Data { - struct trade { - enum Sign { POSITIVE = 0, NEGATIVE = 1 }; - Sign sign; - std::string match_price; // need to determine type(appendix 2) - std::string match_qty; // keeping str for simplicity - - trade( - const std::vector &buffer, - const size_t &offset = 0, - const size_t match_qty_size = 2) { - const size_t SIGN_SIZE = 1; - const size_t MATCH_PRICE_SIZE = 5; - const size_t MATCH_QTY_SIZE = match_qty_size; - auto current_position = offset; - // Extract Sign - sign = (buffer[current_position] == '0') ? POSITIVE : NEGATIVE; - current_position += SIGN_SIZE; - - match_price = - decodePackBCD(buffer.data() + current_position, MATCH_PRICE_SIZE); - current_position += MATCH_PRICE_SIZE; - - match_qty = - extractBCD_STRING(buffer, current_position, MATCH_QTY_SIZE); - } - friend std::ostream &operator<<(std::ostream &os, const trade &data) { - os << "Sign: " - << (data.sign == Sign::POSITIVE ? "Positive" : "Negative") << '\n' - << "Match Price: " << data.match_price << '\n' - << "Match Quantity: " << data.match_qty << '\n'; - return os; - } - }; - std::string prod_id; - unsigned long sequence_number; - bool calculated_flag; - std::string match_time; // make another struct for time? - char match_display_item; // need to discuss - std::vector trades; - // next fields to add - std::string match_total_qty; - std::string match_buy_count; - std::string match_sell_count; - I024Data( - const std::vector &buffer, - const size_t &offset = 0, - const size_t &length = -1) { - const size_t PROD_ID_SIZE = 20; - const size_t SEQ_NUMBER_SIZE = 5; - const size_t CALCULATED_FLAG = 1; - const size_t MATCH_TIME = 6; - const size_t MATCH_DISPLAY_ITEM_SIZE = 1; - const size_t TRADE_SIZE = 8; - const size_t MATCH_TOTAL_QTY_SIZE = 4; - const size_t MATCH_BUY_COUNT_SIZE = 4; - const size_t MATCH_SELL_COUNT_SIZE = 4; - const size_t FIRST_MATCH_QTY_SIZE = 4; - if (buffer.size() < offset + length) { - throw std::out_of_range("Buffer is smaller than the required length"); - } - // do we need this? - size_t current_position = offset; - prod_id = extractString(buffer, current_position, PROD_ID_SIZE); - - sequence_number = - extractBCD_STOUL(buffer, current_position, SEQ_NUMBER_SIZE); - - // Extract Calculated Flag - std::string calculated_flag_str = - extractString(buffer, current_position, CALCULATED_FLAG); - calculated_flag = (calculated_flag_str[0] == '1'); - - // Extract Match Time - match_time = decodePackBCD(buffer.data() + current_position, MATCH_TIME); - ; // extractBCD(buffer, current_position, MATCH_TIME); - current_position += MATCH_TIME; - trades.push_back(trade(buffer, current_position, FIRST_MATCH_QTY_SIZE)); - current_position += TRADE_SIZE + 2; - // Extract Match Display Item - auto getFirstBitAndRemainingValue = - [](char input) -> std::tuple { - bool firstBit = (input & 0b10000000) != 0; - int remainingValue = input & 0b01111111; - return std::make_tuple(firstBit, remainingValue); - }; - match_display_item = buffer[current_position]; - current_position += MATCH_DISPLAY_ITEM_SIZE; - - auto [new_message, trades_count] = - getFirstBitAndRemainingValue(match_display_item); - // assert(new_message); - for (int i = 0; i < trades_count; i++) { - trades.push_back(trade(buffer, current_position)); - current_position += TRADE_SIZE; - } - // match quantity - match_total_qty = - extractBCD_STRING(buffer, current_position, MATCH_TOTAL_QTY_SIZE); - // match buy count - match_buy_count = - extractBCD_STRING(buffer, current_position, MATCH_BUY_COUNT_SIZE); - // match sell count - match_sell_count = - extractBCD_STRING(buffer, current_position, MATCH_SELL_COUNT_SIZE); - std::cout << "trades count: " << trades_count << std::endl; - assert( - buffer[current_position + 1] == 0x0D && - buffer[current_position + 2] == 0x0A); - } - // 833 251 1142 - friend std::ostream &operator<<(std::ostream &os, const I024Data &data) { - os << "Product ID: " << data.prod_id << '\n' - << "Sequence Number: " << data.sequence_number << '\n' - << "Calculated Flag: " << (data.calculated_flag ? '1' : '0') << '\n' - << "Match Time: " << data.match_time << '\n' - << "Match Display Item: " - << std::bitset<8>{static_cast( - data.match_display_item)} - << "\n"; // Output as integer to show value - - for (auto t : data.trades) { - os << "Trade: " << t << "\n"; - } - - os << "Match Total Quantity: " << data.match_total_qty << '\n' - << "Match Buy Count: " << data.match_buy_count << '\n' - << "Match Sell Count: " << data.match_sell_count << '\n'; - return os; - } -}; - -struct I010Data { - std::string prod_id; // PROD-ID-S X(10) 10 Product ID - unsigned long - reference_price; // REFERENCE-PRICE 9(9) 5 Reference price PACK BCD - std::string prod_kind; // PROD-KIND X(1) 1 Type of contract - unsigned int decimal_locator; // DECIMAL-LOCATOR 9(1) 1 Number of decimal - // digits in price fields PACK BCD - unsigned int - strike_price_decimal_locator; // STRIKE-PRICE-DECIMAL-LOCATOR 9(1) 1 - // Number of decimal digits in strike price - // of options product PACK BCD - std::string - begin_date; // BEGIN-DATE 9(8) 4 Listed date of product (YYYYMMDD) - // PACK BCD - std::string - end_date; // END-DATE 9(8) 4 Expiry date of product (YYYYMMDD) PACK BCD - unsigned int flow_group; // FLOW-GROUP 9(2) 1 Flow group PACK BCD - std::string - delivery_date; // DELIVERY-DATE 9(8) 4 Delivery date of product PACK BCD - bool - dynamic_banding; // DYNAMIC-BANDING X(1) 1 Is dynamic banding applicable? - // Y: Yes, N: No - - // Embedded ProductInfo struct - struct ProductInfo { - enum class ProductType { FUTURES, OPTIONS } productType; - - std::string productID; - int expirationYear; - int expirationMonth; - bool isCall; - double strikePrice; - bool isWeekly; - bool isSpread; - std::string spreadSecondLeg; - - // Convert month code to month number - static int getMonthFromCode(char code) { - if (code >= 'A' && code <= 'L') - return code - 'A' + - 1; // 'A' corresponds to 1 (January), 'B' to 2, ..., 'L' to 12 (December) - throw std::runtime_error("Invalid month code"); - } - - // Method to parse Product ID and initialize ProductInfo - static ProductInfo parseProductID(const std::string &prodID) { - ProductInfo info; - - if (prodID.length() == 10 || prodID.length() == 20) { - // Futures product parsing - info.productType = ProductType::FUTURES; - info.productID = prodID.substr(0, 3); - info.expirationMonth = getMonthFromCode(prodID[3]); - info.expirationYear = - 2020 + - (prodID[4] - '0'); // Assuming the year is between 2020 and 2029 - info.isWeekly = - prodID[2] >= '1' && prodID[2] <= '5'; // Weekly expired contract - info.isSpread = prodID.length() > 10; // Check if it's a spread - if (info.isSpread) { - info.spreadSecondLeg = - prodID.substr(11, 6); // Parsing the second leg of the spread - } - } else if (prodID.length() == 11) { - // Weekly time spread product parsing - info.productType = ProductType::FUTURES; - info.isWeekly = true; - info.isSpread = true; - info.productID = prodID.substr(0, 3); - info.expirationMonth = getMonthFromCode(prodID[3]); - info.expirationYear = 2020 + (prodID[4] - '0'); - info.spreadSecondLeg = prodID.substr(6, 5); - } else if (prodID.length() == 12) { - // Options product parsing - info.productType = ProductType::OPTIONS; - info.productID = prodID.substr(0, 3); - info.strikePrice = std::stod( - prodID.substr(3, 5)); // Assuming no decimal point for now - info.isCall = prodID[8] >= 'A' && prodID[8] <= 'L'; // Call options - info.expirationMonth = getMonthFromCode(prodID[8]); - info.expirationYear = 2020 + (prodID[9] - '0'); - } else { - throw std::invalid_argument("Invalid Product ID length"); - } - - return info; - } - - // Overload the << operator to print ProductInfo - friend std::ostream &operator<<( - std::ostream &os, const ProductInfo &info) { - os << "Product Type: " - << (info.productType == ProductType::FUTURES ? "Futures" - : "Options") - << '\n' - << "Product ID: " << info.productID << '\n' - << "Expiration Month: " << info.expirationMonth << " (" - << (info.expirationMonth == 1 ? "January" - : info.expirationMonth == 2 ? "February" - : info.expirationMonth == 3 ? "March" - : info.expirationMonth == 4 ? "April" - : info.expirationMonth == 5 ? "May" - : info.expirationMonth == 6 ? "June" - : info.expirationMonth == 7 ? "July" - : info.expirationMonth == 8 ? "August" - : info.expirationMonth == 9 ? "September" - : info.expirationMonth == 10 ? "October" - : info.expirationMonth == 11 ? "November" - : info.expirationMonth == 12 ? "December" - : "Unknown") - << ")\n" - << "Expiration Year: " << info.expirationYear << '\n' - << "Strike Price: " << info.strikePrice << '\n' - << "Is Weekly: " << (info.isWeekly ? "Yes" : "No") << '\n' - << "Is Call: " << (info.isCall ? "Yes" : "No") << '\n' - << "Is Spread: " << (info.isSpread ? "Yes" : "No") << '\n'; - if (info.isSpread) { - os << "Spread Second Leg: " << info.spreadSecondLeg << '\n'; - } - return os; - } - } parsedProductInfo; - // Constructor to initialize from a buffer - I010Data( - const std::vector &buffer, - size_t offset = 0, - size_t length = -1) { - const size_t PROD_ID_SIZE = 10; - const size_t REFERENCE_PRICE_SIZE = 5; - const size_t PROD_KIND_SIZE = 1; - const size_t DECIMAL_LOCATOR_SIZE = 1; - const size_t STRIKE_PRICE_DECIMAL_LOCATOR_SIZE = 1; - const size_t BEGIN_DATE_SIZE = 4; - const size_t END_DATE_SIZE = 4; - const size_t FLOW_GROUP_SIZE = 1; - const size_t DELIVERY_DATE_SIZE = 4; - // const size_t DYNAMIC_BANDING_SIZE = 1; - - // Parse ProductInfo using the extracted product ID - // parsedProductInfo = ProductInfo::parseProductID(prod_id, strike_price_decimal_locator); - - if (buffer.size() < offset + length) { - throw std::out_of_range("Buffer is smaller than the required length"); - } - - size_t current_position = offset; - - prod_id = extractString(buffer, current_position, PROD_ID_SIZE); - reference_price = - extractBCD_STOUL(buffer, current_position, REFERENCE_PRICE_SIZE); - prod_kind = extractString(buffer, current_position, PROD_KIND_SIZE); - decimal_locator = - extractBCD_STOUL(buffer, current_position, DECIMAL_LOCATOR_SIZE); - strike_price_decimal_locator = extractBCD_STOUL( - buffer, current_position, STRIKE_PRICE_DECIMAL_LOCATOR_SIZE); - begin_date = extractBCDDate(buffer, current_position, BEGIN_DATE_SIZE); - end_date = extractBCDDate(buffer, current_position, END_DATE_SIZE); - flow_group = extractBCD_STOUL(buffer, current_position, FLOW_GROUP_SIZE); - delivery_date = - extractBCDDate(buffer, current_position, DELIVERY_DATE_SIZE); - dynamic_banding = extractBool(buffer, current_position); - - parsedProductInfo = ProductInfo::parseProductID(prod_id); - } - - // Overload the << operator for ProductInfo to print its contents - - // Friend function to overload the << operator for outputting the struct data - friend std::ostream &operator<<(std::ostream &os, const I010Data &data) { - os << "Product ID: " << data.prod_id << '\n' - << "Reference Price: " << data.reference_price << '\n' - << "Product Kind: " << data.prod_kind << '\n' - << "Decimal Locator: " << data.decimal_locator << '\n' - << "Strike Price Decimal Locator: " - << data.strike_price_decimal_locator << '\n' - << "Begin Date: " << data.begin_date << '\n' - << "End Date: " << data.end_date << '\n' - << "Flow Group: " << data.flow_group << '\n' - << "Delivery Date: " << data.delivery_date << '\n' - << "Dynamic Banding: " << (data.dynamic_banding ? 'Y' : 'N') - << "\nParsed Product Info:\n" - << data.parsedProductInfo; - return os; - } - // Overload the << operator for ProductInfo to print its contents - // friend std::ostream &operator<<(std::ostream &os, const ProductInfo &info) { - // os << "Product Type: " << info.productType << '\n' - // << "Product ID: " << info.productID << '\n' - // << "Contract Type: " << info.contractType << '\n' - // << "Expiration Year: " << info.expirationYear << '\n' - // << "Expiration Month: " << info.expirationMonth << '\n' - // << "Is Call: " << (info.isCall ? "Yes" : "No") << '\n' - // << "Strike Price: " << info.strikePrice << '\n' - // << "Is Weekly: " << (info.isWeekly ? "Yes" : "No") << '\n' - // << "Is Spread: " << (info.isSpread ? "Yes" : "No") << '\n' - // << "Spread Second Leg: " << info.spreadSecondLeg; - // return os; - // } -}; - -struct I011Data { - std::string kind_id; // KIND-ID X(4) 4 Contract ID - std::string - chinese_name; // NAME X(30) 30 Contract name contract's Chinese name - std::string - stock_id; // STOCK-ID X(6) 6 Underlying stock ID Only for stock type - unsigned long - contract_size; // CONTRACT-SIZE 9(7)V9(4) 6 Contract size PACK BCD - unsigned int decimal_locator; // DECIMAL-LOCATOR 9(1) 1 Decimals of strike - // price PACK BCD - unsigned int - strike_price_decimal_locator; // STRIKE-PRICE-DECIMAL-LOCATOR 9(1) 1 - // Decimals of strike price PACK BCD - std::string begin_date; // BEGIN-DATE X(8) 8 List date Format: YYYYMMDD Only - // for stock type - - enum CONTRACT_TYPE { // Contract types - INDEX = 1, - INTEREST_RATE, // 2 - BOND, // 3 - COMMODITY, // 4 - STOCK, // 5 - CURRENCY // 6 - } contract_type; - - enum CURRENCY_TYPE { // Currency types - TWD = 1, // Taiwan Dollar - USD, // US Dollar - EUR, // Euro - JPY, // Japanese Yen - GBP, // British Pound - AUD, // Australian Dollar - HKD, // Hong Kong Dollar - CNY // Chinese Yuan - } currency_enum_type; - - enum STATUS_CODE { // Status codes - NORMAL = 'N', - PAUSE = 'P', - UNLISTED = 'U' - } status_code; - - enum EXPIRY_TYPE { // Expiry types - STANDARD = 'S', - WEEKLY = 'W' - } expiry_type; - - enum UNDERLYING_TYPE { // Underlying types - ETF = 'E', - SINGLE_STOCK = 'S' - } underlying_type; - - bool accept_quote_flag; // ACCEPT-QUOTE-FLAG X(1) 1 Quote acceptable? true: - // Yes, false: No - bool block_trade_flag; // BLOCK-TRADE-FLAG X(1) 1 Can block trade? true: - // Yes, false: No - - // Constructor to initialize from a buffer - I011Data( - const std::vector &buffer, - size_t offset = 0, - size_t length = -1) { - const size_t KIND_ID_SIZE = 4; - const size_t CHINESE_NAME_SIZE = 30; - const size_t STOCK_ID_SIZE = 6; - const size_t CONTRACT_SIZE_SIZE = 6; - const size_t DECIMAL_LOCATOR_SIZE = 1; - const size_t STRIKE_PRICE_DECIMAL_LOCATOR_SIZE = 1; - const size_t BEGIN_DATE_SIZE = 8; - - if (buffer.size() < offset + length) { - throw std::out_of_range("Buffer is smaller than the required length"); - } - - size_t current_position = offset; - - kind_id = extractString(buffer, current_position, KIND_ID_SIZE); - chinese_name = extractString(buffer, current_position, CHINESE_NAME_SIZE); - stock_id = extractString(buffer, current_position, STOCK_ID_SIZE); - contract_size = - extractBCD_STOUL(buffer, current_position, CONTRACT_SIZE_SIZE); - status_code = static_cast(buffer[current_position++]); - currency_enum_type = - static_cast(buffer[current_position++]); - decimal_locator = - extractBCD_STOUL(buffer, current_position, DECIMAL_LOCATOR_SIZE); - strike_price_decimal_locator = extractBCD_STOUL( - buffer, current_position, STRIKE_PRICE_DECIMAL_LOCATOR_SIZE); - accept_quote_flag = extractBool(buffer, current_position); - begin_date = extractString(buffer, current_position, BEGIN_DATE_SIZE); - block_trade_flag = extractBool(buffer, current_position); - expiry_type = static_cast(buffer[current_position++]); - underlying_type = - static_cast(buffer[current_position++]); - } - - std::string getCurrencyString() const { - switch (currency_enum_type) { - case TWD: - return "Taiwan Dollar"; - case USD: - return "US Dollar"; - case EUR: - return "Euro"; - case JPY: - return "Japanese Yen"; - case GBP: - return "British Pound"; - case AUD: - return "Australian Dollar"; - case HKD: - return "Hong Kong Dollar"; - case CNY: - return "Chinese Yuan"; - default: - return "Unknown Currency"; - } - } - // Friend function to overload the << operator for outputting the struct - // data - friend std::ostream &operator<<(std::ostream &os, const I011Data &data) { - os << "Kind ID: " << data.kind_id << '\n' - << "Chinese Name: " << data.chinese_name << '\n' - << "Stock ID: " << data.stock_id << '\n' - << "Contract Size: " << data.contract_size << '\n' - << "Status Code: " << static_cast(data.status_code) << '\n' - << "Currency Type: " << static_cast(data.currency_enum_type) - << '\n' - << "Decimal Locator: " << data.decimal_locator << '\n' - << "Strike Price Decimal Locator: " - << data.strike_price_decimal_locator << '\n' - << "Accept Quote Flag: " << (data.accept_quote_flag ? 'Y' : 'N') - << '\n' - << "Begin Date: " << data.begin_date << '\n' - << "Block Trade Flag: " << (data.block_trade_flag ? 'Y' : 'N') << '\n' - << "Expiry Type: " << static_cast(data.expiry_type) << '\n' - << "Underlying Type: " << static_cast(data.underlying_type); - return os; - } -}; - -struct I081Data { - struct MD_ENTRY { - enum Sign { POSITIVE = 0, NEGATIVE = 1 }; - int md_update_action; - char md_entry_type; - Sign sign; - double price; - size_t level; - size_t quantity; - // operator overload for MDentry - friend std::ostream &operator<<( - std::ostream &os, const I081Data::MD_ENTRY &entry) { - os << "MD Update Action: " << entry.md_update_action << "\n" - << "MD Entry Type: " << entry.md_entry_type << "\n" - << "Sign: " - << (entry.sign == I081Data::MD_ENTRY::POSITIVE ? "Positive" - : "Negative") - << "\n" - << "Price: " << entry.price << "\n" - << "Level: " << entry.level << "\n" - << "Quantity: " << entry.quantity << "\n"; - return os; - } - MD_ENTRY(const std::vector &buffer, size_t offset = 0) { - md_update_action = buffer[offset]; - md_entry_type = buffer[offset + 1]; - sign = static_cast(buffer[offset + 2]); - // price - std::string price_str = decodePackBCD(&buffer[offset + 3], 5); - price = std::stod(price_str); - - // quantity - std::string size_str = decodePackBCD(&buffer[offset + 8], 4); - quantity = std::stoul(size_str); - - // level - std::string level_str = decodePackBCD(&buffer[offset + 12], 1); - level = std::stoul(level_str); - } - }; - std::vector entries; - std::string prod_id; - size_t entries_count; - unsigned long seq_number; - // overload that prints dummy values - friend std::ostream &operator<<(std::ostream &os, const I081Data &data) { - os << "Product ID: " << data.prod_id << "\n" - << "Sequence Number: " << data.seq_number << "\n" - << "Entries Count: " << data.entries_count << "\n" - << "MD entries: "; - for (auto entry : data.entries) { - std::cout << " Entry: " << entry; - } - - return os; - } - I081Data( - const std::vector &buffer, const size_t &offset = 0) { - const size_t ENTRIES_COUNT_SIZE = 1; - const size_t PROD_ID_SIZE = 20; - const size_t SEQ_NUMBER_SIZE = 5; - - auto current_position = buffer.begin() + offset; - - prod_id.assign(current_position, current_position + PROD_ID_SIZE); - current_position += PROD_ID_SIZE; - - std::string seq_number_str = - decodePackBCD(&(*current_position), SEQ_NUMBER_SIZE); - seq_number = std::stoul(seq_number_str); - current_position += SEQ_NUMBER_SIZE; - - std::string entries_count_string = - decodePackBCD(&(*current_position), ENTRIES_COUNT_SIZE); - entries_count = std::stoul(entries_count_string); - current_position += ENTRIES_COUNT_SIZE; - // Following fields group repeat NO-MD-ENTRIES times - auto position = PROD_ID_SIZE + SEQ_NUMBER_SIZE + ENTRIES_COUNT_SIZE; - for (size_t i = 0; i < entries_count; ++i) { - entries.push_back(MD_ENTRY(buffer, offset + position)); - position += 13; - // current_position += ENTRIES_COUNT_SIZE;//need to fix - } - } -}; - -struct I083Data { - struct MD_ENTRY { - char md_entry_type; - enum Sign { POSITIVE = 0, NEGATIVE = 1 }; - Sign sign; - double price; - size_t quantity; - size_t level; - - friend std::ostream &operator<<( - std::ostream &os, const I083Data::MD_ENTRY &entry) { - os << "\nMD Entry Type: " << entry.md_entry_type << "\n" - << "Sign: " - << (entry.sign == I083Data::MD_ENTRY::POSITIVE ? "Positive" - : "Negative") - << "\n" - << "Price: " << entry.price << "\n" - << "Quantity: " << entry.quantity << "\n" - << "Level: " << entry.level << "\n"; - return os; - } - - MD_ENTRY(const std::vector &buffer, size_t offset = 0) { - md_entry_type = buffer[offset]; - sign = static_cast(buffer[offset + 1]); - - // price - std::string price_str = decodePackBCD(&buffer[offset + 2], 5); - price = std::stod(price_str); - - // quantity - std::string size_str = decodePackBCD(&buffer[offset + 7], 4); - quantity = std::stoul(size_str); - - // level - std::string level_str = decodePackBCD(&buffer[offset + 11], 1); - level = std::stoul(level_str); - }; - }; - std::vector entries; - std::string prod_id; - unsigned long seq_number; - int calculated_flag; - size_t entries_count; - friend std::ostream &operator<<(std::ostream &os, const I083Data &data) { - os << "Product ID: " << data.prod_id << "\n" - << "Sequence Number: " << data.seq_number << "\n" - << "Calculated Flag: " << data.calculated_flag << "\n" - << "Entries Count: " << data.entries_count << "\n" - << "MD entries: "; - for (auto entry : data.entries) { - std::cout << entry; - } - - return os; - } - - I083Data( - const std::vector &buffer, - const size_t &offset = 0, - size_t length = -1) { - UNUSED(length); - const size_t ENTRIES_COUNT_SIZE = 1; - const size_t PROD_ID_SIZE = 20; - const size_t SEQ_NUMBER_SIZE = 5; - const size_t CALCULATED_FLAG_SIZE = 1; - - auto current_position = buffer.begin() + offset; - - prod_id.assign(current_position, current_position + PROD_ID_SIZE); - current_position += PROD_ID_SIZE; - - std::string seq_number_str = - decodePackBCD(&(*current_position), SEQ_NUMBER_SIZE); - seq_number = std::stoul(seq_number_str); - current_position += SEQ_NUMBER_SIZE; - - calculated_flag = static_cast(*current_position); - current_position += CALCULATED_FLAG_SIZE; - - std::string entries_count_string = - decodePackBCD(&(*current_position), ENTRIES_COUNT_SIZE); - entries_count = std::stoul(entries_count_string); - current_position += ENTRIES_COUNT_SIZE; - - // Following fields group repeat NO-MD-ENTRIES times - auto position = PROD_ID_SIZE + SEQ_NUMBER_SIZE + CALCULATED_FLAG_SIZE + - ENTRIES_COUNT_SIZE; - - for (size_t i = 0; i < entries_count; ++i) { - entries.push_back(MD_ENTRY(buffer, offset + position)); - position += 12; - // current_position += ENTRIES_COUNT_SIZE;//need to fix - } - } -}; - -bool readBinaryFile( - const std::string &file_name, - std::shared_ptr listener, - std::shared_ptr sec_id_store, - std::shared_ptr security_details) { - std::ifstream file(file_name, std::ios::binary); - UNUSED(listener); - if (!file) { - std::cerr << "Failed to open file: " << file_name << std::endl; - assert(false); - } - std::vector buffer(BUFFER_SIZE); - const auto remove_spaces = [](const std::string &name) { - std::string removed = ""; - const char space = ' '; - for (auto c : name) { - if (c != space) { - removed += c; - } - } - return removed; - }; - while (file.read((reinterpret_cast(buffer.data())), BUFFER_SIZE)) { - // printBuffer(buffer, 0, 20); - size_t position = 0; - // there needs to be atleast 19 bytes left in buffer to read a complete - // header - size_t counter = 0; - size_t hits = 0; - const size_t hits_limit = 5; - const size_t limit = 10000; - std::unordered_set names; - - while (position < BUFFER_SIZE - 19 && counter < limit && - hits < hits_limit) { - auto Header = Header_Fields(buffer, position); - // printBuffer(buffer, position, - // Header.Body_Length + HEADER_SIZE + FOOTER_SIZE); // - // UNCOMMENT TO PRINT HEX VALUES OF MESSAGE - - // HEADER VALUE - switch (Header.message_type.identifier) { - case MessageIdentifier::I024: { - // printBuffer(buffer, position, - // Header.Body_Length + HEADER_SIZE + FOOTER_SIZE); - //std::cout << std::endl << std::endl; - //std::cout << "Header: " << Header << std::endl; // UNCOMMENT TO PRINT - - auto i024_message = I024Data( - buffer, position + HEADER_SIZE, - Header.Body_Length + FOOTER_SIZE); - break; - //std::cout << i024_message << std::endl; - // char c = 0b10000000; - // assert((int)i024_message.match_display_item == c); - // hits++; - } - - case MessageIdentifier::I010: { - // std::cout << "we are looking for this!" << std::endl; - auto i010_message = I010Data( - buffer, position + HEADER_SIZE, - Header.Body_Length + FOOTER_SIZE); - - const auto id = remove_spaces(i010_message.prod_id); - const auto symbol = id.substr(0, 2); - bts::domain::SecurityID sec_id{ - sec_id_store->get_or_add(api::domain::VENUE_TAIFEX, id)}; - security_details->add_i010_mapping( - id, sec_id, i010_message.decimal_locator); - // std::ostringstream oss; - // oss <<"\nHeader: \n"<to_string()); - std::vector complete_security_list; - bts::domain::Security &sec = complete_security_list.emplace_back(); - sec.security_common.venue = bts::api::domain::VENUE_TAIFEX; - sec.security_common.id = sec_id; - sec.security_common.exchange_sec_id = id; // Need to fix this - sec.security_common.desc = id; - sec.security_common.symbol = symbol; - sec.security_common.asset = id; - sec.security_common.group = id; - sec.security_common.min_price_increment = security_details->get_min_inc(id); - sec.security_common.min_quantity = security_details->get_min_inc(id); - sec.security_common.min_quantity_increment = security_details->get_min_inc(id); - sec.security_common.currency = security_details->get_currency(id); - switch (i010_message.parsedProductInfo.productType) { - - case I010Data::ProductInfo::ProductType::FUTURES: { - auto &t = sec.security.emplace(); - auto toISODate = [](const std::string &date) { - return date.substr(0, 4) + "-" + date.substr(4, 2) + "-" + - date.substr(6, 2); - }; - t.expiration = bts::core::TimeStamp::from_iso_string( - toISODate(i010_message.end_date)); - - break; - } - - case I010Data::ProductInfo::ProductType::OPTIONS: { - auto &t = sec.security.emplace(); - std::tm tm = {}; - std::istringstream iss(i010_message.end_date); - iss >> std::get_time(&tm, "%Y%m%d"); - std::time_t time = std::mktime(&tm); - t.expiration = bts::core::TimeStamp(static_cast(time)); - t.strike = domain::Price::from_double( - i010_message.parsedProductInfo.strikePrice); - break; - } - } - - std::vector const_security_list; - for (const auto &security : complete_security_list) { - const_security_list.push_back(&security); - } - listener->on_securities(const_security_list); - break; - } - - case MessageIdentifier::I011: { - // std::cout << "we are looking for this!" << std::endl; - auto i011_message = I011Data( - buffer, position + HEADER_SIZE, - Header.Body_Length + FOOTER_SIZE); - const auto id = remove_spaces(i011_message.kind_id); - security_details->add_i011_mapping(id, i011_message.contract_size, i011_message.getCurrencyString()); - // bts::domain::SecurityID sec_id{ - // sec_id_store->get_or_add(api::domain::VENUE_TAIFEX, i011_message.kind_id)}; - // std::vector complete_security_list; - // bts::domain::Security &sec = complete_security_list.emplace_back(); - // sec.security_common.venue = bts::api::domain::VENUE_TAIFEX; - // // sec.security_common.id = sec_id; - // sec.security_common.exchange_sec_id = i011_message.kind_id; // Need to fix this - // sec.security_common.desc = i011_message.kind_id; - // sec.security_common.symbol = i011_message.kind_id; - // sec.security_common.asset = i011_message.kind_id; - // sec.security_common.group = i011_message.kind_id; - // sec.security_common.min_price_increment = 0.1; - // sec.security_common.min_quantity = 1; - // sec.security_common.min_quantity_increment = 0.1; - // sec.security_common.currency = i011_message.getCurrencyString(); - // switch(i011_message.contract_type){ - - // case I011Data::STOCK: - // case I011Data::INDEX: - // case I011Data::INTEREST_RATE: - // case I011Data::BOND: - // case I011Data::COMMODITY: - // case I011Data::CURRENCY: - // break; - // } - // auto &t = sec.security.emplace(); - // t.expiration = exp_time; - // std::vector const_security_list; - // for (const auto &security : complete_security_list) { - // const_security_list.push_back(&security); - // } - // listner->on_securities(const_security_list); - - // std::cout << i011_message << std::endl; - break; - } - case MessageIdentifier::I083: { - auto i083_message = I083Data( - buffer, position + HEADER_SIZE, - Header.Body_Length + FOOTER_SIZE); - auto sec_id = security_details->get_sec_id( - remove_spaces(i083_message.prod_id)); - auto dec_loc = security_details->get_dec_loc( - remove_spaces(i083_message.prod_id)); - LOG(md, Error, "XSEC: {}", i083_message.prod_id); - if (!sec_id.has_value() || !dec_loc.has_value()) { - continue; - } - domain::Book book; - auto &bids = book.bids(); - auto &asks = book.asks(); - book.set_security_id(sec_id.value()); - - for (const auto &entry : i083_message.entries) { - bts::domain::Price price( - entry.price * - pow(10, - 9 - dec_loc - .value())); // Assuming the price needs to be adjusted by a factor of -2 - bts::domain::Quantity quantity(entry.quantity); - // Process each MD_ENTRY - if (entry.md_entry_type == '0' || - entry.md_entry_type == 'E') { // Buy or derived buy - // Update the corresponding bid level - if (entry.level <= bids.size()) { - bids[entry.level - 1].price = price; - bids[entry.level - 1].total_quantity = quantity; - } - } else if ( - entry.md_entry_type == '1' || - entry.md_entry_type == 'F') { // Sell or derived sell - // Update the corresponding ask level - if (entry.level <= asks.size()) { - asks[entry.level - 1].price = price; - asks[entry.level - 1].total_quantity = quantity; - } - } - } - - std::string book_deets = - "Top bid price: " + std::to_string(bids[0].price.to_double()) + - " Top bid size: " + - std::to_string(bids[0].total_quantity.value()) + - " Top ask price: " + std::to_string(asks[0].price.to_double()) + - " Top ask size: " + - std::to_string(asks[0].total_quantity.value()) + - " Bid levels: " + std::to_string(bids.size()) + - " Ask levels: " + std::to_string(asks.size()); - - listener->on_book(book); - - hits++; - break; - } - - default: { - // std::cout << "Case not Handled!" << std::endl; - } - } - position += Header.Body_Length + HEADER_SIZE + FOOTER_SIZE; - // assert(Header.message_type.identifier != MessageIdentifier::I024); - counter++; - } - - return false; - } - return true; -} - -//const std::string &filename, -void bts::md::taifex::TaifexDatahandler::run( - bool use_file, - std::shared_ptr listner, - std::shared_ptr sec_id_store) { - std::string reference_file_name = "/reference_data_20240806_1"; - std::string realtime_file_name = "/real_time_data_20240806_318"; - std::shared_ptr sec_details = - std::make_shared(); - if (use_file) { - std::string base_path = - config::get().data_path(); - readBinaryFile( - base_path + reference_file_name, listner, sec_id_store, sec_details); - readBinaryFile( - base_path + realtime_file_name, listner, sec_id_store, sec_details); - } - // bts_assert_msg(false, "inside run taifex"); -} - -} //namespace bts::md::taifex diff --git a/src/server/sparkd/md/taifex/TaifexMessages.h b/src/server/sparkd/md/taifex/TaifexMessages.h new file mode 100644 index 000000000..f50d336e5 --- /dev/null +++ b/src/server/sparkd/md/taifex/TaifexMessages.h @@ -0,0 +1,1049 @@ +#include "TaifexUtils.h" +#include "lib/utils/bts_assert.h" +#include "lib/utils/helper_macros.h" +#include +#include +#include +#include +#include +namespace bts::md::taifex { +class TaifexMessages { + public: + struct MessageIdentifier { + enum MessageID { + I010 = 1, + I030 = 2, + I011 = 3, + I050 = 4, + I060 = 5, + I120 = 6, + I130 = 7, + I064 = 8, + I012 = 9, + I083 = 10, + I140 = 11, + I110 = 12, + I014 = 13, + I024 = 14, + I025 = 15, + I100 = 16, + I081 = 17, // Add I081 + I084 = 18, // Add I084 + I072 = 19, // Add I072 + I071 = 20, // Add I071 + I073 = 21, // Add I073 + I070 = 22, + I001 = 23, + I002 = 24, + I999 = 0 // unknown + }; + static std::string messageIDToString(MessageID id) { + switch (id) { + case I010: + return "I010"; + case I030: + return "I030"; + case I011: + return "I011"; + case I050: + return "I050"; + case I060: + return "I060"; + case I120: + return "I120"; + case I130: + return "I130"; + case I064: + return "I064"; + case I012: + return "I012"; + case I083: + return "I083"; + case I140: + return "I140"; + case I110: + return "I110"; + case I014: + return "I014"; + case I024: + return "I024"; + case I025: + return "I025"; + case I100: + return "I100"; + case I081: + return "I081"; + case I084: + return "I084"; + case I072: + return "I072"; + case I071: + return "I071"; + case I073: + return "I073"; + case I070: + return "I070"; + case I001: + return "I001"; + case I002: + return "I002"; + default: + return "Unknown"; + } + } + void set_identifier_description( + const unsigned char transmissionCode, + const unsigned char messageKind) { + switch (transmissionCode) { + case '0': + switch (messageKind) { + case '1': + identifier = I001; + description = "Heartbeat"; + break; + case '2': + identifier = I002; + description = "Reset message"; + break; + default: + identifier = I999; + description = "unknown"; + break; + } + break; + case '1': + switch (messageKind) { + case '1': + identifier = I010; + description = "Product basic data"; + break; + case '2': + identifier = I030; + description = "Sum of order data"; + break; + case '3': + identifier = I011; + description = "Contract basic data"; + break; + case '4': + identifier = I050; + description = "System message"; + break; + case '5': + identifier = I060; + description = "Underlying index or stock reference data"; + break; + case '6': + identifier = I120; + description = "Reference of stock or underlying index"; + break; + case '7': + identifier = I130; + description = "Contract Adjustment"; + break; + case '8': + identifier = I064; + description = + "Calculated opening and closing price for underlying stocks"; + break; + case 'A': + identifier = I012; + description = "Price limits"; + break; + default: + identifier = I999; + description = "unknown"; + break; + } + break; + case '2': + switch (messageKind) { + case 'B': + identifier = I083; + description = "Snapshot order book"; + break; + case '3': + identifier = I140; + description = "System message"; + break; + case '4': + identifier = I100; + description = "Closing market data (settlement price included)"; + break; + case 'A': + identifier = I081; + description = "Aggregated order book"; + break; + case 'C': + identifier = I084; + description = "Market data snapshot refresh"; + break; + case 'D': + identifier = I024; + description = "Matched prices and quantities"; + break; + case 'E': + identifier = I025; + description = "Closing market data"; + break; + default: + identifier = I999; + description = "unknown"; + break; + } + break; + case '3': + switch (messageKind) { + case '3': + identifier = I072; + description = "Closing market data"; + break; + case '1': + identifier = I070; + description = "Closing market data"; + break; + case '2': + identifier = I071; + description = "Closing market data with settlement price"; + break; + case '4': + identifier = I073; + description = "Combination product closing market data"; + break; + default: + identifier = I999; + description = "unknown"; + break; + } + break; + default: + identifier = I999; + description = "unknown"; + break; + } + } + MessageIdentifier( + const unsigned char transmissionCode, const unsigned char messageKind) + : transmissionCode(transmissionCode), messageKind(messageKind) { + set_identifier_description(transmissionCode, messageKind); + } + unsigned char transmissionCode; + unsigned char messageKind; + MessageID identifier; + std::string description; + friend std::ostream &operator<<( + std::ostream &os, const MessageIdentifier &MI) { + os << "TransmissionCode: " << MI.transmissionCode + << "\nMessageKind: " << MI.messageKind + << "\nDescription: " << MI.description << "\nidentifier: " + << MessageIdentifier::messageIDToString(MI.identifier); + return os; + } + }; + + struct Header_Fields { + uint8_t Esc_Code; // 1 byte + MessageIdentifier message_type; + std::string Information_Time; + int Channel_Id; + unsigned long Channel_Seq; + uint8_t Version_No; + uint Body_Length; + bool valid = false; + Header_Fields( + const std::vector &buffer, const size_t &offset) + : Esc_Code(buffer[offset]), + message_type(buffer[offset + 1], buffer[offset + 2]) { + // creates header feild struct + // and populates all fields + // Header_Fields header; + // Read single-byte fields + if(message_type.identifier == MessageIdentifier::MessageID::I999){ + valid = false; + return; + } + // Read 2 bytes for Body_Length + unsigned char bl[2] = {buffer[offset + 17], buffer[offset + 18]}; + Body_Length = std::stoul(TaifexUtils::decodePackBCD(bl, 2)); + // / Extract Channel_Seq + size_t channel_seq_offset = offset + 11; // Starting at 11 bytes from offset + + Channel_Seq = TaifexUtils::extractBCD_STOUL(buffer,channel_seq_offset,5); + + valid = Channel_Seq!=0; + } + + friend std::ostream &operator<<( + std::ostream &os, const Header_Fields &hf) { + os << "Esc_Code: " << static_cast(hf.Esc_Code) << "\n" + << hf.message_type + << "\n" + // << "Information_Time: " << hf.Information_Time << "\n" + // << "Channel_Id: " << hf.Channel_Id << "\n" + // << "Channel_Seq: " << hf.Channel_Seq << "\n" + // << "Version_No: " << static_cast(hf.Version_No) << "\n" + << "Body_Length: " << hf.Body_Length << "\n" + << "Valid: " << (hf.valid ? "true" : "false"); + return os; + } + }; + + struct I024Data { + struct trade { + enum Sign { POSITIVE = 0, NEGATIVE = 1 }; + Sign sign; + double match_price; // need to determine type(appendix 2) + float match_qty; // keeping str for simplicity + + trade( + const std::vector &buffer, + const size_t &offset = 0, + const size_t match_qty_size = 2) { + const size_t SIGN_SIZE = 1; + const size_t MATCH_PRICE_SIZE = 5; + const size_t MATCH_QTY_SIZE = match_qty_size; + auto current_position = offset; + // Extract Sign + sign = (buffer[current_position] == '0') ? POSITIVE : NEGATIVE; + current_position += SIGN_SIZE; + + match_price = std::stod(TaifexUtils::decodePackBCD( + buffer.data() + current_position, MATCH_PRICE_SIZE)); + current_position += MATCH_PRICE_SIZE; + + match_qty = std::stof(TaifexUtils::extractBCD_STRING( + buffer, current_position, MATCH_QTY_SIZE)); + } + friend std::ostream &operator<<(std::ostream &os, const trade &data) { + os << "Sign: " + << (data.sign == Sign::POSITIVE ? "Positive" : "Negative") + << '\n' + << "Match Price: " << data.match_price << '\n' + << "Match Quantity: " << data.match_qty << '\n'; + return os; + } + }; + std::string prod_id; + unsigned long sequence_number; + bool calculated_flag; + std::string match_time; // make another struct for time? + char match_display_item; // need to discuss + std::vector trades; + // next fields to add + std::string match_total_qty; + std::string match_buy_count; + std::string match_sell_count; + I024Data( + const std::vector &buffer, + const size_t &offset = 0, + const size_t &length = -1) { + const size_t PROD_ID_SIZE = 20; + const size_t SEQ_NUMBER_SIZE = 5; + const size_t CALCULATED_FLAG = 1; + const size_t MATCH_TIME = 6; + const size_t MATCH_DISPLAY_ITEM_SIZE = 1; + const size_t TRADE_SIZE = 8; + const size_t MATCH_TOTAL_QTY_SIZE = 4; + const size_t MATCH_BUY_COUNT_SIZE = 4; + const size_t MATCH_SELL_COUNT_SIZE = 4; + const size_t FIRST_MATCH_QTY_SIZE = 4; + if (buffer.size() < offset + length) { + throw std::out_of_range( + "Buffer is smaller than the required length"); + } + // do we need this? + size_t current_position = offset; + prod_id = + TaifexUtils::extractString(buffer, current_position, PROD_ID_SIZE); + + sequence_number = TaifexUtils::extractBCD_STOUL( + buffer, current_position, SEQ_NUMBER_SIZE); + + // Extract Calculated Flag + std::string calculated_flag_str = TaifexUtils::extractString( + buffer, current_position, CALCULATED_FLAG); + calculated_flag = (calculated_flag_str[0] == '1'); + + // Extract Match Time + match_time = TaifexUtils::time_decodePackBCD( + buffer.data() + current_position, MATCH_TIME); + //match_time = TaifexUtils::convertToISO(match_time); + //match_time = sanitizeISOString(match_time); + ; // extractBCD(buffer, current_position, MATCH_TIME); + current_position += MATCH_TIME; + trades.push_back( + trade(buffer, current_position, FIRST_MATCH_QTY_SIZE)); + current_position += TRADE_SIZE + 2; + // Extract Match Display Item + auto getFirstBitAndRemainingValue = + [](char input) -> std::tuple { + bool firstBit = (input & 0b10000000) != 0; + int remainingValue = input & 0b01111111; + return std::make_tuple(firstBit, remainingValue); + }; + match_display_item = buffer[current_position]; + current_position += MATCH_DISPLAY_ITEM_SIZE; + + auto [new_message, trades_count] = + getFirstBitAndRemainingValue(match_display_item); + // assert(new_message); + for (int i = 0; i < trades_count; i++) { + trades.push_back(trade(buffer, current_position)); + current_position += TRADE_SIZE; + } + // match quantity + match_total_qty = TaifexUtils::extractBCD_STRING( + buffer, current_position, MATCH_TOTAL_QTY_SIZE); + // match buy count + match_buy_count = TaifexUtils::extractBCD_STRING( + buffer, current_position, MATCH_BUY_COUNT_SIZE); + // match sell count + match_sell_count = TaifexUtils::extractBCD_STRING( + buffer, current_position, MATCH_SELL_COUNT_SIZE); + std::cout << "trades count: " << trades_count << std::endl; + assert( + buffer[current_position + 1] == 0x0D && + buffer[current_position + 2] == 0x0A); + } + // 833 251 1142 + friend std::ostream &operator<<(std::ostream &os, const I024Data &data) { + os << "Product ID: " << data.prod_id << '\n' + << "Sequence Number: " << data.sequence_number << '\n' + << "Calculated Flag: " << (data.calculated_flag ? '1' : '0') << '\n' + << "Match Time: " << data.match_time << '\n' + << "Match Display Item: " + << std::bitset<8>{static_cast( + data.match_display_item)} + << "\n"; // Output as integer to show value + + for (auto t : data.trades) { + os << "Trade: " << t << "\n"; + } + + os << "Match Total Quantity: " << data.match_total_qty << '\n' + << "Match Buy Count: " << data.match_buy_count << '\n' + << "Match Sell Count: " << data.match_sell_count << '\n'; + return os; + } + }; + + struct I010Data { + std::string prod_id; // PROD-ID-S X(10) 10 Product ID + unsigned long + reference_price; // REFERENCE-PRICE 9(9) 5 Reference price PACK BCD + std::string prod_kind; // PROD-KIND X(1) 1 Type of contract + unsigned int decimal_locator; // DECIMAL-LOCATOR 9(1) 1 Number of decimal + // digits in price fields PACK BCD + unsigned int + strike_price_decimal_locator; // STRIKE-PRICE-DECIMAL-LOCATOR 9(1) 1 + // Number of decimal digits in strike price + // of options product PACK BCD + std::string + begin_date; // BEGIN-DATE 9(8) 4 Listed date of product (YYYYMMDD) + // PACK BCD + std::string + end_date; // END-DATE 9(8) 4 Expiry date of product (YYYYMMDD) PACK BCD + unsigned int flow_group; // FLOW-GROUP 9(2) 1 Flow group PACK BCD + std::string + delivery_date; // DELIVERY-DATE 9(8) 4 Delivery date of product PACK BCD + bool + dynamic_banding; // DYNAMIC-BANDING X(1) 1 Is dynamic banding applicable? + // Y: Yes, N: No + + // Embedded ProductInfo struct + struct ProductInfo { + enum class ProductType { FUTURES, OPTIONS } productType; + + std::string productID; + int expirationYear; + int expirationMonth; + bool isCall; + double strikePrice; + bool isWeekly; + bool isSpread; + std::string spreadSecondLeg; + + // Convert month code to month number + static int getMonthFromCode(char code) { + if (code >= 'A' && code <= 'L') + return code - 'A' + + 1; // 'A' corresponds to 1 (January), 'B' to 2, ..., 'L' to 12 (December) + throw std::runtime_error("Invalid month code"); + } + + // Method to parse Product ID and initialize ProductInfo + static ProductInfo parseProductID(const std::string &prodID) { + ProductInfo info; + + if (prodID.length() == 10 || prodID.length() == 20) { + // Futures product parsing + info.productType = ProductType::FUTURES; + info.productID = prodID.substr(0, 3); + info.expirationMonth = getMonthFromCode(prodID[3]); + info.expirationYear = + 2020 + (prodID[4] - + '0'); // Assuming the year is between 2020 and 2029 + info.isWeekly = prodID[2] >= '1' && + prodID[2] <= '5'; // Weekly expired contract + info.isSpread = prodID.length() > 10; // Check if it's a spread + if (info.isSpread) { + info.spreadSecondLeg = prodID.substr( + 11, 6); // Parsing the second leg of the spread + } + } else if (prodID.length() == 11) { + // Weekly time spread product parsing + info.productType = ProductType::FUTURES; + info.isWeekly = true; + info.isSpread = true; + info.productID = prodID.substr(0, 3); + info.expirationMonth = getMonthFromCode(prodID[3]); + info.expirationYear = 2020 + (prodID[4] - '0'); + info.spreadSecondLeg = prodID.substr(6, 5); + } else if (prodID.length() == 12) { + // Options product parsing + info.productType = ProductType::OPTIONS; + info.productID = prodID.substr(0, 3); + info.strikePrice = std::stod( + prodID.substr(3, 5)); // Assuming no decimal point for now + info.isCall = + prodID[8] >= 'A' && prodID[8] <= 'L'; // Call options + info.expirationMonth = getMonthFromCode(prodID[8]); + info.expirationYear = 2020 + (prodID[9] - '0'); + } else { + throw std::invalid_argument("Invalid Product ID length"); + } + + return info; + } + + // Overload the << operator to print ProductInfo + friend std::ostream &operator<<( + std::ostream &os, const ProductInfo &info) { + os << "Product Type: " + << (info.productType == ProductType::FUTURES ? "Futures" + : "Options") + << '\n' + << "Product ID: " << info.productID << '\n' + << "Expiration Month: " << info.expirationMonth << " (" + << (info.expirationMonth == 1 ? "January" + : info.expirationMonth == 2 ? "February" + : info.expirationMonth == 3 ? "March" + : info.expirationMonth == 4 ? "April" + : info.expirationMonth == 5 ? "May" + : info.expirationMonth == 6 ? "June" + : info.expirationMonth == 7 ? "July" + : info.expirationMonth == 8 ? "August" + : info.expirationMonth == 9 ? "September" + : info.expirationMonth == 10 ? "October" + : info.expirationMonth == 11 ? "November" + : info.expirationMonth == 12 ? "December" + : "Unknown") + << ")\n" + << "Expiration Year: " << info.expirationYear << '\n' + << "Strike Price: " << info.strikePrice << '\n' + << "Is Weekly: " << (info.isWeekly ? "Yes" : "No") << '\n' + << "Is Call: " << (info.isCall ? "Yes" : "No") << '\n' + << "Is Spread: " << (info.isSpread ? "Yes" : "No") << '\n'; + if (info.isSpread) { + os << "Spread Second Leg: " << info.spreadSecondLeg << '\n'; + } + return os; + } + } parsedProductInfo; + // Constructor to initialize from a buffer + I010Data( + const std::vector &buffer, + size_t offset = 0, + size_t length = -1) { + const size_t PROD_ID_SIZE = 10; + const size_t REFERENCE_PRICE_SIZE = 5; + const size_t PROD_KIND_SIZE = 1; + const size_t DECIMAL_LOCATOR_SIZE = 1; + const size_t STRIKE_PRICE_DECIMAL_LOCATOR_SIZE = 1; + const size_t BEGIN_DATE_SIZE = 4; + const size_t END_DATE_SIZE = 4; + const size_t FLOW_GROUP_SIZE = 1; + const size_t DELIVERY_DATE_SIZE = 4; + // const size_t DYNAMIC_BANDING_SIZE = 1; + + // Parse ProductInfo using the extracted product ID + // parsedProductInfo = ProductInfo::parseProductID(prod_id, strike_price_decimal_locator); + + if (buffer.size() < offset + length) { + throw std::out_of_range( + "Buffer is smaller than the required length"); + } + + size_t current_position = offset; + + prod_id = + TaifexUtils::extractString(buffer, current_position, PROD_ID_SIZE); + reference_price = TaifexUtils::extractBCD_STOUL( + buffer, current_position, REFERENCE_PRICE_SIZE); + prod_kind = TaifexUtils::extractString( + buffer, current_position, PROD_KIND_SIZE); + decimal_locator = TaifexUtils::extractBCD_STOUL( + buffer, current_position, DECIMAL_LOCATOR_SIZE); + strike_price_decimal_locator = TaifexUtils::extractBCD_STOUL( + buffer, current_position, STRIKE_PRICE_DECIMAL_LOCATOR_SIZE); + begin_date = TaifexUtils::extractBCDDate( + buffer, current_position, BEGIN_DATE_SIZE); + end_date = TaifexUtils::extractBCDDate( + buffer, current_position, END_DATE_SIZE); + flow_group = TaifexUtils::extractBCD_STOUL( + buffer, current_position, FLOW_GROUP_SIZE); + delivery_date = TaifexUtils::extractBCDDate( + buffer, current_position, DELIVERY_DATE_SIZE); + dynamic_banding = TaifexUtils::extractBool(buffer, current_position); + + parsedProductInfo = ProductInfo::parseProductID(prod_id); + } + + // Overload the << operator for ProductInfo to print its contents + + // Friend function to overload the << operator for outputting the struct data + friend std::ostream &operator<<(std::ostream &os, const I010Data &data) { + os << "Product ID: " << data.prod_id << '\n' + << "Reference Price: " << data.reference_price << '\n' + << "Product Kind: " << data.prod_kind << '\n' + << "Decimal Locator: " << data.decimal_locator << '\n' + << "Strike Price Decimal Locator: " + << data.strike_price_decimal_locator << '\n' + << "Begin Date: " << data.begin_date << '\n' + << "End Date: " << data.end_date << '\n' + << "Flow Group: " << data.flow_group << '\n' + << "Delivery Date: " << data.delivery_date << '\n' + << "Dynamic Banding: " << (data.dynamic_banding ? 'Y' : 'N') + << "\nParsed Product Info:\n" + << data.parsedProductInfo; + return os; + } + // Overload the << operator for ProductInfo to print its contents + // friend std::ostream &operator<<(std::ostream &os, const ProductInfo &info) { + // os << "Product Type: " << info.productType << '\n' + // << "Product ID: " << info.productID << '\n' + // << "Contract Type: " << info.contractType << '\n' + // << "Expiration Year: " << info.expirationYear << '\n' + // << "Expiration Month: " << info.expirationMonth << '\n' + // << "Is Call: " << (info.isCall ? "Yes" : "No") << '\n' + // << "Strike Price: " << info.strikePrice << '\n' + // << "Is Weekly: " << (info.isWeekly ? "Yes" : "No") << '\n' + // << "Is Spread: " << (info.isSpread ? "Yes" : "No") << '\n' + // << "Spread Second Leg: " << info.spreadSecondLeg; + // return os; + // } + }; + + struct I011Data { + std::string kind_id; // KIND-ID X(4) 4 Contract ID + std::string + chinese_name; // NAME X(30) 30 Contract name contract's Chinese name + std::string + stock_id; // STOCK-ID X(6) 6 Underlying stock ID Only for stock type + unsigned long + contract_size; // CONTRACT-SIZE 9(7)V9(4) 6 Contract size PACK BCD + unsigned int decimal_locator; // DECIMAL-LOCATOR 9(1) 1 Decimals of strike + // price PACK BCD + unsigned int + strike_price_decimal_locator; // STRIKE-PRICE-DECIMAL-LOCATOR 9(1) 1 + // Decimals of strike price PACK BCD + std::string + begin_date; // BEGIN-DATE X(8) 8 List date Format: YYYYMMDD Only + // for stock type + + enum CONTRACT_TYPE { // Contract types + INDEX = 1, + INTEREST_RATE, // 2 + BOND, // 3 + COMMODITY, // 4 + STOCK, // 5 + CURRENCY // 6 + } contract_type; + + enum CURRENCY_TYPE { // Currency types + TWD = 1, // Taiwan Dollar + USD, // US Dollar + EUR, // Euro + JPY, // Japanese Yen + GBP, // British Pound + AUD, // Australian Dollar + HKD, // Hong Kong Dollar + CNY // Chinese Yuan + } currency_enum_type; + + enum STATUS_CODE { // Status codes + NORMAL = 'N', + PAUSE = 'P', + UNLISTED = 'U' + } status_code; + + enum EXPIRY_TYPE { // Expiry types + STANDARD = 'S', + WEEKLY = 'W' + } expiry_type; + + enum UNDERLYING_TYPE { // Underlying types + ETF = 'E', + SINGLE_STOCK = 'S' + } underlying_type; + + bool + accept_quote_flag; // ACCEPT-QUOTE-FLAG X(1) 1 Quote acceptable? true: + // Yes, false: No + bool block_trade_flag; // BLOCK-TRADE-FLAG X(1) 1 Can block trade? true: + // Yes, false: No + + // Constructor to initialize from a buffer + I011Data( + const std::vector &buffer, + size_t offset = 0, + size_t length = -1) { + const size_t KIND_ID_SIZE = 4; + const size_t CHINESE_NAME_SIZE = 30; + const size_t STOCK_ID_SIZE = 6; + const size_t CONTRACT_SIZE_SIZE = 6; + const size_t DECIMAL_LOCATOR_SIZE = 1; + const size_t STRIKE_PRICE_DECIMAL_LOCATOR_SIZE = 1; + const size_t BEGIN_DATE_SIZE = 8; + + if (buffer.size() < offset + length) { + throw std::out_of_range( + "Buffer is smaller than the required length"); + } + + size_t current_position = offset; + + kind_id = + TaifexUtils::extractString(buffer, current_position, KIND_ID_SIZE); + chinese_name = TaifexUtils::extractString( + buffer, current_position, CHINESE_NAME_SIZE); + stock_id = TaifexUtils::extractString( + buffer, current_position, STOCK_ID_SIZE); + contract_size = TaifexUtils::extractBCD_STOUL( + buffer, current_position, CONTRACT_SIZE_SIZE); + status_code = static_cast(buffer[current_position++]); + currency_enum_type = + static_cast(buffer[current_position++]); + decimal_locator = TaifexUtils::extractBCD_STOUL( + buffer, current_position, DECIMAL_LOCATOR_SIZE); + strike_price_decimal_locator = TaifexUtils::extractBCD_STOUL( + buffer, current_position, STRIKE_PRICE_DECIMAL_LOCATOR_SIZE); + accept_quote_flag = TaifexUtils::extractBool(buffer, current_position); + begin_date = TaifexUtils::extractString( + buffer, current_position, BEGIN_DATE_SIZE); + block_trade_flag = TaifexUtils::extractBool(buffer, current_position); + expiry_type = static_cast(buffer[current_position++]); + underlying_type = + static_cast(buffer[current_position++]); + } + + std::string getCurrencyString() const { + switch (currency_enum_type) { + case TWD: + return "Taiwan Dollar"; + case USD: + return "US Dollar"; + case EUR: + return "Euro"; + case JPY: + return "Japanese Yen"; + case GBP: + return "British Pound"; + case AUD: + return "Australian Dollar"; + case HKD: + return "Hong Kong Dollar"; + case CNY: + return "Chinese Yuan"; + default: + return "Unknown Currency"; + } + } + // Friend function to overload the << operator for outputting the struct + // data + friend std::ostream &operator<<(std::ostream &os, const I011Data &data) { + os << "Kind ID: " << data.kind_id << '\n' + << "Chinese Name: " << data.chinese_name << '\n' + << "Stock ID: " << data.stock_id << '\n' + << "Contract Size: " << data.contract_size << '\n' + << "Status Code: " << static_cast(data.status_code) << '\n' + << "Currency Type: " << static_cast(data.currency_enum_type) + << '\n' + << "Decimal Locator: " << data.decimal_locator << '\n' + << "Strike Price Decimal Locator: " + << data.strike_price_decimal_locator << '\n' + << "Accept Quote Flag: " << (data.accept_quote_flag ? 'Y' : 'N') + << '\n' + << "Begin Date: " << data.begin_date << '\n' + << "Block Trade Flag: " << (data.block_trade_flag ? 'Y' : 'N') + << '\n' + << "Expiry Type: " << static_cast(data.expiry_type) << '\n' + << "Underlying Type: " << static_cast(data.underlying_type); + return os; + } + }; + + struct I081Data { + struct MD_ENTRY { + enum Sign { POSITIVE = 0, NEGATIVE = 1 }; + int md_update_action; + char md_entry_type; + Sign sign; + double price; + size_t level; + size_t quantity; + // operator overload for MDentry + friend std::ostream &operator<<( + std::ostream &os, const I081Data::MD_ENTRY &entry) { + os << "MD Update Action: " << entry.md_update_action << "\n" + << "MD Entry Type: " << entry.md_entry_type << "\n" + << "Sign: " + << (entry.sign == I081Data::MD_ENTRY::POSITIVE ? "Positive" + : "Negative") + << "\n" + << "Price: " << entry.price << "\n" + << "Level: " << entry.level << "\n" + << "Quantity: " << entry.quantity << "\n"; + return os; + } + MD_ENTRY(const std::vector &buffer, size_t offset = 0) { + md_update_action = buffer[offset]; + md_entry_type = buffer[offset + 1]; + sign = static_cast(buffer[offset + 2]); + // price + std::string price_str = + TaifexUtils::decodePackBCD(&buffer[offset + 3], 5); + price = std::stod(price_str); + + // quantity + std::string size_str = + TaifexUtils::decodePackBCD(&buffer[offset + 8], 4); + quantity = std::stoul(size_str); + + // level + std::string level_str = + TaifexUtils::decodePackBCD(&buffer[offset + 12], 1); + level = std::stoul(level_str); + } + }; + std::vector entries; + std::string prod_id; + size_t entries_count; + unsigned long seq_number; + // overload that prints dummy values + friend std::ostream &operator<<(std::ostream &os, const I081Data &data) { + os << "Product ID: " << data.prod_id << "\n" + << "Sequence Number: " << data.seq_number << "\n" + << "Entries Count: " << data.entries_count << "\n" + << "MD entries: "; + for (auto entry : data.entries) { + std::cout << " Entry: " << entry; + } + + return os; + } + I081Data( + const std::vector &buffer, const size_t &offset = 0) { + const size_t ENTRIES_COUNT_SIZE = 1; + const size_t PROD_ID_SIZE = 20; + const size_t SEQ_NUMBER_SIZE = 5; + + auto current_position = buffer.begin() + offset; + + prod_id.assign(current_position, current_position + PROD_ID_SIZE); + current_position += PROD_ID_SIZE; + + std::string seq_number_str = + TaifexUtils::decodePackBCD(&(*current_position), SEQ_NUMBER_SIZE); + seq_number = std::stoul(seq_number_str); + current_position += SEQ_NUMBER_SIZE; + + std::string entries_count_string = TaifexUtils::decodePackBCD( + &(*current_position), ENTRIES_COUNT_SIZE); + entries_count = std::stoul(entries_count_string); + current_position += ENTRIES_COUNT_SIZE; + // Following fields group repeat NO-MD-ENTRIES times + auto position = PROD_ID_SIZE + SEQ_NUMBER_SIZE + ENTRIES_COUNT_SIZE; + for (size_t i = 0; i < entries_count; ++i) { + entries.push_back(MD_ENTRY(buffer, offset + position)); + position += 13; + // current_position += ENTRIES_COUNT_SIZE;//need to fix + } + } + }; + + struct I083Data { + struct MD_ENTRY { + char md_entry_type; + enum Sign { POSITIVE = 0, NEGATIVE = 1 }; + Sign sign; + double price; + size_t quantity; + size_t level; + + friend std::ostream &operator<<( + std::ostream &os, const I083Data::MD_ENTRY &entry) { + os << "\nMD Entry Type: " << entry.md_entry_type << "\n" + << "Sign: " + << (entry.sign == I083Data::MD_ENTRY::POSITIVE ? "Positive" + : "Negative") + << "\n" + << "Price: " << entry.price << "\n" + << "Quantity: " << entry.quantity << "\n" + << "Level: " << entry.level << "\n"; + return os; + } + + MD_ENTRY(const std::vector &buffer, size_t offset = 0) { + md_entry_type = buffer[offset]; + sign = static_cast(buffer[offset + 1]); + + // price + std::string price_str = + TaifexUtils::decodePackBCD(&buffer[offset + 2], 5); + price = std::stod(price_str); + + // quantity + std::string size_str = + TaifexUtils::decodePackBCD(&buffer[offset + 7], 4); + quantity = std::stoul(size_str); + + // level + std::string level_str = + TaifexUtils::decodePackBCD(&buffer[offset + 11], 1); + level = std::stoul(level_str); + }; + }; + std::vector entries; + std::string prod_id; + unsigned long seq_number; + int calculated_flag; + size_t entries_count; + friend std::ostream &operator<<(std::ostream &os, const I083Data &data) { + os << "Product ID: " << data.prod_id << "\n" + << "Sequence Number: " << data.seq_number << "\n" + << "Calculated Flag: " << data.calculated_flag << "\n" + << "Entries Count: " << data.entries_count << "\n" + << "MD entries: "; + for (auto entry : data.entries) { + std::cout << entry; + } + + return os; + } + + I083Data( + const std::vector &buffer, + const size_t &offset = 0, + size_t length = -1, + bool ignore_calc_flag=false) { + UNUSED(length); + const size_t ENTRIES_COUNT_SIZE = 1; + const size_t PROD_ID_SIZE = 20; + const size_t SEQ_NUMBER_SIZE = 5; + const size_t CALCULATED_FLAG_SIZE = 1; + + auto current_position = buffer.begin() + offset; + + prod_id.assign(current_position, current_position + PROD_ID_SIZE); + current_position += PROD_ID_SIZE; + + std::string seq_number_str = + TaifexUtils::decodePackBCD(&(*current_position), SEQ_NUMBER_SIZE); + seq_number = std::stoul(seq_number_str); + current_position += SEQ_NUMBER_SIZE; + + calculated_flag = static_cast(*current_position); + if(!ignore_calc_flag) + current_position += CALCULATED_FLAG_SIZE; + + std::string entries_count_string = TaifexUtils::decodePackBCD( + &(*current_position), ENTRIES_COUNT_SIZE); + entries_count = std::stoul(entries_count_string); + current_position += ENTRIES_COUNT_SIZE; + + // Following fields group repeat NO-MD-ENTRIES times + auto position = PROD_ID_SIZE + SEQ_NUMBER_SIZE + CALCULATED_FLAG_SIZE + + ENTRIES_COUNT_SIZE; + if(ignore_calc_flag) + position-=CALCULATED_FLAG_SIZE; + + for (size_t i = 0; i < entries_count; ++i) { + entries.push_back(MD_ENTRY(buffer, offset + position)); + position += 12; + // current_position += ENTRIES_COUNT_SIZE;//need to fix + } + } + + }; + struct I084Data { + enum MESSAGE_TYPE { + UNDEFINED = 0, + A = 65, + O = 79, + S = 83, + P = 80, + Z = 90, + } message_type; + + MESSAGE_TYPE charToMessageType(char c) { + switch (c) { + case 'A': return A; + case 'O': return O; + case 'S': return S; + case 'P': return P; + case 'Z': return Z; + default: return UNDEFINED; + } + } + + std::vector data; + unsigned long last_seq; + + // Overload the << operator for convenient output + friend std::ostream &operator<<(std::ostream &os, const I084Data &data) { + os << "The Message Type is: " << char(data.message_type) << "\n"; + for (const auto &entry : data.data) { + os << entry; + } + return os; + } + + I084Data(const std::vector &buffer, const size_t &offset = 0, const bool skip_o =false) { + auto current_position = offset; + message_type = charToMessageType(buffer[current_position]); + current_position += 1; + + switch (message_type) { + case A: { + + last_seq = TaifexUtils::extractBCD_STOUL(buffer, current_position,5); + break; + } + case O: { + if(skip_o) + break; + unsigned int no_entries = TaifexUtils::extractBCD_STOUL(buffer,current_position , 1); + + // Inner loop: Process each Market Data Entry + for (unsigned int i = 0; i < no_entries; ++i) { + auto d = I083Data(buffer, current_position,0,true); + data.push_back(d); + current_position += 26 + 12*d.entries_count; + } + break; + } + case Z: { + last_seq = TaifexUtils::extractBCD_STOUL(buffer, current_position,5); + break; + } + case S: + case P: + default: + break; + } + } +}; + +}; +} // namespace bts::md::taifex \ No newline at end of file diff --git a/src/server/sparkd/md/taifex/TaifexSecurityDetailsMapper.h b/src/server/sparkd/md/taifex/TaifexSecurityDetailsMapper.h new file mode 100644 index 000000000..adbbea59a --- /dev/null +++ b/src/server/sparkd/md/taifex/TaifexSecurityDetailsMapper.h @@ -0,0 +1,95 @@ +#include "lib/domain/SecurityID.h" +#include +#include +#include +namespace bts::md::taifex { +class TaifexSecurityDetailsMapper { + struct security_details { + double min_increment; + std::string currency; + bool has_i010 = false; + bool has_i011 = false; + uint dec_loc; + bts::domain::SecurityID sec_id; + }; + + public: + // Add a mapping from instrument_id to sec_id + void add_i010_mapping( + std::string instrument_id, + bts::domain::SecurityID sec_id, + uint decimal_locator) { + auto &details = sec_deets_map[instrument_id]; + details.sec_id = sec_id; + details.dec_loc = decimal_locator; + details.has_i010 = true; + } + + // Add a mapping for i011 + void add_i011_mapping( + std::string instrument_id, double min_increment, std::string currency) { + auto &details = sec_deets_map[instrument_id]; + details.min_increment = min_increment; + details.currency = currency; + details.has_i011 = true; + } + + // Find sec_id by instrument_id + std::optional get_sec_id( + std::string instrument_id) const { + auto it = sec_deets_map.find(instrument_id); + if (it != sec_deets_map.end() && it->second.has_i010) { + return it->second.sec_id; + } + return std::nullopt; + } + + // Find dec_loc by instrument_id + std::optional get_dec_loc(std::string instrument_id) const { + auto it = sec_deets_map.find(instrument_id); + if (it != sec_deets_map.end() && it->second.has_i010) { + return it->second.dec_loc; + } + return std::nullopt; + } + std::string get_currency(std::string instrument_id) const { + auto it = sec_deets_map.find(instrument_id); + if (it != sec_deets_map.end() && it->second.has_i010 && + it->second.has_i011) { + return it->second.currency; + } + return "usd"; + } + + double get_min_inc(std::string instrument_id) const { + auto it = sec_deets_map.find(instrument_id); + if (it != sec_deets_map.end() && it->second.has_i010 && + it->second.has_i011) { + return it->second.min_increment; + } + return 1; + } + // to_string function to print all data in both maps + std::string to_string() const { + std::stringstream ss; + for (const auto &[instrument_id, details] : sec_deets_map) { + ss << "Instrument ID: " << instrument_id << "\n" + << " Sec ID: " << details.sec_id << "\n" + << " Dec Loc: " << details.dec_loc << "\n" + << " Min Increment: " << details.min_increment << "\n" + << " Currency: " << details.currency << "\n" + << " Has I010: " << (details.has_i010 ? "Yes" : "No") << "\n" + << " Has I011: " << (details.has_i011 ? "Yes" : "No") << "\n"; + } + return ss.str(); + } + // Reset function to clear the data map + void reset() { + sec_deets_map.clear(); + } + + private: + std::unordered_map sec_deets_map; +}; + +} // namespace bts::md::taifex \ No newline at end of file diff --git a/src/server/sparkd/md/taifex/TaifexUtils.h b/src/server/sparkd/md/taifex/TaifexUtils.h new file mode 100644 index 000000000..7a02ac567 --- /dev/null +++ b/src/server/sparkd/md/taifex/TaifexUtils.h @@ -0,0 +1,455 @@ +#include "lib/logging/logging.h" +#include "lib/utils/bts_assert.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace bts::md::taifex { +class TaifexUtils { + public: + static int recv_socket_data(int socket, std::vector& buffer, const size_t FEED_BUFFER_SIZE, const std::string & socket_desc ="") { + int bytes_received = -1; + try { + bytes_received = recvfrom(socket, buffer.data(), FEED_BUFFER_SIZE, 0, nullptr, nullptr); + } catch (...) { + std::string s = strerror(errno); + LOG(md, Error, "{}: Error receiving data from socket, {}",socket_desc, s); + } + if (bytes_received < 0) { + std::string s = strerror(errno); + LOG(md, Error, "{}: Socket error: {}",socket_desc, s); + } else if (bytes_received == 0) { + std::string s = strerror(errno); + LOG(md, Error, "{} Received 0 bytes {}",socket_desc, s); + } + return bytes_received; +} + + // Reusable function to create and join a multicast group + static int create_multicast_socket( + const std::string &multicast_ip, + const int port, + const std::string &interface_ip) { + struct sockaddr_in addr; + memset(&addr, 0, sizeof(addr)); + + // Create UDP socket + auto sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) { + LOG(md, Error, "Socket creation failed IP{} PORT{}", multicast_ip, + port); + return -1; + } + + // Allow multiple sockets to use the same port + int reuse = 1; + if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < + 0) { + LOG(md, Error, "Setting SO_REUSEADDR failed IP{} PORT{}", multicast_ip, + port); + close(sock); + return -1; + } + + // Bind to the multicast port + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + addr.sin_addr.s_addr = htonl(INADDR_ANY); + + if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { + LOG(md, Error, "Bind failed IP{} PORT{}", multicast_ip, port); + close(sock); + return -1; + } + + // Specify the network interface for multicast + struct in_addr localInterface; + localInterface.s_addr = inet_addr(interface_ip.c_str()); + if (setsockopt( + sock, IPPROTO_IP, IP_MULTICAST_IF, (char *)&localInterface, + sizeof(localInterface)) < 0) { + LOG(md, Error, "Setting local interface failed IP{} PORT{}", + multicast_ip, port); + close(sock); + return -1; + } + + // Join the multicast group + struct ip_mreq mreq; + mreq.imr_multiaddr.s_addr = inet_addr(multicast_ip.c_str()); + mreq.imr_interface.s_addr = inet_addr(interface_ip.c_str()); + if (setsockopt( + sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&mreq, + sizeof(mreq)) < 0) { + LOG(md, Error, "adding multicast group failed IP{} PORT{}", + multicast_ip, port); + close(sock); + return -1; + } + LOG(md, Info, "Joined multicast group on IP: {}, Port: {}", multicast_ip, + port); + // struct timeval tv; + // tv.tv_sec = 5; + // tv.tv_usec = 0; + // setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv); + return sock; + } + static int create_multicast_socket_assert( + const std::string &ip, int port, const std::string &market_data_ip) { + int socket = + TaifexUtils::create_multicast_socket(ip, port, market_data_ip); + if (socket == -1) { + bts_assert_msgf(false, "Couldn't open socket for {}:{}", ip, port); + } + return socket; + } + static void close_sockets(std::set &sockets) { + for (int socket : sockets) { + try { + close(socket); + } catch (...) { + LOG(md, Error, "Couldnt properly close socket {}", socket); + } + } + sockets.clear(); + } + static std::string getBufferString( + const std::vector &buffer, + size_t offset = 0, + size_t length = std::numeric_limits::max()) { + + // Adjust length if it exceeds buffer size + if (length == std::numeric_limits::max() || + offset + length > buffer.size()) { + length = buffer.size() - offset; + } + + if (offset >= buffer.size()) { + offset = buffer.size() - 1; + } + + std::stringstream ss; // Use stringstream to build the string + + for (size_t i = 0; i < length; ++i) { + ss << " offset: " << offset << ", i: " << i << ", value: " << std::hex + << std::uppercase << std::setw(2) << std::setfill('0') + << (unsigned int)buffer[offset + i] << "|"; + } + + return ss.str(); // Return the constructed string + } + + static void printBuffer( + const std::vector &buffer, + size_t offset = 0, + size_t length = std::numeric_limits::max()) { + // Adjust length if it exceeds buffer size + if (length == std::numeric_limits::max() || + offset + length > buffer.size()) { + length = buffer.size() - offset; + } + if (offset >= buffer.size()) + offset = buffer.size() - 1; + for (size_t i = 0; i < length; ++i) { + printf( + " offset: %zu, i: %zu, value: %.2X|", offset, i, + (unsigned int)buffer[offset + i]); + } + // std::cout << std::dec << std::endl; + } + + //Replace std::localtime with localtime_s (use localtime_r for POSIX) + static std::string getCurrentDate() { + auto now = std::chrono::system_clock::now(); + std::time_t now_c = std::chrono::system_clock::to_time_t(now); + std::tm local_tm = *std::localtime(&now_c); + + char buffer[11]; // Buffer to hold formatted date + std::strftime(buffer, sizeof(buffer), "%Y-%m-%d", &local_tm); + return std::string(buffer); + } + + static boost::posix_time::ptime convertToPTime( + const std::string &match_time) { + if (match_time.length() != 12) { + throw std::invalid_argument( + "match_time must be exactly 12 characters long"); + } + + // Extract hours, minutes, seconds, and microseconds from match_time + std::string hours = match_time.substr(0, 2); + std::string minutes = match_time.substr(2, 2); + std::string seconds = match_time.substr(4, 2); + std::string microseconds = match_time.substr(6, 6); + + // Get the current date + std::string date = getCurrentDate(); + + // Combine the date and time + std::string datetime = date + " " + hours + ":" + minutes + ":" + seconds; + + // Convert to ptime + boost::posix_time::ptime pt = + boost::posix_time::time_from_string(datetime); + + // Add fractional seconds (microseconds) + boost::posix_time::ptime result = + pt + boost::posix_time::microseconds(std::stoi(microseconds)); + + return result; + } + + static std::string convertToISO( + const std::string &match_time, + const std::string &format = "datetime_no_timezone") { + if (match_time.length() != 12) { + throw std::invalid_argument( + "in function convertToISO: match_time must be exactly 12 " + "characters " + "long: -> " + + match_time); + } + + try { + // Extract time components + std::string hours = match_time.substr(0, 2); + std::string minutes = match_time.substr(2, 2); + std::string seconds = match_time.substr(4, 2); + + // Validate and sanitize time components + int h = std::abs(std::stoi(hours)) % 24; + int m = std::abs(std::stoi(minutes)) % 60; + int s = std::abs(std::stoi(seconds)) % 60; + + // Get the current date dynamically + std::string current_date = getCurrentDate(); + + // Construct the desired ISO format + std::ostringstream iso_stream; + if (format == "datetime_with_timezone") { + // Full date-time with time zone: "YYYY-MM-DDTHH:MM:SS+02:00" (for simplicity using UTC "Z") + iso_stream << current_date << "T" << std::setfill('0') + << std::setw(2) << h << ":" << std::setfill('0') + << std::setw(2) << m << ":" << std::setfill('0') + << std::setw(2) << s << "Z"; // Assuming UTC for now + } else if (format == "datetime_no_timezone") { + // Date-time without time zone: "YYYY-MM-DDTHH:MM:SS" + iso_stream << current_date << "T" << std::setfill('0') + << std::setw(2) << h << ":" << std::setfill('0') + << std::setw(2) << m << ":" << std::setfill('0') + << std::setw(2) << s; + } else if (format == "date_only") { + // Date only: "YYYY-MM-DD" + iso_stream << current_date; + } else { + throw std::invalid_argument( + "Unknown format specified for convertToISO: " + format); + } + + return iso_stream.str(); + } catch (const std::exception &e) { + std::cerr << "Error in convertToISO: " << e.what() << std::endl; + throw; + } + } + + static std::string sanitizeISOString(const std::string &isoString) { + std::string result = isoString; + + // Remove any whitespace + result.erase( + std::remove_if(result.begin(), result.end(), ::isspace), + result.end()); + + // Ensure it's at least 20 characters long (e.g., YYYY-MM-DDTHH:MM:SS) + if (result.size() != 20) { + if (result.size() < 20) { + // If it's too short, pad with zeros at the end (assuming it's missing time components) + result.append(20 - result.size(), '0'); + } else { + // If it's too long, truncate to 20 characters + result = result.substr(0, 20); + } + } + + // Check for and correct any time zone issues or missing Z (UTC indicator) + size_t posT = result.find('T'); + if (posT != std::string::npos) { + size_t posZ = result.find('Z', posT); + if (posZ == std::string::npos) { + size_t posMinus = result.find('-', posT); + size_t posPlus = result.find('+', posT); + if (posMinus != std::string::npos && posMinus > posT) { + // Check if it's "-0" or "-00" or "-000", etc. + if (std::all_of( + result.begin() + posMinus + 1, result.end(), + [](char c) { return c == '0'; })) { + result = result.substr(0, posMinus) + "Z"; + } + } else if (posPlus != std::string::npos && posPlus > posT) { + // Check if it's "+0" or "+00" or "+000", etc. + if (std::all_of( + result.begin() + posPlus + 1, result.end(), + [](char c) { return c == '0'; })) { + result = result.substr(0, posPlus) + "Z"; + } + } else { + // If there's no timezone indicator, assume UTC and add 'Z' + result += "Z"; + } + } + } + + return result; + } + + static std::string time_decodePackBCD( + const unsigned char *data, size_t length) { + std::stringstream ss; + for (size_t i = 0; i < length; ++i) { + int upper = (data[i] >> 4) & 0x0F; + int lower = data[i] & 0x0F; + + // Check if the decoded values are valid digits + if (upper > 9 || lower > 9) { + // Instead of throwing an error, replace invalid digits with '0' + upper = upper > 9 ? 0 : upper; + lower = lower > 9 ? 0 : lower; + } + + ss << upper << lower; + } + + std::string result = ss.str(); + + // Ensure the result is exactly 12 characters long (hhmmssxxxxxx) + if (result.length() < 12) { + // If less than 12 characters, pad with zeros at the end + result = result + std::string(12 - result.length(), '0'); + } else if (result.length() > 12) { + // If more than 12 characters, keep the first 12 + result = result.substr(0, 12); + } + + // Ensure the time part (hhmmss) is valid + int hours = std::stoi(result.substr(0, 2)); + int minutes = std::stoi(result.substr(2, 2)); + int seconds = std::stoi(result.substr(4, 2)); + + hours = std::min(23, std::max(0, hours)); + minutes = std::min(59, std::max(0, minutes)); + seconds = std::min(59, std::max(0, seconds)); + + // Reconstruct the result with valid time + std::stringstream final_ss; + final_ss << std::setfill('0') << std::setw(2) << hours + << std::setfill('0') << std::setw(2) << minutes + << std::setfill('0') << std::setw(2) << seconds + << result.substr(6); // Keep the last 6 characters (xxxxxx) as is + + return final_ss.str(); + } + + // need to change parameters + static std::string decodePackBCD(const unsigned char *data, size_t length) { + std::stringstream ss; + for (size_t i = 0; i < length; ++i) { + // Extract the upper and lower nibble (4 bits each) + int upper = (data[i] >> 4) & 0x0F; + int lower = data[i] & 0x0F; + + // Append both nibbles to the stringstream + ss << upper << lower; + } + + std::string result = ss.str(); + + // Remove leading zeros + result.erase(0, result.find_first_not_of('0')); + + // If the result is empty (all zeros), return "0" + return result.empty() ? "0" : result; + } + static std::string extractString( + const std::vector &buffer, + size_t &position, + size_t length) { + // Extract the substring from the buffer + std::string result( + buffer.begin() + position, buffer.begin() + position + length); + position += length; + + // Log the raw result + return result; + } + + // Helper function to extract a BCD value from the buffer and convert to + // unsigned long + static unsigned long extractBCD_STOUL( + const std::vector &buffer, + size_t &position, + size_t length) { + std::string bcd_str = decodePackBCD(&buffer[position], length); + position += length; + return std::stoul(bcd_str); + } + static std::string extractBCD_STRING( + const std::vector &buffer, + size_t &position, + size_t length) { + std::string bcd_str = decodePackBCD(&buffer[position], length); + position += length; + return bcd_str; + } + // Helper function to extract a single character and convert to bool + static bool extractBool( + const std::vector &buffer, size_t &position) { + bool result = (buffer[position] == 'Y'); + position += 1; + return result; + } + + static std::string extractBCDDate( + const std::vector &buffer, + size_t ¤t_position, + size_t size) { + if (size != 4) { + throw std::invalid_argument("BCD date must be 4 bytes long"); + } + + std::string date; + for (size_t i = 0; i < size; ++i) { + unsigned char byte = buffer[current_position++]; + char high = (byte >> 4) + '0'; + char low = (byte & 0x0F) + '0'; + date.push_back(high); + date.push_back(low); + } + + // Ensure the date is in YYYYMMDD format + if (date.length() != 8) { + throw std::runtime_error("Extracted date is not in YYYYMMDD format"); + } + + return date; + } + + static auto remove_spaces(std::string &name) { + std::string removed = ""; + const char space = ' '; + for (auto c : name) { + if (c != space) { + removed += c; + } + } + return removed; + }; +}; + +} //namespace bts::md::taifex \ No newline at end of file