using bts; using Bts.PubSub; using Bts.PubSub.Routing; using mbts.utils; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; namespace BCG { public class PubSubRouter : IPubSubRouter { // private Regex[] mySubRouteRegExps; private PubSubRoute[] _pub_routes; private PubSubRoute[] _sub_routes; public PubSubRouter() : this(Log.notnull(PubSubConfig.Instance.Routing)) { } public PubSubRouter(IOptions config) : this(config.Value) { } public PubSubRouter(PubSubRouterConfig config) : this( ExceptionAssert.Argument.NotNullOrEmpty(config.SubscriberRoutes?.ToArray()), ExceptionAssert.Argument.NotNullOrEmpty(config.PublisherRoutes?.ToArray())) { } public PubSubRouter(PubSubRoute[] sub_routes, PubSubRoute[] pub_routes) { string log_msg = String.Empty; foreach (var route in sub_routes) { log_msg += $" sub_route: {JsonSerializer.Serialize(route)}"; } foreach (var route in pub_routes) { log_msg += $" pub_route: {JsonSerializer.Serialize(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)) { Log.assert(false, $"Failed to find route for tag '{tag}'", nameof(tag)); } Log.Gen.info($"PubSubRouter.get_sub_url_for_tag tag: {tag} route: {JsonSerializer.Serialize(route)}"); ArgumentNullException.ThrowIfNull(route.ServerAddress); return RemoteConnectionInfo.parse_url(route.ServerAddress); } public RemoteConnectionInfo get_sub_route_for_tag(string tag) { if (!_sub_routes.TryGetFirst(r => r?.IsMatch(tag) ?? false, out var route)) { Log.assert(false, $"Failed to find route for tag '{tag}'", nameof(tag)); } Log.Gen.info($"PubSubRouter.get_sub_url_for_tag tag: {tag} route: {JsonSerializer.Serialize(route)}"); ArgumentNullException.ThrowIfNull(route.ServerAddress); return RemoteConnectionInfo.parse_url(route.ServerAddress); } public List get_all_pubsub_sub_urls() => _sub_routes.Select(r => r.ServerAddress ?? throw new InvalidOperationException("Route.ServerAddress is null")).ToList(); public List get_all_pubsub_pub_urlss() => _pub_routes.Select(r => r.ServerAddress ?? throw new InvalidOperationException("Route.ServerAddress is null")).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; } } } }