fix: Make SystemSubscriptionMapPublisher threadsafe

The PubSubState.onTagMapChanged event may not be invoked on
the same thread as doWork.
This commit is contained in:
John Colvin committed 2024-10-14 17:21:46 +00:00
1 parent 7550e81aa7
commit 6e0dbe56a3
1 file changed
+26 -21
@@ -31,6 +31,7 @@ namespace BCG {
public static string tag_name = "System_AllSubscriptions";
readonly IInternalPublisher internalPublisher;
readonly IWorker workerImpl;
readonly object syncRoot = new();
public SystemSubscriptionMapPublisher(IPubSubState state, IInternalPublisher internalPublisher) {
bts.Log.Gen.info("SystemSubscriptionMapPublisher.constructor");
@@ -54,31 +55,35 @@ namespace BCG {
return rv;
};
bts.Log.Gen.info($"SystemSubscriptionMapPublisher._on_tag_state_changes tags: {tags_to_string()}");
_dirty_tags.AddRange(tags);
lock (syncRoot) {
_dirty_tags.AddRange(tags);
}
}
private void _internal_publish() {
if (_dirty_tags.Count > 0) {
List<TagPubSubInfo> tpsis = new List<TagPubSubInfo>();
foreach (string tag in _dirty_tags) {
Dictionary<string, string> subscribers, active_pubslishers;
ICollection<Pair<string, string>> dead_publishers;
_state.get_all_connections(tag, out subscribers, out active_pubslishers, out dead_publishers);
TagPubSubInfo ti = new TagPubSubInfo(tag, subscribers, active_pubslishers,
dead_publishers, _ip);
tpsis.Add(ti);
lock (syncRoot) {
if (_dirty_tags.Count > 0) {
List<TagPubSubInfo> tpsis = new List<TagPubSubInfo>();
foreach (string tag in _dirty_tags) {
Dictionary<string, string> subscribers, active_pubslishers;
ICollection<Pair<string, string>> dead_publishers;
_state.get_all_connections(tag, out subscribers, out active_pubslishers, out dead_publishers);
TagPubSubInfo ti = new TagPubSubInfo(tag, subscribers, active_pubslishers,
dead_publishers, _ip);
tpsis.Add(ti);
}
_dirty_tags.Clear();
var ser_bytes = TagPubSubInfo.serialize(tpsis);
PublishMsg pub_msg = new PublishMsg() {
publish_time_epoch_ms = 0,
tag = SystemSubscriptionMapPublisher.tag_name,
tag_type = SystemSubscriptionMapPublisher.tag_type,
connection = "Internal",
is_compressed = false,
data_to_publish = ser_bytes
};
internalPublisher.Publish(pub_msg);
}
_dirty_tags.Clear();
var ser_bytes = TagPubSubInfo.serialize(tpsis);
PublishMsg pub_msg = new PublishMsg() {
publish_time_epoch_ms = 0,
tag = SystemSubscriptionMapPublisher.tag_name,
tag_type = SystemSubscriptionMapPublisher.tag_type,
connection = "Internal",
is_compressed = false,
data_to_publish = ser_bytes
};
internalPublisher.Publish(pub_msg);
}
}