public ChannelFactory(RawRabbitConfiguration config, IConnectionFactory connectionFactory)
        {
            _connectionFactory = connectionFactory;
            _accessDictionary = new ConcurrentDictionary<IModel, DateTime>();
            _config = config;
            _threadChannels = new ThreadLocal<IModel>(true);

            try
            {
                _logger.LogDebug("Connecting to primary host.");
                _connection = _connectionFactory.CreateConnection(_config.Hostnames);
                _logger.LogInformation("Successfully established connection.");
            }
            catch (BrokerUnreachableException e)
            {
                _logger.LogError("Unable to connect to broker", e);
                throw e.InnerException;
            }
            _closeTimer = new System.Threading.Timer(state =>
            {
                var enumerator = _accessDictionary.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    if (DateTime.Now - enumerator.Current.Value > _config.RequestTimeout)
                    {
                        DateTime lastUsed;
                        if (_accessDictionary.TryRemove(enumerator.Current.Key, out lastUsed))
                        {
                            _logger.LogInformation($"Channel {enumerator.Current.Key.ChannelNumber} was last used {lastUsed}. Closing...");
                            enumerator.Current.Key.Close();
                        }
                    }
                }
            }, null, _config.RequestTimeout, _config.RequestTimeout);
        }
        public async Task PublishAsync <TEvent>(TEvent @event, ICorrelationContext context, string tenant = null)
            where TEvent : IEvent
        {
            //  Parallel.ForEach(_busClient, busclient => busclient.PublishAsync(@event, ctx => ctx.UseMessageContext(context)));

            IBusClient client = _busClient.Where(x =>
            {
                //PropertyInfo propertyInfo = typeof(BusClient).GetProperty("_contextFactory", BindingFlags.NonPublic | BindingFlags.Instance);

                //MethodInfo getter = propertyInfo.GetGetMethod(nonPublic: true);

                RawRabbit.Pipe.PipeContextFactory pipeContextFactory = typeof(RawRabbit.BusClient).GetField("_contextFactory", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(x) as PipeContextFactory;



                //PropertyInfo propertyInfoPipeContextFactory = typeof(PipeContextFactory).GetProperty("_config", BindingFlags.NonPublic | BindingFlags.Instance);

                //MethodInfo getterPipeContextFactory = propertyInfoPipeContextFactory.GetGetMethod(nonPublic: true);

                //RawRabbitConfiguration RawRabbitConfiguration = (RawRabbitConfiguration)getterPipeContextFactory.Invoke(PipeContextFactory, null);

                RawRabbit.Configuration.RawRabbitConfiguration RawRabbitConfiguration = typeof(RawRabbit.Pipe.PipeContextFactory).GetField("_config", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(pipeContextFactory) as RawRabbit.Configuration.RawRabbitConfiguration;

                if (RawRabbitConfiguration.VirtualHost == tenant)
                {
                    return(true);
                }

                return(false);
            }).SingleOrDefault();


            await client.PublishAsync(@event, ctx => ctx.UseMessageContext(context));
        }
 /// <summary>
 /// Changes the configuration so that it does not use PersistentDeliveryMode. Also,
 /// it sets the exchange type to Direct to increase performance, however that
 /// disables the ability to use the MessageSequence extension.
 /// </summary>
 /// <param name="config">The RawRabbit configuration object</param>
 /// <returns></returns>
 public static RawRabbitConfiguration AsHighPerformance(this RawRabbitConfiguration config)
 {
     config.PersistentDeliveryMode = false;
     config.RouteWithGlobalId      = false;
     config.Exchange.Type          = ExchangeType.Direct;
     return(config);
 }
        public static RawRabbitConfiguration Parse(string connectionString)
        {
            var cfg = new RawRabbitConfiguration();

            var brokersMatch = _brokers.Match(connectionString);
            var brokerStrs = brokersMatch.Groups["brokers"].Value.Split(',');

            foreach (var broker in brokerStrs)
            {
                int port;
                var brokerMatch = _broker.Match(broker);
                var brokerCfg = new BrokerConfiguration
                {
                    Hostname = brokerMatch.Groups["host"].Value,
                    VirtualHost = brokerMatch.Groups["vhost"].Value,
                    Port = int.TryParse(brokerMatch.Groups["port"].Value, out port) ? port : default(int),
                    Username = brokerMatch.Groups["user"].Value,
                    Password = brokerMatch.Groups["password"].Value,
                };
                cfg.Brokers.Add(brokerCfg);
            }

            var reqMatch = _requestTimeout.Match(connectionString);
            var timeoutGrp = reqMatch.Groups["timeout"];
            if (timeoutGrp.Success)
            {
                cfg.RequestTimeout = TimeSpan.FromSeconds(int.Parse(timeoutGrp.Value));
            }

            return cfg;
        }
 public BindingProvider(RawRabbitConfiguration config)
 {
     _config = config;
     var vHost = string.Equals(config.VirtualHost, DefaultVhost)
         ? UriEncodedDefaultVhost
         : config.VirtualHost;
     _baseUrl = $"http://{config.Hostnames.FirstOrDefault()}:15672/api/exchanges/{vHost}";
 }
		public ChannelFactory(IConnectionFactory connectionFactory, RawRabbitConfiguration config, ChannelFactoryConfiguration channelConfig)
		{
			_connectionFactory = connectionFactory;
			_config = config;
			_channelConfig = channelConfig;
			_requestQueue = new ConcurrentQueue<TaskCompletionSource<IModel>>();
			_channels = new LinkedList<IModel>();

			ConnectToBroker();
			Initialize();
		}
		public async void Should_Use_Guest_Credentials_By_Default()
		{
			/* Setup */
			var config = new RawRabbitConfiguration();

			/* Test */
			BusClientFactory.CreateDefault(config);

			/* Assert */
			Assert.True(true, "Does not throw.");
		}
		public static RawRabbitConfiguration Parse(string connectionString)
		{
			var mainMatch = MainRegex.Match(connectionString);
			var port = Defaults.Port;
			if (RegexMatchGroupIsNonEmpty(mainMatch, "port"))
			{
				var suppliedPort = mainMatch.Groups["port"].Value;
				if (!int.TryParse(suppliedPort, out port))
				{
					throw new FormatException($"The supplied port '{suppliedPort}' in the connection string is not a number");
				}
			}

			var cfg = new RawRabbitConfiguration
			{
				Username = RegexMatchGroupIsNonEmpty(mainMatch, "username") ? mainMatch.Groups["username"].Value : Defaults.Username,
				Password = RegexMatchGroupIsNonEmpty(mainMatch, "password") ? mainMatch.Groups["password"].Value : Defaults.Password,
				Hostnames = mainMatch.Groups["hosts"].Value.Split(',').ToList(),
				Port = port,
				VirtualHost = ExctractVirutalHost(mainMatch)
			};

			var parametersMatches = ParametersRegex.Matches(mainMatch.Groups["parameters"].Value);
			foreach (Match match in parametersMatches)
			{
				var name = match.Groups["name"].Value.ToLower();
				var val = match.Groups["value"].Value.ToLower();
				var propertyInfo = cfg
					.GetType()
					.GetTypeInfo()
					.GetProperty(name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

				if (propertyInfo == null)
				{
					throw new ArgumentException($"No configuration property named '{name}'");
				}

				if (propertyInfo.PropertyType == typeof (TimeSpan))
				{
					var convertedValue = TimeSpan.FromSeconds(int.Parse(val));
					propertyInfo.SetValue(cfg, convertedValue, null);
				}
				else
				{
					propertyInfo.SetValue(cfg, Convert.ChangeType(val, propertyInfo.PropertyType), null);
				}
			}

			return cfg;
		}
		public BindingProvider(RawRabbitConfiguration config)
		{
			var vHost = string.Equals(config.VirtualHost, DefaultVhost)
					? UriEncodedDefaultVhost
					: config.VirtualHost;

			_httpClient = new HttpClient(new HttpClientHandler
			{
				Credentials = new NetworkCredential(config.Username, config.Password)
			})
			{
				BaseAddress = new Uri($"http://{config.Hostnames.FirstOrDefault()}:15672/api/exchanges/{vHost}/")
			};
		}
		public ChannelFactoryTests()
		{
			_connectionFactory = new Mock<IConnectionFactory>();
			_connection = new Mock<IConnection>();
			_firstChannel = new Mock<IModel>();
			_secondChannel = new Mock<IModel>();
			_thirdChannel = new Mock<IModel>();
			_config = RawRabbitConfiguration.Local;
			_channelConfig = ChannelFactoryConfiguration.Default;

			_connectionFactory
				.Setup(c => c.CreateConnection(It.IsAny<IList<string>>()))
				.Returns(_connection.Object);
		}
        public RawRabbitConfiguration Parse(IConfiguration root)
        {
            if (root == null)
            {
                throw new ArgumentNullException(nameof(root));
            }

            var cfg = new RawRabbitConfiguration();

            var timeout = root["Data:RawRabbit:RequestTimeout"];
            if (timeout != null)
            {
                cfg.RequestTimeout = ParseToTimeSpan(timeout);
            }

            bool autoDelete;
            if(bool.TryParse(root["Data:RawRabbit:Queue:AutoDelete"], out autoDelete))
            {
                cfg.Queue.AutoDelete = autoDelete;
            }
            bool durable;
            if (bool.TryParse(root["Data:RawRabbit:Queue:Durable"], out durable))
            {
                cfg.Queue.Durable = durable;
            }
            bool exclusive;
            if (bool.TryParse(root["Data:RawRabbit:Queue:Exclusive"], out exclusive))
            {
                cfg.Queue.Exclusive = exclusive;
            }
            bool xcAutoDelete;
            if (bool.TryParse(root["Data:RawRabbit:Exchange:AutoDelete"], out xcAutoDelete))
            {
                cfg.Exchange.AutoDelete= xcAutoDelete;
            }
            bool xcDurable;
            if (bool.TryParse(root["Data:RawRabbit:Exchange:Durable"], out xcDurable))
            {
                cfg.Exchange.Durable = xcDurable;
            }
            ExchangeType type;
            if (Enum.TryParse(root["Data:RawRabbit:Exchange:Type"], out type))
            {
                cfg.Exchange.Type = type;
            }

            cfg.Brokers = GetBrokers(root);
            return cfg;
        }
		public async Task Should_Give_Clear_Error_Message_If_User_Does_Not_Exist()
		{
			/* Setup */
			var config = new RawRabbitConfiguration
			{
				Username = "******",
				Password = "******",
				Hostnames = {"localhost"},
				VirtualHost = "/",
				Port = 5672
			};

			/* Test */
			/* Assert */
			Assert.ThrowsAny<AuthenticationFailureException>(() => TestClientFactory.CreateNormal(ioc => ioc.AddSingleton(p => config)));
		}
		public async Task Should_Not_Throw_If_Credentials_Are_Correct()
		{
			/* Setup */
			var config = new RawRabbitConfiguration
			{
				Username = "******",
				Password = "******",
				Hostnames = new List<string> {"localhost"},
				VirtualHost = "/",
				Port = 5672
			};

			/* Test */
			BusClientFactory.CreateDefault(config);

			/* Assert */
			Assert.True(true, "Does not throw.");
		}
		public async Task Should_Not_Throw_If_Credentials_Are_Correct()
		{
			/* Setup */
			var config = new RawRabbitConfiguration
			{
				Username = "******",
				Password = "******",
				Hostnames = new List<string> {"localhost"},
				VirtualHost = "/",
				Port = 5672
			};

			/* Test */
			var b = TestClientFactory.CreateNormal(ioc => ioc.AddSingleton(p => config));
			b.Dispose();

			/* Assert */
			Assert.True(true, "Does not throw.");
		}
Exemple #15
0
        public ChannelFactory(IConnectionFactory connectionFactory, RawRabbitConfiguration config, ChannelFactoryConfiguration channelConfig)
        {
            try
            {
                _connection = connectionFactory.CreateConnection(config.Hostnames);
            }
            catch (BrokerUnreachableException e)
            {
                _logger.LogError("Unable to connect to broker", e);
                throw e.InnerException;
            }
            _connectionFactory = connectionFactory;
            _config = config;
            _channelConfig = channelConfig;
            _requestQueue = new ConcurrentQueue<TaskCompletionSource<IModel>>();
            _channels = new LinkedList<IModel>();

            Initialize();
        }
        public IDictionary<string, object> GetClientProperties(RawRabbitConfiguration cfg = null)
        {
            var props = new Dictionary<string, object>
            {
                { "product", "RawRabbit" },
                { "version", typeof(BusClient).Assembly.GetName().Version.ToString() },
                { "platform", ".NET" },
                { "client_directory", typeof(BusClient).Assembly.CodeBase},
                { "client_server", Environment.MachineName },
            };

            if (cfg != null)
            {
                props.Add("request_timeout", cfg.RequestTimeout.ToString("g"));
                props.Add("broker_username", cfg.Username);
            }

            return props;
        }
Exemple #17
0
        public ChannelFactory(RawRabbitConfiguration config, IConnectionFactory connectionFactory)
        {
            _connectionFactory = connectionFactory;

            _config = config;
            _threadChannels = new ThreadLocal<IModel>(true);

            try
            {
                _logger.LogDebug("Connecting to primary host.");
                _connection = _connectionFactory.CreateConnection(_config.Hostnames);
                _logger.LogInformation("Successfully established connection.");
            }
            catch (BrokerUnreachableException e)
            {
                _logger.LogError("Unable to connect to broker", e);
                throw e.InnerException;
            }
        }
        public IDictionary<string, object> GetClientProperties(RawRabbitConfiguration cfg = null, BrokerConfiguration brokerCfg = null)
        {
            var props = new Dictionary<string, object>
            {
                { "client_api", "RawRabbit" },
                { "client_version", typeof(BusClient).Assembly.GetName().Version.ToString() },
                { "client_directory", typeof(BusClient).Assembly.CodeBase},
                { "client_connected", DateTime.UtcNow.ToString("u") },
                { "client_server", Environment.MachineName },
            };
            if (brokerCfg != null)
            {
                props.Add("broker_username", brokerCfg.Username);
            }
            if (cfg != null)
            {
                props.Add("request_timeout", cfg.RequestTimeout.ToString("g"));
            }

            return props;
        }
		public async void Should_Give_Clear_Error_Message_If_User_Does_Not_Exist()
		{
			/* Setup */
			var config = new RawRabbitConfiguration
			{
				Brokers =
				{
					new BrokerConfiguration
					{
						Username = "******",
						Password = "******",
						Hostname = "localhost",
						VirtualHost = "/"
					}
				}
			};

			/* Test */
			/* Assert */
			Assert.ThrowsAny<AuthenticationFailureException>(() => BusClientFactory.CreateDefault(config));
		}
		public static RawRabbitConfiguration Parse(string connectionString)
		{
			var mainMatch = MainRegex.Match(connectionString);
			var cfg = new RawRabbitConfiguration
			{
				Username = mainMatch.Groups["username"].Value,
				Password = mainMatch.Groups["password"].Value,
				VirtualHost = mainMatch.Groups["vhost"].Value,
				Port = int.Parse(mainMatch.Groups["port"].Value),
				Hostnames = mainMatch.Groups["hosts"].Value.Split(',').ToList()
			};

			var reqMatch = RequestTimeout.Match(connectionString);
			var timeoutGrp = reqMatch.Groups["timeout"];
			if (timeoutGrp.Success)
			{
				cfg.RequestTimeout = TimeSpan.FromSeconds(int.Parse(timeoutGrp.Value));
			}

			return cfg;
		}
		public async void Should_Not_Throw_If_Credentials_Are_Correct()
		{
			/* Setup */
			var config = new RawRabbitConfiguration
			{
				Brokers =
				{
					new BrokerConfiguration
					{
						Username = "******",
						Password = "******",
						Hostname = "localhost",
						VirtualHost = "/"
					}
				}
			};

			/* Test */
			BusClientFactory.CreateDefault(config);

			/* Assert */
			Assert.True(true, "Does not throw.");
		}
 /// <summary>
 /// Disables RouteWithGlobalId to keep routing keys intact with older versions of
 /// RawRabbit and sets exchange type to Direct.
 /// </summary>
 /// <param name="config"></param>
 /// <returns></returns>
 public static RawRabbitConfiguration AsLegacy(this RawRabbitConfiguration config)
 {
     config.Exchange.Type     = ExchangeType.Direct;
     config.RouteWithGlobalId = false;
     return(config);
 }