diff --git a/src/DataStreamSuite/DataStream/Primitives/Misc/TestStream.cs b/src/DataStreamSuite/DataStream/Primitives/Misc/TestStream.cs index e21afa9ec..4f9c258f8 100644 --- a/src/DataStreamSuite/DataStream/Primitives/Misc/TestStream.cs +++ b/src/DataStreamSuite/DataStream/Primitives/Misc/TestStream.cs @@ -51,19 +51,20 @@ namespace BCG { Tuple.Create("exception", TypeCode.String) ); // resgiter 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_schema_serialization_test)); - _tests.Add(new Func(_row_serialization_tests_no_dbnulls)); - _tests.Add(new Func(_row_serialization_tests_with_dbnulls)); - _tests.Add(new Func(_row_serialization_tests_all_types)); - _tests.Add(new Func(_run_full_stream_serialization_test)); - _tests.Add(new Func(_run_full_stream_serialization_with_controller_test)); - _tests.Add(new Func(_run_pubsub_server_stream_tag_handler_test)); - _tests.Add(new Func(_run_single_tag_data_test_clean)); + // _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)); + // _tests.Add(new Func(_row_serialization_tests_all_types)); + // _tests.Add(new Func(_run_full_stream_serialization_test)); + // _tests.Add(new Func(_run_full_stream_serialization_with_controller_test)); + // _tests.Add(new Func(_run_pubsub_server_stream_tag_handler_test)); + // _tests.Add(new Func(_run_single_tag_data_test_clean)); + _tests.Add(new Func(_run_datetime_seriliaztion_test)); } protected override void myOnFirstSubscriber() { @@ -228,9 +229,16 @@ namespace BCG { }; } - private TestResult _run_universal_row_serialization_test() { + + private TestResult _run_datetime_seriliaztion_test() { + DateTime dt = DateTime.Now; + DateTimeOffset dt_off = new DateTimeOffset(dt); + long dt_epoch_ms = dt_off.ToUnixTimeMilliseconds(); + DateTimeOffset dt_off_pr = DateTimeOffset.FromUnixTimeMilliseconds(dt_epoch_ms); + DateTime dt_p = dt_off_pr.DateTime; + var passes = dt.Equals(dt_p); return new TestResult { - test_name = "UniversalRowwSerialization", + test_name = "_run_datetime_seriliaztion_test", test_result = false }; } @@ -439,100 +447,6 @@ namespace BCG { }; } - // private static TestResult _run_single_tag_data_test() { - // // create message - // var schema = create_schema_with_all_types(); - // var tag = "DS_" + schema.tableName; - // BlueTable cr_rows = new BlueTable(schema); - // // 100 rows - // int n_rows = 100; - // for (int i = 0; i < n_rows; i++) { - // var nr = generate_random_row(schema, i); - // cr_rows.addRow(nr); - // } - // bts.SingleTagData st_data = new bts.SingleTagData(tag, "DS"); - - // bts.StreamIOMessage.CreateMessage cr_msg = new bts.StreamIOMessage.CreateMessage(cr_rows); - // bts.StreamIOMessage str_io_msg = new bts.StreamIOMessage(cr_msg); - // IStreamIOMsgSerializer serializer = new StreamIOSerializationController(); - // byte[] msg_bytes = serializer.serialize(str_io_msg); - // PublishMsg pub_msg = new PublishMsg() { - // connection = "test_connection", - // tag = tag, - // tag_type = "DS", - // data_to_publish = msg_bytes - // }; - // st_data.handle_publish(pub_msg); - // byte[] data_p = st_data.get_current_content(); - // IStreamMsgDeserilizer deser = new StreamIODeserializationController(); - // var msg_p = deser.deserialize(data_p); - // bool passes = msg_p.op == bts.StreamIOMessage.StreamOp.CREATE && - // BlueDataUtility.compute_equality(cr_rows, msg_p.create_message.rows); - - // Func build_pub_msg = (added_row, removed_row) => { - // BlueTable added_table = new BlueTable(cr_rows.schema); - // if (added_row != null) - // added_table.addRow(added_row); - // BlueTable rem_table = new BlueTable(cr_rows.schema); - // if (removed_row != null) - // rem_table.addRow(removed_row); - // bts.StreamIOMessage.MultipleRemoveAddMessage mra_msg = - // new bts.StreamIOMessage.MultipleRemoveAddMessage(rem_table, added_table); - // bts.StreamIOMessage str_io_msg = new bts.StreamIOMessage(mra_msg); - // byte[] msg_bytes = serializer.serialize(str_io_msg); - // PublishMsg pub_msg = new PublishMsg() { - // connection = "test_connection", - // tag = tag, - // tag_type = "DS", - // data_to_publish = msg_bytes - // }; - // return pub_msg; - // }; - - // Func get_state = (content) => { - // IStreamMsgDeserilizer deser = new StreamIODeserializationController(); - // var msg_p = deser.deserialize(content); - // Log.assert(msg_p.op == bts.StreamIOMessage.StreamOp.CREATE); - // return msg_p.create_message.rows; - // }; - // // 1. adding 100 rows - // int n_added_rows = 100; - // for (int i = 0; i < n_added_rows; i++) { - // var nr = generate_random_row(schema, cr_rows.Count); - // cr_rows.addRow(nr); - // // added - // PublishMsg new_pub_msg = build_pub_msg(nr, null); - // st_data.handle_publish(new_pub_msg); - // } - // var state_bytes = st_data.get_current_content(); - // IBlueRowCollection total_state = get_state(state_bytes); - // passes = passes && BlueDataUtility.compute_equality(cr_rows, total_state); - // // modifying 100 rows - // int n_mods = 100; - // int init_count = cr_rows.Count; - // for (int i = 0; i < n_mods; i++) { - // var dr = BlueDataUtility.extractRow(cr_rows, i); - // var nr = generate_random_row(schema, i + init_count); - // cr_rows.deleteRow(dr); - // cr_rows.addRow(nr); - // var new_pub_msg = build_pub_msg(nr, dr); - // st_data.handle_publish(new_pub_msg); - // } - // IBlueRowCollection new_total_state = get_state(st_data.get_current_content()); - // passes = passes && BlueDataUtility.compute_equality(cr_rows, new_total_state); - // // deleting all rows - // foreach (IBlueRow r in cr_rows) { - // pub_msg = build_pub_msg(null, r); - // st_data.handle_publish(pub_msg); - // } - // cr_rows.clear(); - // new_total_state = get_state(st_data.get_current_content()); - // passes = passes && BlueDataUtility.compute_equality(new_total_state, cr_rows); - // return new TestResult() { - // test_name = "SingleTagData", - // test_result = passes - // }; - // } private static TestResult _run_single_tag_data_test_clean() { // create message @@ -632,7 +546,7 @@ namespace BCG { BlueTableSchema schema = new BlueTableSchema(); List cis = new List(); foreach (Type t in BlueDataUtility.valid_column_types()) { - if (t == null || t == typeof(DateTime)) + if (t == null/* || t == typeof(DateTime)*/) continue; var col_name = t.ToString() + "_" + cis.Count.ToString(); // Guid.NewGuid().ToString(); ColumnInfo ci = new ColumnInfo(col_name, cis.Count, t); @@ -671,8 +585,8 @@ namespace BCG { case TypeCode.Decimal: Decimal dec = 100.123M; return dec; - // object obj_d = get_random_object(TypeCode.Double); - // return Convert.ToDecimal(obj_d); + case TypeCode.DateTime: + return DateTime.Now; case TypeCode.Double: return random.NextDouble() * (double.MaxValue - double.MinValue) + double.MinValue; // Random double value case TypeCode.Int16: diff --git a/src/DataStreamSuite/DataStream/Publish/PublisherStream.cs b/src/DataStreamSuite/DataStream/Publish/PublisherStream.cs new file mode 100644 index 000000000..ab294aa49 --- /dev/null +++ b/src/DataStreamSuite/DataStream/Publish/PublisherStream.cs @@ -0,0 +1,31 @@ +namespace BCG { + // this for testing purposes mainly, its wraps a ViewPublisher around a stream, + // and hence epublishes it out to the PS + public class PublisherStream : ViewStream { + private readonly ViewStream _main_stream; + private readonly string _name; + private ViewPublisher _vs_publisher; + private readonly PubTableBroker _broker = new PubTableBroker(); + + public PublisherStream(ViewStream main_stream, string name) { + _main_stream = main_stream; + _name = name; + } + + protected override void myOnFirstSubscriber() { + _vs_publisher = new ViewPublisher(_name, _broker, _main_stream); + _main_stream.onChange += new DataStream.ChangeDelegate(_handle_update); + } + + protected override void myOnLastSubscriber() { + _main_stream.onChange -= new DataStream.ChangeDelegate(_handle_update); + _vs_publisher.Dispose(); + } + + private void _handle_update(object o) { + myFireEvent(o); + } + + + } +} \ No newline at end of file diff --git a/src/DataStreamSuite/DataStream/Publish/ViewStreamPublisher.cs b/src/DataStreamSuite/DataStream/Publish/ViewStreamPublisher.cs deleted file mode 100644 index 8d75b5036..000000000 --- a/src/DataStreamSuite/DataStream/Publish/ViewStreamPublisher.cs +++ /dev/null @@ -1,93 +0,0 @@ -// using System; -// using BCG.Utilities; - -// TODO: remove -// namespace BCG -// { -// public class ViewStreamPublisher -// { -// private IDynamicStreamMapper myMapper; -// private PubTableBroker myBroker; -// private IBlueRowCollection myOutputTable; -// private IBlueRowCollection myInputTable; - -// public ViewStreamPublisher (PubTableBroker broker) -// { -// myBroker = broker; -// } - -// public ViewStreamPublisher (PubTableBroker broker, IDynamicStreamMapper mapper) -// : this (broker) -// { -// myMapper = mapper; -// } - -// public ViewStreamPublisher (PubTableBroker broker, IDynamicStreamMapper mapper, ViewStream vs) -// : this (broker, mapper) -// { -// vs.onChange += new BCG.DataStream.ChangeDelegate(myHandleChanges); -// } - -// private void myHandleChanges (object newValue) -// { -// DataPacket dp = newValue as DataPacket; -// if (myMapper == null) -// { -// if (myOutputTable == null) -// { -// myBroker.createTable (dp.newRows); -// } -// else -// { -// myBroker.makeBatchChanges (dp.newRows, dp.deletedRows, dp.addedRows); -// } -// myOutputTable = dp.newRows; -// } -// else -// { -// if (myOutputTable != null) -// { -// BlueTable dRows = new BlueTable (myOutputTable.schema), -// aRows = new BlueTable (myOutputTable.schema); -// foreach (IBlueRow dRow in dp.deletedRows) -// { -// (myOutputTable as BlueTable).deleteRow ((int)dRow["id"]); -// dRows.addRow (myMapper.map (dRow)); -// } -// foreach (IBlueRow aRow in dp.addedRows) -// { -// IBlueRow r = myMapper.map (aRow); -// (myOutputTable as BlueTable).addRow (r); -// aRows.addRow (r); -// } -// myBroker.makeBatchChanges (myOutputTable, dRows, aRows); -// } -// else -// { -// if (dp.newRows.Count > 0) -// { -// myOutputTable = new BlueTable ( -// myMapper.map (BlueDataUtility.extractRow (dp.newRows, 0)).schema); -// myHandleChanges (newValue); -// } -// } -// } -// } - -// public void addRows (IBlueRowCollection aRows) -// { -// if (myInputTable != null) -// (myInputTable as BlueTable).addRows (aRows); -// else -// myInputTable = new BlueTable (aRows); -// myHandleChanges (new DataPacket(myInputTable, aRows, new BlueTable (aRows.schema))); -// } - -// public void deleteRows (IBlueRowCollection dRows) -// { -// // BlueEventLog.logAssert (myInputTable != null); -// (myInputTable as BlueTable).deleteRows (dRows); -// myHandleChanges (new DataPacket (myInputTable, new BlueTable (myInputTable.schema), dRows)); -// } -// } -// } diff --git a/src/DataStreamSuite/DataStreamCore/BlueData/BlueDataUtility.cs b/src/DataStreamSuite/DataStreamCore/BlueData/BlueDataUtility.cs index 97097fb76..ade6dac40 100644 --- a/src/DataStreamSuite/DataStreamCore/BlueData/BlueDataUtility.cs +++ b/src/DataStreamSuite/DataStreamCore/BlueData/BlueDataUtility.cs @@ -225,7 +225,7 @@ namespace BCG { { TypeCode.Byte, typeof(byte) }, { TypeCode.Char, typeof(char) }, // TODO - // { TypeCode.DateTime, typeof(DateTime) }, + { TypeCode.DateTime, typeof(DateTime) }, { TypeCode.Decimal, typeof(decimal) }, { TypeCode.Double, typeof(double) }, //{ TypeCode.Empty, null }, @@ -1141,6 +1141,11 @@ namespace BCG { public static void compute_differences_fast(IBlueRowCollection new_rows, IBlueRowCollection old_rows, out IBlueRowCollection out_d_rows, out IBlueRowCollection out_a_rows) { + if (old_rows == null || old_rows.Count == 0) { + out_d_rows = new BlueTable(new_rows.schema); + out_a_rows = new BlueTable(new_rows); + return; + } int[] col_indices = new int[new_rows.schema.columnNames.Length]; for (int i = 0; i < col_indices.Length; i++) col_indices[i] = i; @@ -1149,6 +1154,11 @@ namespace BCG { public static void compute_differences_id_based(IBlueRowCollection new_rows, IBlueRowCollection old_rows, out IBlueRowCollection out_d_rows, out IBlueRowCollection out_a_rows) { + if (old_rows == null || old_rows.Count == 0) { + out_d_rows = new BlueTable(new_rows.schema); + out_a_rows = new BlueTable(new_rows); + return; + } int[] col_indices = new int[] { new_rows.schema["id"].colNo }; compute_differences_fast(new_rows, old_rows, col_indices, out out_d_rows, out out_a_rows); } diff --git a/src/DataStreamSuite/DataStreamCore/LightTableStream.cs b/src/DataStreamSuite/DataStreamCore/LightTableStream.cs index 561dbd769..0d4b1c07d 100644 --- a/src/DataStreamSuite/DataStreamCore/LightTableStream.cs +++ b/src/DataStreamSuite/DataStreamCore/LightTableStream.cs @@ -1,51 +1,44 @@ -using System; -using System.Collections; -using System.Data; +// using System; +// using System.Collections; +// using System.Data; -using BCG.Utilities; +// using BCG.Utilities; -/* this class reprsents a table stream for use with CppDataStreams. It does not hold on to the last value fired. - * This way, the last value is purged from managed memory and only the slimmer, sexier Cpp implementation of the row remains. - * - */ -namespace BCG -{ - public class LightTableStream : TableStream - { - public LightTableStream(string tableName) - : - base(tableName, null, null) - { - } +// /* this class reprsents a table stream for use with CppDataStreams. It does not hold on to the last value fired. +// * This way, the last value is purged from managed memory and only the slimmer, sexier Cpp implementation of the row remains. +// * +// */ +// namespace BCG { +// public class LightTableStream : TableStream { +// public LightTableStream(string tableName) +// : +// base(tableName, null, null) { +// } - public LightTableStream(string tableName, ViewStreamDatabase db) - : - base(tableName, db, null) - {} +// public LightTableStream(string tableName, ViewStreamDatabase db) +// : +// base(tableName, db, null) { } - public LightTableStream(string tableName, string colExp) - : - base(tableName, - null, - colExp) - {} - - - public LightTableStream(string ttableName, ViewStreamDatabase db, string colExp) : - base(ttableName,db,colExp) - { - } +// public LightTableStream(string tableName, string colExp) +// : +// base(tableName, +// null, +// colExp) { } - protected override void myHandleUpdates(IBlueRowCollection newRows, IBlueRowCollection addedRows, IBlueRowCollection deletedRows) - { +// public LightTableStream(string ttableName, ViewStreamDatabase db, string colExp) : +// base(ttableName, db, colExp) { +// } - base.myHandleUpdates(newRows, addedRows, deletedRows); - //once you've fired the rows, delete them becuase we don't want to hold onto them in memory - myLastValue = null; - - } - } -} +// protected override void _handle_updates(IBlueRowCollection newRows, IBlueRowCollection addedRows, IBlueRowCollection deletedRows) { + +// base._handle_updates(newRows, addedRows, deletedRows); +// //once you've fired the rows, delete them becuase we don't want to hold onto them in memory +// myLastValue = null; + +// } + +// } +// } diff --git a/src/DataStreamSuite/DataStreamCore/Messaging/Accumulation/AccumulatorFactory.cs b/src/DataStreamSuite/DataStreamCore/Messaging/Accumulation/AccumulatorFactory.cs index 61c15ad61..fa2ba0cdb 100644 --- a/src/DataStreamSuite/DataStreamCore/Messaging/Accumulation/AccumulatorFactory.cs +++ b/src/DataStreamSuite/DataStreamCore/Messaging/Accumulation/AccumulatorFactory.cs @@ -1,17 +1,14 @@ using System; -namespace BCG -{ +namespace BCG { /// /// A central place to get all ITableAccumulators. This is helpful, since specific implementations /// of ITableAccumulators can be instantiated using config. /// - public class AccumulatorFactory - { - public static ITableAccumulator getAccumulator (string tag, ISubscriberCore subCore) - { - return new TableAccumulator (tag, subCore); + public class AccumulatorFactory { + public static ITableAccumulator getAccumulator(string tag, ISubscriberCore subCore) { + return new TableAccumulator2(tag, subCore); } } } diff --git a/src/DataStreamSuite/DataStreamCore/Messaging/Accumulation/ITableAccumulator.cs b/src/DataStreamSuite/DataStreamCore/Messaging/Accumulation/ITableAccumulator.cs index e712e5aa3..298043d39 100644 --- a/src/DataStreamSuite/DataStreamCore/Messaging/Accumulation/ITableAccumulator.cs +++ b/src/DataStreamSuite/DataStreamCore/Messaging/Accumulation/ITableAccumulator.cs @@ -1,24 +1,24 @@ using System; +using System.Collections.Generic; using System.IO; -namespace BCG -{ - public delegate void TableUpdateDelegate (IBlueRowCollection newRows, - IBlueRowCollection addedRows, - IBlueRowCollection deletedRows); +namespace BCG { + public delegate void TableUpdateDelegate(IBlueRowCollection new_rows, + IBlueRowCollection added_rows, + IBlueRowCollection deleted_rows); /// /// This interface is supposed to hook upto pubsub on one end, receive data in bytes, /// deserialize and call the client (that wil hook upto this interface) and give tables /// - public interface ITableAccumulator - { - event TableUpdateDelegate onUpdate; + public interface ITableAccumulator { + event TableUpdateDelegate on_update; /// /// return trues if this table acumulator has any subscribers. /// /// - bool isActive(); - void update (Stream[] streams); + //bool is_active(); + void update(Stream[] streams); + void handle_updates(IEnumerable msgs); } } diff --git a/src/DataStreamSuite/DataStreamCore/Messaging/Accumulation/TableAccumulator.cs b/src/DataStreamSuite/DataStreamCore/Messaging/Accumulation/TableAccumulator.cs index 4d55a1e28..fddc9f6f7 100644 --- a/src/DataStreamSuite/DataStreamCore/Messaging/Accumulation/TableAccumulator.cs +++ b/src/DataStreamSuite/DataStreamCore/Messaging/Accumulation/TableAccumulator.cs @@ -1,82 +1,80 @@ using System; +using System.Collections; using System.IO; -//using BCG.Utilities; +using BCG.Utilities; +using BCG.Utilities.General; +//using BCG.Utilities.BlueConfiguration; +using System.Collections.Generic; +using System.Threading; using mbts; +using System.Linq; using mbts.spark; -namespace BCG -{ - public class TableAccumulator : ITableAccumulator - { +namespace BCG { + public class TableAccumulator : ITableAccumulator { private HighPerformanceTimer _timer = new HighPerformanceTimer(); - private IClientDeserializer myDeserializer = new ClientDeserializationController (); + private IClientDeserializer myDeserializer = new ClientDeserializationController(); private BlueTable myStateTable; private ISubscriberCore mySubscriptionCore; private TableUpdateDelegate myOnUpdateDelegate; private string myTag; private bool myUseIncrementsForMultipleOps = DataStreamGatewaySettings.instance.useIncrementsForMultipleOps; - public TableAccumulator (string tag, ISubscriberCore subCore) - { + public TableAccumulator(string tag, ISubscriberCore subCore) { myTag = tag; mySubscriptionCore = subCore; } #region ITableAccumulator Members - public bool isActive() - {return myOnUpdateDelegate != null;} + public bool is_active() { return myOnUpdateDelegate != null; } - public event TableUpdateDelegate onUpdate - { - add - { + public event TableUpdateDelegate on_update { + add { // BlueEventLog.logEvent ("TableSubscriber being Subscribed for tag :" + myTag, BlueEventLevel.Information); - if (myOnUpdateDelegate == null) - { + if (myOnUpdateDelegate == null) { //ie first subscription // BlueEventLog.logEvent ("Subscription made to PubSub for tag : " + myTag, BlueEventLevel.Information); - mySubscriptionCore.subscribe (myTag); + mySubscriptionCore.subscribe(myTag); } - myOnUpdateDelegate = - Delegate.Combine (myOnUpdateDelegate, value) as TableUpdateDelegate; + myOnUpdateDelegate = + Delegate.Combine(myOnUpdateDelegate, value) as TableUpdateDelegate; if (myStateTable != null) - value (myStateTable, myStateTable, new BlueTable (myStateTable.schema)); - } - remove - { + value(myStateTable, myStateTable, new BlueTable(myStateTable.schema)); + } + remove { // BlueEventLog.logEvent ("TableSubscriber being Unsubscribed for tag :" + myTag, BlueEventLevel.Information); - if (myOnUpdateDelegate != null) - { - myOnUpdateDelegate = - Delegate.Remove (myOnUpdateDelegate, value) as TableUpdateDelegate; - if (myOnUpdateDelegate == null) - { + if (myOnUpdateDelegate != null) { + myOnUpdateDelegate = + Delegate.Remove(myOnUpdateDelegate, value) as TableUpdateDelegate; + if (myOnUpdateDelegate == null) { //all subscribers gone // BlueEventLog.logEvent ("Unubscription made to PubSub for tag : " + myTag, BlueEventLevel.Information); - mySubscriptionCore.unsubscribe (myTag); - myStateTable = null; + mySubscriptionCore.unsubscribe(myTag); + myStateTable = null; } } } } - public void update(Stream[] streams) - { + public void handle_updates(IEnumerable msgs) { + update(msgs.Select(t => new MemoryStream(t)).ToArray()); + } + + public void update(Stream[] streams) { bts.Log.Gen.info($"TableAccumulator.update tag: {myTag} n_streams: {streams.Length} stream[0].len: {streams[0].Length - streams[0].Position}"); //checking the condition as a subscriber might unsubscribe in a callback and there might be more than one //data element for that tag in the ViewStreamDatabase - if (myOnUpdateDelegate != null) - { + if (myOnUpdateDelegate != null) { byte[] ops; Array rows; _timer.start(); - myDeserializer.deserialize (streams, out ops, out rows); + myDeserializer.deserialize(streams, out ops, out rows); _timer.stop(); // BlueEventLog.logEvent(String.Format("deserializing {0} took {1} msecs", myTag, _timer.lastIntervalTime), BlueEventLevel.Performance); _timer.start(); - myAccumulateAndFire (ops, rows); + myAccumulateAndFire(ops, rows); _timer.stop(); // BlueEventLog.logEvent(String.Format("myAccumulateAndFire for {0} took {1} msecs", myTag, _timer.lastIntervalTime), BlueEventLevel.Performance); } @@ -84,22 +82,16 @@ namespace BCG #endregion - private void myAccumulateAndFire (byte[] ops, Array rows) - { + private void myAccumulateAndFire(byte[] ops, Array rows) { //if a non create comes before the create, the deserializer returns 0 sized arrays - if (ops.Length == 0 || rows.Length == 0) - { + if (ops.Length == 0 || rows.Length == 0) { //ie if one is zero sized so should be the other one // BlueEventLog.logAssert (ops.Length + rows.Length == 0); - } - else - { - if (ops.Length > 1) - { + } else { + if (ops.Length > 1) { int index = 0; - if (myStateTable == null) - { - for(index=0; index 0 || dRows.Count > 0) - { + if (aRows.Count > 0 || dRows.Count > 0) { myStateTable = new BlueTable(newState); myOnUpdateDelegate(myStateTable, aRows, dRows); } } - } - else - { - if (op == StreamOpCode.add) - { + } else { + if (op == StreamOpCode.add) { myStateTable.addRows(aRows = tableArray[0]); dRows = new BlueTable(myStateTable.schema); - } - else if (op == StreamOpCode.remove) - { + } else if (op == StreamOpCode.remove) { myStateTable.deleteRows(dRows = tableArray[0]); aRows = new BlueTable(myStateTable.schema); - } - else if (op == StreamOpCode.change) - { + } else if (op == StreamOpCode.change) { IBlueRow cRow = BlueDataUtility.extractRow(tableArray[0], 0); aRows = new BlueTable(myStateTable.schema); dRows = new BlueTable(myStateTable.schema); (aRows as BlueTable).addRow(cRow); (dRows as BlueTable).addRow(myStateTable[(int)cRow["id"]]); myStateTable.changeRow(cRow); - } - else if (op == StreamOpCode.multipleChange) - { - if (myStateTable.Count == tableArray[0].Count) - { + } else if (op == StreamOpCode.multipleChange) { + if (myStateTable.Count == tableArray[0].Count) { //all rows are changed, so we can optimize this dRows = myStateTable; aRows = myStateTable = new BlueTable(tableArray[0]); - } - else - { + } else { dRows = new BlueTable(myStateTable.schema); aRows = tableArray[0]; - foreach (IBlueRow r in tableArray[0]) - { + foreach (IBlueRow r in tableArray[0]) { (dRows as BlueTable).addRow(myStateTable[(int)r["id"]]); myStateTable.changeRow(r); } } - } - else if (op == StreamOpCode.multipleRemoveAdd) - { + } else if (op == StreamOpCode.multipleRemoveAdd) { BlueDataUtility.absorbChanges(myStateTable, dRows = tableArray[0], aRows = tableArray[1]); - } - else - { + } else { aRows = dRows = null; // BlueEventLog.logAssert(false, "unknown opcode"); } @@ -347,5 +281,5 @@ namespace BCG } } } - + } diff --git a/src/DataStreamSuite/DataStreamCore/Messaging/Accumulation/TableAccumulator2.cs b/src/DataStreamSuite/DataStreamCore/Messaging/Accumulation/TableAccumulator2.cs new file mode 100644 index 000000000..5a97de700 --- /dev/null +++ b/src/DataStreamSuite/DataStreamCore/Messaging/Accumulation/TableAccumulator2.cs @@ -0,0 +1,100 @@ +using System; +using System.IO; +//using BCG.Utilities; +using mbts; +using mbts.spark; +using bts; +using System; +using System.Collections; +using System.IO; +using BCG.Utilities; +using BCG.Utilities.General; +using System.Collections.Generic; +using System.Threading; +using mbts; +using System.Linq; + +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 { + private readonly string _tag; + private readonly ISubscriberCore _subscriber_core; + private HighPerformanceTimer _timer = new HighPerformanceTimer(); + IStreamMsgDeserilizer _deser = new StreamIODeserializationController(); + private BlueTable _table; + private TableUpdateDelegate _on_update_delegate; + + public TableAccumulator2(string tag, ISubscriberCore sub_core) { + _tag = tag; + _subscriber_core = sub_core; + } + + #region ITableAccumulator Members + + //public bool is_active() { return _on_update_delegate != null; } + + public event TableUpdateDelegate on_update { + add { + Log.Gen.info("TableAccumulator2.on_update.add {_tag} subscribed"); + if (_on_update_delegate == null) { + //ie first subscription + Log.Gen.info("TableAccumulator2.on_update {_tag} subscribed for the first time"); + _subscriber_core.subscribe(_tag); + } + _on_update_delegate = + Delegate.Combine(_on_update_delegate, value) as TableUpdateDelegate; + if (_table != null) + value(_table, _table, new BlueTable(_table.schema)); + } + remove { + Log.Gen.info("TableAccumulator2.on_update.remove {_tag} unsubscribed"); + 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) { + _subscriber_core.unsubscribe(_tag); + // TODO + //_table = null; + } + } + + } + } + + 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}"); + IBlueRowCollection table_0 = _table == null ? null : new BlueTable(_table); + foreach (var msg in msgs) { + bts.StreamIOMessage str_msg = _deser.deserialize(msg); + var state_txt = _table == null ? "NULL" : _table.Count.ToString(); + Log.Gen.info($"TableAccumulator2.handle_update tag: {_tag} sz: {msg.Length} str_msg: {str_msg} _state: {state_txt}"); + switch (str_msg.op) { + case bts.StreamIOMessage.StreamOp.CREATE: + _table = new BlueTable(str_msg.create_message.rows); + break; + case bts.StreamIOMessage.StreamOp.MULTIPLE_REMOVE_ADD: + _table.deleteRows(str_msg.multiple_remove_add_message.removed_rows); + _table.addRows(str_msg.multiple_remove_add_message.added_rows); + break; + } + } + // 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); + _on_update_delegate(_table, a_rows, d_rows); + } + + public void update(Stream[] streams) { + } + + #endregion + } + +} diff --git a/src/DataStreamSuite/DataStreamCore/Messaging/Publish/SinglePubTableBroker.cs b/src/DataStreamSuite/DataStreamCore/Messaging/Publish/SinglePubTableBroker.cs index f9fa7fa64..52741c9dc 100644 --- a/src/DataStreamSuite/DataStreamCore/Messaging/Publish/SinglePubTableBroker.cs +++ b/src/DataStreamSuite/DataStreamCore/Messaging/Publish/SinglePubTableBroker.cs @@ -32,9 +32,7 @@ namespace BCG { tag_type = DSTagManager.DataStreamTagType, data_to_publish = msg_bytes }; - PubSubClientMessage msg = new PubSubClientMessage() { - pub_msg = pub_msg - }; + PubSubClientMessage msg = new PubSubClientMessage(pub_msg); _publisher_core.publish(msg); } @@ -48,9 +46,7 @@ namespace BCG { tag_type = DSTagManager.DataStreamTagType, data_to_publish = msg_bytes }; - PubSubClientMessage msg = new PubSubClientMessage() { - pub_msg = pub_msg - }; + PubSubClientMessage msg = new PubSubClientMessage(pub_msg); _publisher_core.publish(msg); } diff --git a/src/DataStreamSuite/DataStreamCore/Messaging/v2/Publish/Serialization/StreamSerializationUtils.cs b/src/DataStreamSuite/DataStreamCore/Messaging/v2/Publish/Serialization/StreamSerializationUtils.cs index fb218ca40..7d3f35b3d 100644 --- a/src/DataStreamSuite/DataStreamCore/Messaging/v2/Publish/Serialization/StreamSerializationUtils.cs +++ b/src/DataStreamSuite/DataStreamCore/Messaging/v2/Publish/Serialization/StreamSerializationUtils.cs @@ -4,6 +4,7 @@ namespace bts { using System; using System.Collections.Generic; using System.IO; + using System.Reactive.Subjects; using System.Reflection.Metadata; using System.Runtime.Serialization.Formatters.Binary; using System.Text; @@ -28,7 +29,13 @@ namespace bts { {typeof(byte), (bw, r, col_no) => {bw.Write(r.get(col_no)); }}, {typeof(char), (bw, r, col_no) => {bw.Write(r.get(col_no)); }}, // TODO - //{typeof(DateTime), (bw, r, col_no) => {bw.Write(r.get(col_no)); }}, + {typeof(DateTime), (bw, r, col_no) => { + DateTime dt = r.get(col_no); + DateTimeOffset dt_off = new DateTimeOffset (dt); + long mseconds = dt_off.ToUnixTimeMilliseconds(); + bw.Write(mseconds); + } + }, {typeof(Decimal), (bw, r, col_no) => {bw.Write(r.get(col_no)); }}, {typeof(Double), (bw, r, col_no) => {bw.Write(r.get(col_no)); }}, {typeof(Int16), (bw, r, col_no) => {bw.Write(r.get(col_no)); }}, @@ -47,6 +54,11 @@ namespace bts { {typeof(byte), (br) => {return br.ReadByte();}}, {typeof(char), (br) => {return br.ReadChar();}}, // TODO DateTime + {typeof(DateTime), (br) => { + long msecs = br.ReadInt64(); + DateTimeOffset dt_off = DateTimeOffset.FromUnixTimeMilliseconds(msecs); + return dt_off.DateTime; + }}, //{typeof(byte), (br) => {return br.ReadByte()} {typeof(Decimal), (br) => {return br.ReadDecimal();}}, {typeof(Double), (br) => {return br.ReadDouble();}}, diff --git a/src/DataStreamSuite/DataStreamCore/Messaging/v2/Receive/PubSubServer/PubsubServerStreamTagHandler.cs b/src/DataStreamSuite/DataStreamCore/Messaging/v2/Receive/PubSubServer/PubsubServerStreamTagHandler.cs index 360fec817..e768cc3fd 100644 --- a/src/DataStreamSuite/DataStreamCore/Messaging/v2/Receive/PubSubServer/PubsubServerStreamTagHandler.cs +++ b/src/DataStreamSuite/DataStreamCore/Messaging/v2/Receive/PubSubServer/PubsubServerStreamTagHandler.cs @@ -1,5 +1,4 @@ -namespace bts -{ +namespace bts { using BCG; using System; @@ -7,15 +6,12 @@ namespace bts using System.IO; // for non stream tags - public class PubsubServerGenericDataHandler : IPubSubServerTagHandler - { + public class PubsubServerGenericDataHandler : IPubSubServerTagHandler { byte[] _state = null; - public void update(string tag, byte[] msg) - { + public void update(string tag, byte[] msg) { _state = msg; } - public byte[] get_content(string tag) - { + public byte[] get_content(string tag) { return _state; } public string[] supportedTagTypes { get; } @@ -23,21 +19,24 @@ namespace bts public void doWork() { } } - public class PubsubServerSingleStreamTagHandler : IPubSubServerTagHandler - { - // this is kept around to deserielie the incoming messages and keep the state of the table + // This class is created by the SingleTagData for stream tag_type. Every pub + + public class PubsubServerSingleStreamTagHandler : IPubSubServerTagHandler { + // this is kept around to deserielize the incoming messages and keep the state of the table StreamIODeserializationController _deser = new StreamIODeserializationController(); // this is kept around so that get_content, serielizes the state StreamIOSerializationController _ser = new StreamIOSerializationController(); + // this is where the state of the table is kept. BlueTable _state = null; - public void update(string tag, byte[] msg) - { - BinaryReader br = new BinaryReader(new MemoryStream(msg)); - StreamIOMessage str_msg = _deser.deserialize(ref br); - switch (str_msg.op) - { + + + 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}"); + switch (str_msg.op) { case StreamIOMessage.StreamOp.CREATE: - Log.assert(_state == null); + //Log.assert(_state == null); _state = new BlueTable(str_msg.create_message.rows); break; case StreamIOMessage.StreamOp.MULTIPLE_REMOVE_ADD: @@ -46,59 +45,51 @@ 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}"); } - public byte[] get_content(string tag) - { - if (_state != null) - { - MemoryStream str = new MemoryStream(); - BinaryWriter bw = new BinaryWriter(str); - StreamIOMessage.CreateMessage cr_msg = new StreamIOMessage.CreateMessage(_state); - StreamIOMessage op_msg = new StreamIOMessage(cr_msg); - _ser.serialize(op_msg, ref bw); - str.Position = 0; - return str.ToArray(); - } - return null; + public byte[] get_content(string tag) { + Func get_content_ = () => { + if (_state != null) { + StreamIOMessage.CreateMessage cr_msg = new StreamIOMessage.CreateMessage(_state); + StreamIOMessage op_msg = new StreamIOMessage(cr_msg); + byte[] rv = _ser.serialize(op_msg); + return rv; + } + return null; + }; + var rv = get_content_(); + Log.Gen.info("PubsubServerStreamTagHandler.get_content rv: {rv == null ? null : rv.Length}"); + return rv; } - public string[] supportedTagTypes - { - get - { + public string[] supportedTagTypes { + get { return new string[] { "DS" }; } } - public void register(InternalPublishDelegate callback) - { + public void register(InternalPublishDelegate callback) { } public void doWork() { } } - public class PubsubServerStreamTagHandler : IPubSubServerTagHandler - { + public class PubsubServerStreamTagHandler : IPubSubServerTagHandler { IDictionary _handler_map = new Dictionary(); private readonly string _tag; - public PubsubServerStreamTagHandler() - { + public PubsubServerStreamTagHandler() { } - public void update(string tag, byte[] msg) - { + public void update(string tag, byte[] msg) { BCG.IPubSubServerTagHandler rv = _get_handler(tag); rv.update(tag, msg); } - public byte[] get_content(string tag) - { + public byte[] get_content(string tag) { BCG.IPubSubServerTagHandler rv = _get_handler(tag); return rv.get_content(tag); } - public string[] supportedTagTypes - { - get - { + public string[] supportedTagTypes { + get { List rv = new List(); foreach (var h in _handler_map.Values) rv.AddRange(h.supportedTagTypes); @@ -106,23 +97,19 @@ namespace bts } } - private BCG.IPubSubServerTagHandler _get_handler(string tag) - { + private BCG.IPubSubServerTagHandler _get_handler(string tag) { PubsubServerSingleStreamTagHandler rv = null; - if (!_handler_map.TryGetValue(tag, out rv)) - { + if (!_handler_map.TryGetValue(tag, out rv)) { rv = new PubsubServerSingleStreamTagHandler(); _handler_map.Add(tag, rv); } return rv; } - public void register(InternalPublishDelegate callback) - { + public void register(InternalPublishDelegate callback) { foreach (var h in _handler_map.Values) h.register(callback); } - public void doWork() - { + public void doWork() { foreach (var h in _handler_map.Values) h.doWork(); } diff --git a/src/DataStreamSuite/DataStreamCore/TableStream.cs b/src/DataStreamSuite/DataStreamCore/TableStream.cs index 211894d58..bc3977212 100644 --- a/src/DataStreamSuite/DataStreamCore/TableStream.cs +++ b/src/DataStreamSuite/DataStreamCore/TableStream.cs @@ -1,169 +1,39 @@ -using System; -using System.Collections; -using System.Data; -using BCG.Utilities; namespace BCG { + // this is the stream that gets tables directly off the pubsubServer public class TableStream : ViewStream { - public string tableName; - private ITableAccumulator myTA; - private bool myGotData = false; + private readonly string _table_name; + private readonly ITableAccumulator _ta; - public TableStream(string tableName) + + public TableStream(string table_name) : - this(tableName, null, null) { - } - - public TableStream(string tableName, ViewStreamDatabase db) - : - this(tableName, db, null) { } - - public TableStream(string tableName, string colExp) - : - this(tableName, - null, - colExp) { } + this(table_name, + ViewStreamDatabase.instance) { } - public TableStream(string ttableName, ViewStreamDatabase db, string colExp) { - tableName = DSTagManager.get_stream_tag(ttableName); - // if (colExp != null) - // mySetRealSource (new ProjectStream (new TableStream (tableName, db), colExp)); - // else - { - if (db == null) - myTA = ViewStreamDatabase.instance.getITableAccumulator(tableName); - else - myTA = db.getITableAccumulator(tableName); - } + public TableStream(string table_name, ViewStreamDatabase db) { + _table_name = table_name; + db = db == null ? ViewStreamDatabase.instance : db; + _ta = db.getITableAccumulator(_table_name); } protected override void myOnFirstSubscriber() { - myTA.onUpdate += new TableUpdateDelegate(myHandleUpdates); + _ta.on_update += new TableUpdateDelegate(_handle_updates); } protected override void myOnLastSubscriber() { - myTA.onUpdate -= new TableUpdateDelegate(myHandleUpdates); + _ta.on_update -= new TableUpdateDelegate(_handle_updates); } - protected virtual void myHandleUpdates(IBlueRowCollection newRows, IBlueRowCollection addedRows, IBlueRowCollection deletedRows) { - if (!myGotData) { - myGotData = true; - // BlueEventLog.logEvent("Received data for " + tableName + " for the first time", BlueEventLevel.Information); - } - myFireEvent(new DataPacket(newRows, addedRows, deletedRows)); + protected virtual void _handle_updates( + IBlueRowCollection new_rows, IBlueRowCollection added_rows, IBlueRowCollection del_rows) { + myFireEvent(new DataPacket(new_rows, added_rows, del_rows)); } public override string ToString() { - return GetType() + " table = " + tableName; + return $"{GetType()} table: {_table_name}"; } } - - public class ThreadedTableStream : TableStream, IExportableDataStream { - static private Lazy _vsd = new Lazy(() => new ViewStreamDatabase(), true); - public ThreadedTableStream(string table) : base(table, _vsd.Value) { - } - - public void begin_subscription() { - this.onChange += _stream_onChange; - } - - public event ExportableChangeDelegate on_change; - void _stream_onChange(object newValue) { - if (on_change != null) - on_change(newValue); - } - } - - // public class ExportableTableStream : IExportableDataStream - // { - // TableStream _stream; - // public ExportableTableStream(string table, IDataPump pump) - // { - // _stream = new TableStream(table, ((ExportableDataPump)pump).vsd.Value); - // } - - // public void begin_subscription() - // { - // _stream.onChange += _stream_onChange; - // } - - // public event ExportableChangeDelegate on_change; - // void _stream_onChange(object newValue) - // { - // if(on_change != null) - // on_change(newValue); - // } - // } - - // public class ExportableQuery : IExportableDataStream - // { - // ViewStream _stream; - // public ExportableQuery(string query, BCG.IDataPump _) - // { - // // BCG.Evaluator.DataStreamExpression.syntax parser = new BCG.Evaluator.DataStreamExpression.syntax(); - // // BCG.Evaluator.DataStreamExpression.DataStreamExpression exp = - // // (BCG.Evaluator.DataStreamExpression.DataStreamExpression)parser.Parse(query); - - // _stream = exp.getView(new System.Collections.Hashtable()); - // } - - // public void begin_subscription() - // { - // _stream.onChange += _stream_onChange; - // } - - // public event ExportableChangeDelegate on_change; - // void _stream_onChange(object newValue) - // { - // if(on_change != null) - // on_change(newValue); - // } - // } - - // public class ExportableDataPump : IDataPump - // { - // public Lazy vsd = new Lazy(() => new ViewStreamDatabase(), true); - // System.Threading.Thread _thread; - // bool _continue = true; - // public ExportableDataPump(string pumpname) - // { - // tag = pumpname; - // _thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart((_) => - // { - // while(_continue) - // { - // vsd.Value.doWork(); - // System.Threading.Thread.Sleep(50); - // } - // })); - // _thread.Name = "DataPump " + pumpname; - // _thread.IsBackground = true; - // } - // public string tag - // { - // get; - // private set; - // } - // public void start() - // { - // try - // { - // if(_thread.ThreadState != System.Threading.ThreadState.Running) - // _thread.Start(); - // } - // catch(System.Threading.ThreadStateException) { } - // } - // public void stop() - // { - // try - // { - // _continue = false; - // if(_thread.ThreadState == System.Threading.ThreadState.Running) - // _thread.Join(500); - // } - // catch(System.Threading.ThreadStateException) { } - // } - // } } diff --git a/src/DataStreamSuite/DataStreamCore/ViewStreamDatabase.cs b/src/DataStreamSuite/DataStreamCore/ViewStreamDatabase.cs index e1b2eeac8..de0552cec 100644 --- a/src/DataStreamSuite/DataStreamCore/ViewStreamDatabase.cs +++ b/src/DataStreamSuite/DataStreamCore/ViewStreamDatabase.cs @@ -15,9 +15,9 @@ namespace BCG { public class ViewStreamDatabase : IWorker, IDisposable { internal delegate void TagFireDelegate(string tag); public delegate void DoWorkDelegate(); - public event DoWorkDelegate onDoWorkStart, + private event DoWorkDelegate onDoWorkStart, onDoWorkEnd; - internal event TagFireDelegate onTagFireStart, + private event TagFireDelegate onTagFireStart, onTagFireEnd; //currently onTagUpdate is usd by the DataStreamPerfRecorder to keep track of how often the updates for various streams come in //and how big they are. @@ -82,28 +82,19 @@ namespace BCG { } } - public ICollection getCachedTables() { - List result = new List(); - - - foreach (string s in _table_accumulator_map.Keys) - if (((ITableAccumulator)_table_accumulator_map[s]).isActive()) - result.Add(s); - - return result; - } - public ISubscriberCore subscriber { get { return mySubscriberCore; } } - public ITableAccumulator getITableAccumulator(string tableName) { + public ITableAccumulator getITableAccumulator(string table_name) { // If theres a ITableAccumulator for the tableName its returned (to share subscriptions), otherwise // a new one is obtained from the Subscriber factory - - _table_accumulator_map[tableName] = _table_accumulator_map[tableName] == null ? - AccumulatorFactory.getAccumulator(tableName, mySubscriberCore) : _table_accumulator_map[tableName]; - - return _table_accumulator_map[tableName] as ITableAccumulator; + ITableAccumulator rv = null; + var table_tag_name = DSTagManager.get_stream_tag(table_name); + if (!_table_accumulator_map.TryGetValue(table_tag_name, out rv)) { + rv = AccumulatorFactory.getAccumulator(table_tag_name, mySubscriberCore); + _table_accumulator_map.Add(table_tag_name, rv); + } + return rv; } public void doWork() { @@ -136,7 +127,7 @@ namespace BCG { if (onTagFireStart != null) onTagFireStart(tag); - table_accumulator.update(tag_updates.Select(t => new MemoryStream(t)).ToArray()); + table_accumulator.handle_updates(tag_updates); if (onTagFireEnd != null) onTagFireEnd(tag); _timer.stop(); @@ -253,27 +244,4 @@ namespace BCG { #endregion } - - /* - /// - /// Returns a subscriber based on the name of the tag. Hardcoded right now, will change to config - /// later - /// - public class SubscriberFactory - { - public static ITableAccumulator getITableAccumulator (string tag, SubscriberCore subCore) - { - string tableName = tag.Substring (3); - if (!DataStreamGatewaySettings.instance.isSerializableUnderNewScheme (tableName)) - return new TableSubscriber (tag, subCore); - else - { - string subName = DataStreamGatewaySettings.instance.getSubscriber (tableName); - if (subName.Equals ("BCG.NonIncrementalTableSubscriber")) - return new NonIncrementalTableSubscriber (tag, subCore); - else - return new TableSubscriber (tag, subCore); - } - } - }*/ } diff --git a/src/DataStreamSuite/DataStreamQueryAnalyzer/MainForm.cs b/src/DataStreamSuite/DataStreamQueryAnalyzer/MainForm.cs index a82fe1f9c..cf49929e5 100644 --- a/src/DataStreamSuite/DataStreamQueryAnalyzer/MainForm.cs +++ b/src/DataStreamSuite/DataStreamQueryAnalyzer/MainForm.cs @@ -75,7 +75,7 @@ namespace BCG { private ViewStream myGetAllTagsStream() { // TODO: Port PublishedTagsStream from edge (then we can uncomment impl below) //ViewStream vs = new PubSubServerStateStream(); - ViewStream vs = new BlueRowCollectionStaticStream(); + ViewStream vs = new PubSubServerStateStream(); return new FilterStream(vs, "tag~='DS_'"); //return new LiteralStream("tag/String", "DS_Comedians;DS_Baldies"); } diff --git a/src/DataStreamSuite/PubSub/Client/MetaData/PubSubClientMessage.cs b/src/DataStreamSuite/PubSub/Client/MetaData/PubSubClientMessage.cs index 0703093cc..a2b4c724b 100644 --- a/src/DataStreamSuite/PubSub/Client/MetaData/PubSubClientMessage.cs +++ b/src/DataStreamSuite/PubSub/Client/MetaData/PubSubClientMessage.cs @@ -180,10 +180,32 @@ namespace bts { public class PubSubClientMessage : IPubSubMessage { public PubSubMessageType msg_type; // only one of these wil be non null - public SubscribeMsg sub_msg; - public UnsubscribeMsg unsub_msg; - public TransactionMsg transaction_msg; - public PublishMsg pub_msg; + public SubscribeMsg sub_msg = null; + public UnsubscribeMsg unsub_msg = null; + public TransactionMsg transaction_msg = null; + public PublishMsg pub_msg = null; + + public PubSubClientMessage() { } + + public PubSubClientMessage(SubscribeMsg sub_msg_) { + sub_msg = sub_msg_; + msg_type = PubSubMessageType.SUBSCRIIBE; + } + + public PubSubClientMessage(UnsubscribeMsg unsub_msg_) { + unsub_msg = unsub_msg_; + msg_type = PubSubMessageType.UNSUBSCRIIBE; + } + + public PubSubClientMessage(TransactionMsg transaction_msg_) { + transaction_msg = transaction_msg_; + msg_type = PubSubMessageType.TRANSACTION; + } + + public PubSubClientMessage(PublishMsg pub_msg_) { + pub_msg = pub_msg_; + msg_type = PubSubMessageType.PUBLISH; + } public void serialize_into_str(Stream str) { BinaryWriter bw = new BinaryWriter(str); diff --git a/src/DataStreamSuite/PubSub/Client/PubsubTagHandlerFactory.cs b/src/DataStreamSuite/PubSub/Client/PubsubTagHandlerFactory.cs index e2e888082..e11b14ab5 100644 --- a/src/DataStreamSuite/PubSub/Client/PubsubTagHandlerFactory.cs +++ b/src/DataStreamSuite/PubSub/Client/PubsubTagHandlerFactory.cs @@ -26,7 +26,7 @@ namespace bts { {"System_Sub", new TagHandlerEntry("System_Sub", "PubSub", "BCG.SystemSubscriptionMapPublisher")}, {"System_Stats", new TagHandlerEntry("System_Stats", "PubSub", "BCG.SystemStatsPublisher")} }; - private static TagHandlerEntry _wildcard_handler = new TagHandlerEntry("*", "DataStreamCore", "BCG.PubsubServerGenericDataHandler"); + private static TagHandlerEntry _wildcard_handler = new TagHandlerEntry("*", "DataStreamCore", "bts.PubsubServerGenericDataHandler"); private static Dictionary _handler_map = new Dictionary(); public static string assembly_location => Assembly.GetExecutingAssembly().Location; diff --git a/src/DataStreamSuite/PubSub/PublishedCache.cs b/src/DataStreamSuite/PubSub/PublishedCache.cs index 6c02d5848..034a1fb9f 100644 --- a/src/DataStreamSuite/PubSub/PublishedCache.cs +++ b/src/DataStreamSuite/PubSub/PublishedCache.cs @@ -24,7 +24,7 @@ namespace bts { public byte[] get_content(string tag, out string tag_type) { SingleTagData tag_data; - if (!_data_map.TryGetValue(tag, out tag_data)) { + if (_data_map.TryGetValue(tag, out tag_data)) { tag_type = tag_data.tag_type; return tag_data.get_current_content(); } diff --git a/src/DataStreamSuite/PubSub/PublisherCore.cs b/src/DataStreamSuite/PubSub/PublisherCore.cs index 074c75b3a..bd03b5e62 100644 --- a/src/DataStreamSuite/PubSub/PublisherCore.cs +++ b/src/DataStreamSuite/PubSub/PublisherCore.cs @@ -17,8 +17,8 @@ namespace BCG { // internal queue used to serialize pubsub method calls protected SyncQueue _main_queue = new SyncQueue(); - // all the data published through this object in snapshot form - // i.e. in a form that can be used repopulate a pubsub server + // 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 protected PublishedCache _state = new PublishedCache(); @@ -89,6 +89,7 @@ namespace BCG { } public void publish(PubSubClientMessage msg) { + Log.assert(msg.msg_type == PubSubMessageType.PUBLISH); bts.Log.Gen.info($"PublisherCore.publish msg: {msg}"); _main_queue.enqueue(msg); } @@ -125,7 +126,7 @@ namespace BCG { bts.Log.Gen.info($"PublisherCore._message_pump msg: {msg}"); switch (msg.msg_type) { case PubSubMessageType.TRANSACTION: - bts.Log.assert_d(false, "transactiosn not supported for now"); + bts.Log.assert_d(false, "transaction not supported for now"); break; case PubSubMessageType.SUBSCRIIBE: case PubSubMessageType.UNSUBSCRIIBE: @@ -251,7 +252,6 @@ namespace BCG { // } } - // updates the state and calls _send_data to send the data out protected virtual void _publish(PublishMsg msg) { bts.Log.Gen.info($"PublisherCore._publish msg: {msg}"); // update the state @@ -300,7 +300,8 @@ namespace BCG { if (conn.server_url == server_url) { string tag_type; var content_bytes = _state.get_content(tag, out tag_type); - //_send_data(tag, tag_type, tag_data); + string content_bytes_log = content_bytes == null ? "NULL" : content_bytes.Length.ToString(); + Log.Gen.info($"PublisherCore._handle_server_reboot 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/SingleTagData.cs b/src/DataStreamSuite/PubSub/Server/SingleTagData.cs index d7c0c5935..9bb3cd0ae 100644 --- a/src/DataStreamSuite/PubSub/Server/SingleTagData.cs +++ b/src/DataStreamSuite/PubSub/Server/SingleTagData.cs @@ -25,11 +25,21 @@ namespace bts { bts.Log.Gen.info($"SingleTagData constructed for tag: {tag} tag_type: {tag_type}"); _tag = tag; _tag_type = tag_type; - _tag_handler = PubsubTagHandlerFactory.get_handler(tag_type, true); + _tag_handler = get_handler(tag_type); Log.assert(_tag_handler != null); + Log.Gen.info($"SingleTagData.cons tag: {tag} tag_type: {tag_type} _tag_handler: {_tag_handler}"); _tag_handler.register(new InternalPublishDelegate(_on_handler_internal_publish)); } + public IPubSubServerTagHandler get_handler(string tag_type) { + if (tag_type == SystemSubscriptionMapPublisher.tag_type) + return SystemSubscriptionMapPublisher.getInstance(); + else if (tag_type == SystemStatsPublisher.tag_type) + return SystemStatsPublisher.get_instance(); + return PubsubTagHandlerFactory.get_handler(tag_type, true); + + } + public string tag { get { return _tag; } } public string tag_type { get { return _tag_type; } } @@ -37,12 +47,12 @@ 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} pub_msg: {pub_msg}"); + bts.Log.Gen.info($"SingleTagData.handle_publish pub_msg: {pub_msg} handler: {handler_str} "); try { _tag_handler.update(_tag, pub_msg.data_to_publish); } catch (Exception e) { - var err_msg = "SingleTagData.handle_publish pub_msg: {pub_msg} handler: {handler_str} threw exception: {e}"; + var err_msg = $"SingleTagData.handle_publish pub_msg: {pub_msg} handler: {handler_str} threw exception: {e}"; bts.Log.Gen.error(err_msg); if (e is OutOfMemoryException) throw e;