public bool TryGetConnection(string path, out PersistentConnection connection) { if (path == null) { throw new ArgumentNullException("path"); } connection = null; if (!String.IsNullOrEmpty(_hubPath) && path.StartsWith(_hubPath, StringComparison.OrdinalIgnoreCase)) { connection = new HubDispatcher(_hubPath); return(true); } foreach (var pair in _connectionMapping) { // If the url matches then create the connection type if (path.StartsWith(pair.Key, StringComparison.OrdinalIgnoreCase)) { var factory = new PersistentConnectionFactory(_resolver); connection = factory.CreateInstance(pair.Value); return(true); } } return(false); }
private void SubsManager_OnEventReplyRemoved(object sender, string eventName) { if (!PersistentConnection.IsConnected) { PersistentConnection.TryConnect(); } using (var channel = PersistentConnection.CreateModel()) { channel.QueueUnbind(QueueName, ExchangeDeclareParameters.ExchangeName, eventName); channel.QueueUnbind(_queueNameReply, ExchangeDeclareParameters.ExchangeName, eventName); } if (!SubsManager.IsReplyEmpty) { return; } QueueName = string.Empty; ConsumerChannel?.Close(); //ToDo _queueNameReply = string.Empty; _consumerChannelReply?.Close(); }
public override async ValueTask Publish(IIntegrationEvent @event) { if (!PersistentConnection.IsConnected) { PersistentConnection.TryConnect(); } var policy = Policy.Handle <BrokerUnreachableException>() .Or <SocketException>() .Or <Exception>() .WaitAndRetryForever(retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) => { Logger.LogWarning(ex.ToString()); }); using var channel = PersistentConnection.CreateModel(); var routingKey = @event.RoutingKey; channel.ExchangeDeclare(ExchangeDeclareParameters.ExchangeName, ExchangeDeclareParameters.ExchangeType, ExchangeDeclareParameters.ExchangeDurable, ExchangeDeclareParameters.ExchangeAutoDelete); await using var ms = new MemoryStream(); Serializer.Serialize(ms, @event); var body = ms.ToArray(); policy.Execute(() => { var properties = channel.CreateBasicProperties(); properties.DeliveryMode = 1; //2 = persistent, write on disk properties.CorrelationId = _correlationId; properties.ReplyTo = _queueNameReply; channel.BasicPublish(ExchangeDeclareParameters.ExchangeName, routingKey, true, properties, body); }); }
public IHttpHandler GetHttpHandler(RequestContext requestContext) { var factory = (IPersistentConnectionFactory)_resolver.GetService(typeof(IPersistentConnectionFactory)); PersistentConnection connection = factory.CreateInstance(_handlerType); return(new AspNetHost(connection)); }
public IHttpHandler GetHttpHandler(RequestContext requestContext) { var factory = new PersistentConnectionFactory(_resolver); PersistentConnection connection = factory.CreateInstance(_handlerType); return(new AspNetHandler(_resolver, connection)); }
public void If_connects_after_disposal_should_redispose_underlying_connection() { var eventBus = Substitute.For <IEventBus>(); var connectionFactory = Substitute.For <IConnectionFactory>(); var mockConnection = Substitute.For <IConnection>(); PersistentConnection mockPersistentConnection = Substitute.For <PersistentConnection>(connectionFactory, eventBus); // This test is constructed using small delays, such that the IConnectionFactory will return a connection just _after the IPersistentConnection has been disposed. TimeSpan shimDelay = TimeSpan.FromSeconds(0.5); connectionFactory.CreateConnection().Returns(a => { Thread.Sleep(shimDelay.Double()); return(mockConnection); }); Task.Factory.StartNew(() => { mockPersistentConnection.Initialize(); }); // Start the persistent connection attempting to connect. Thread.Sleep(shimDelay); // Allow some time for the persistent connection code to try to create a connection. // First call to dispose. Because CreateConnection() is stubbed to delay for shimDelay.Double(), it will not yet have returned a connection. So when the PersistentConnection is disposed, no underlying IConnection should yet be disposed. mockPersistentConnection.Dispose(); mockConnection.DidNotReceive().Dispose(); Thread.Sleep(shimDelay.Double()); // Allow time for persistent connection code to _return its connection ... // Assert that the connection returned from connectionFactory.CreateConnection() (_after the PersistentConnection was disposed), still gets disposed. mockConnection.Received().Dispose(); // Ensure that PersistentConnection also did not flag (eg to IPersistentChannel) the late-made connection as successful. connectionFactory.DidNotReceive().Success(); // Ensure that PersistentConnection does not retry after was disposed. connectionFactory.DidNotReceive().Next(); }
public void Should_retry_connection_for_expected_connection_types_OnConnected(Type exceptionType) { var mockBuilder = new MockBuilder(); using (mockBuilder.Bus) { var first = true; var succeeded = false; mockBuilder.ConnectionFactory.Succeeded.Returns(c => succeeded); mockBuilder.ConnectionFactory.When(x => x.Success()).Do(c => succeeded = true); mockBuilder.ConnectionFactory.Configuration.ConnectIntervalAttempt = TimeSpan.FromSeconds(1); var connection = new PersistentConnection(mockBuilder.ConnectionFactory, mockBuilder.EventBus); mockBuilder.EventBus.Subscribe <ConnectionCreatedEvent>(e => { if (first) { first = false; ThrowException(exceptionType); } }); connection.Initialize(); Thread.Sleep(TimeSpan.FromSeconds(2)); mockBuilder.ConnectionFactory.Received(3).CreateConnection(); first.ShouldEqual(false); } }
public void If_connects_after_disposal_should_redispose_underlying_connection() { var logger = MockRepository.GenerateMock <IEasyNetQLogger>(); var eventBus = MockRepository.GenerateMock <IEventBus>(); var connectionFactory = MockRepository.GenerateMock <IConnectionFactory>(); var mockConnection = MockRepository.GenerateMock <IConnection>(); PersistentConnection mockPersistentConnection = MockRepository.GenerateMock <PersistentConnection>(connectionFactory, logger, eventBus); // This test is constructed using small delays, such that the IConnectionFactory will return a connection just _after the IPersistentConnection has been disposed. TimeSpan shimDelay = TimeSpan.FromSeconds(0.5); connectionFactory.Expect(cf => cf.CreateConnection()).WhenCalled(a => { Thread.Sleep(shimDelay.Double()); a.ReturnValue = mockConnection; }).Repeat.Once(); Task.Factory.StartNew(() => { mockPersistentConnection.Initialize(); }); // Start the persistent connection attempting to connect. Thread.Sleep(shimDelay); // Allow some time for the persistent connection code to try to create a connection. // First call to dispose. Because CreateConnection() is stubbed to delay for shimDelay.Double(), it will not yet have returned a connection. So when the PersistentConnection is disposed, no underlying IConnection should yet be disposed. mockPersistentConnection.Dispose(); mockConnection.AssertWasNotCalled(underlyingConnection => underlyingConnection.Dispose()); Thread.Sleep(shimDelay.Double()); // Allow time for persistent connection code to _return its connection ... // Assert that the connection returned from connectionFactory.CreateConnection() (_after the PersistentConnection was disposed), still gets disposed. mockConnection.AssertWasCalled(latedCreatedUnderlyingConnection => latedCreatedUnderlyingConnection.Dispose()); // Ensure that PersistentConnection also did not flag (eg to IPersistentChannel) the late-made connection as successful. connectionFactory.AssertWasNotCalled(c => c.Success()); // Ensure that PersistentConnection does not retry after was disposed. connectionFactory.AssertWasNotCalled(c => c.Next()); }
public IConnection GetPublishConnection() { //note: The purpose is there so that we/users can add more advanced connection managers in the future lock (connectionFactory) { return connectionPublish ?? (connectionPublish = new PersistentConnection(connectionFactory, connectionConfiguration.RetryDelay)); } }
public EventBusRabbitMQ(IOptionsMonitor <RabbitMQOptions> options, PersistentConnection connection, IEventExecutor eventExecutor, ILogger <EventBusRabbitMQ> logger ) { _options = options.CurrentValue; _logger = logger; _eventExecutor = eventExecutor; _connection = connection; _consumerChannel = CreateConsumerChannel(); }
public IConnection GetConnection(ConnectionPurpose purpose) { //note: The purpose is there so that we/users can add more advanced connection managers in the future lock (connectionFactory) { if (connectionFailed) throw connectionFailedReason; return connection ?? (connection = new PersistentConnection(connectionFactory, connectionConfiguration.RetryDelay)); } }
public void CreatesInstanceIfTypeIsPersistentConnection() { // Arrange var resolver = new Mock <IDependencyResolver>(); var factory = new PersistentConnectionFactory(resolver.Object); // Act PersistentConnection connection = factory.CreateInstance(typeof(MyConnection)); // Assert Assert.NotNull(connection); }
public bool TryGetConnection(string path, out PersistentConnection connection) { connection = null; if (_hubsEnabled && path.StartsWith("/signalr", StringComparison.OrdinalIgnoreCase)) { connection = new HubDispatcher("/signalr"); return(true); } return(TryGetMappedConnection(path, out connection)); }
public void Should_establish_connection_when_persistent_connection_created() { var mockBuilder = new MockBuilder(); using var connection = new PersistentConnection( new ConnectionConfiguration(), mockBuilder.ConnectionFactory, mockBuilder.EventBus ); connection.CreateModel(); connection.IsConnected.Should().BeTrue(); mockBuilder.ConnectionFactory.Received(1).CreateConnection(Arg.Any <IList <AmqpTcpEndpoint> >()); }
public void Should_not_retry_connection_for_unexpected_connection_types() { var mockBuilder = new MockBuilder(); using (mockBuilder.Bus) { mockBuilder.ConnectionFactory.Configuration.ConnectIntervalAttempt = TimeSpan.FromSeconds(1); mockBuilder.ConnectionFactory.CreateConnection().Returns(c => { ThrowException(typeof(Exception)); return(null); }); var connection = new PersistentConnection(mockBuilder.ConnectionFactory, mockBuilder.EventBus); Assert.Throws <Exception>(() => connection.Initialize()); } }
public void Should_be_not_connected_if_connection_not_established() { var mockBuilder = new MockBuilder(); mockBuilder.ConnectionFactory.CreateConnection(Arg.Any <IList <AmqpTcpEndpoint> >()) .Returns(c => throw new Exception("Test")); using var connection = new PersistentConnection( new ConnectionConfiguration(), mockBuilder.ConnectionFactory, mockBuilder.EventBus ); Assert.Throws <Exception>(() => connection.CreateModel()); connection.IsConnected.Should().BeFalse(); mockBuilder.ConnectionFactory.Received().CreateConnection(Arg.Any <IList <AmqpTcpEndpoint> >()); }
private static AppDelegate ExecuteConnection(Func <IDictionary <string, object>, PersistentConnection> factory) { return((environment, result, fault) => { // Read the request body then process the request. ParseBodyAsync(environment).ContinueWith(task => { if (task.IsFaulted) { // There was an error reading the body fault(task.Exception); } else { var request = new OwinRequest(environment, task.Result); var origin = request.Headers["Origin"]; var response = new OwinResponse(result, origin); var hostContext = new HostContext(request, response); try { PersistentConnection connection = factory(environment); connection .ProcessRequestAsync(hostContext) .ContinueWith(innerTask => { if (innerTask.IsFaulted) { fault(innerTask.Exception); } else { response.End().Catch(); } }); } catch (Exception ex) { fault(ex); } } }); }); }
/// <summary> /// Do a passive exchange declaration. /// Or /// (Spec method) Declare an exchange. /// This method performs a "passive declare" on an exchange, which verifies whether. It will do nothing if the exchange already exists and result in a channel-levelprotocol exception (channel closure) if not. /// </summary> /// <param name="persistentConnection"></param> /// <param name="exchange"></param> /// <param name="type"></param> /// <param name="durable"></param> /// <param name="autoDelete"></param> /// <param name="arguments"></param> public static IModel ExchangeDeclare(this PersistentConnection persistentConnection, string exchange, string type = ExchangeType.Topic, bool durable = true, bool autoDelete = false, IDictionary <string, object> arguments = null) { IModel channel; try { channel = persistentConnection.CreateModel(); channel.ExchangeDeclarePassive(exchange); } catch { channel = persistentConnection.CreateModel(); channel.ExchangeDeclare(exchange, type, durable, autoDelete, arguments); } return(channel); }
public When_using_default_consumer_error_strategy() { var customConventions = new Conventions(new DefaultTypeNameSerializer()) { ErrorQueueNamingConvention = info => "CustomEasyNetQErrorQueueName", ErrorExchangeNamingConvention = info => "CustomErrorExchangePrefixName." + info.RoutingKey }; mockBuilder = new MockBuilder(); var connectionConfiguration = new ConnectionConfiguration(); var connection = new PersistentConnection(connectionConfiguration, mockBuilder.ConnectionFactory, new EventBus()); errorStrategy = new DefaultConsumerErrorStrategy( connection, new JsonSerializer(), customConventions, new DefaultTypeNameSerializer(), new DefaultErrorMessageSerializer(), connectionConfiguration ); const string originalMessage = ""; var originalMessageBody = Encoding.UTF8.GetBytes(originalMessage); var context = new ConsumerExecutionContext( (bytes, properties, info, cancellation) => Task.FromResult(AckStrategies.Ack), new MessageReceivedInfo("consumerTag", 0, false, "orginalExchange", "originalRoutingKey", "queue"), new MessageProperties { CorrelationId = string.Empty, AppId = string.Empty }, originalMessageBody ); try { errorAckStrategy = errorStrategy.HandleConsumerError(context, new Exception()); cancelAckStrategy = errorStrategy.HandleConsumerCancelled(context); } catch (Exception) { // swallow } }
public void UsesDependencyResolver() { // Arrange var resolver = new Mock <IDependencyResolver>(); var factory = new PersistentConnectionFactory(resolver.Object); var otherConnection = new MyOtherConnection(); resolver.Setup(m => m.GetService(typeof(MyConnection))) .Returns(otherConnection); // Act PersistentConnection connection = factory.CreateInstance(typeof(MyConnection)); // Assert Assert.NotNull(connection); Assert.Same(otherConnection, connection); }
private bool TryGetMappedConnection(string path, out PersistentConnection connection) { connection = null; foreach (var pair in _connectionMapping) { // If the url matches then create the connection type if (path.StartsWith(pair.Key, StringComparison.OrdinalIgnoreCase)) { var factory = DependencyResolver.Resolve <IPersistentConnectionFactory>(); connection = factory.CreateInstance(pair.Value); return(true); } } return(false); }
private void DoInternalSubscriptionRpc(string eventName, string eventNameResult) { var containsKey = SubsManager.HasSubscriptionsForEvent(eventName); if (containsKey) { return; } if (!PersistentConnection.IsConnected) { PersistentConnection.TryConnect(); } using var channel = PersistentConnection.CreateModel(); channel.QueueBind(QueueName, ExchangeDeclareParameters.ExchangeName, eventName); channel.QueueBind(_queueNameReply, ExchangeDeclareParameters.ExchangeName, eventNameResult); }
public override Task Invoke(IOwinContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (JsonUtility.TryRejectJSONPRequest(_configuration, context)) { return(TaskAsyncHelper.Empty); } var connectionFactory = new PersistentConnectionFactory(_configuration.Resolver); PersistentConnection connection = connectionFactory.CreateInstance(_connectionType); connection.Initialize(_configuration.Resolver); return(connection.ProcessRequest(context.Environment)); }
public async Task <TR> CallAsync <TR>(IIntegrationEvent @event, CancellationToken cancellationToken = default) where TR : IIntegrationEventReply { if (!PersistentConnection.IsConnected) { PersistentConnection.TryConnect(); } var policy = Policy.Handle <BrokerUnreachableException>() .Or <SocketException>() .Or <Exception>() .WaitAndRetryForever(retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) => { Logger.LogWarning(ex.ToString()); }); using var channel = PersistentConnection.CreateModel(); var routingKey = @event.RoutingKey; channel.ExchangeDeclare(ExchangeDeclareParameters.ExchangeName, ExchangeDeclareParameters.ExchangeType, ExchangeDeclareParameters.ExchangeDurable, ExchangeDeclareParameters.ExchangeAutoDelete); await using var ms = new MemoryStream(); Serializer.Serialize(ms, @event); var body = ms.ToArray(); var correlationId = Guid.NewGuid().ToString(); var tcs = new TaskCompletionSource <dynamic>(); _callbackMapper.TryAdd(correlationId, tcs); policy.Execute(() => { var properties = channel.CreateBasicProperties(); properties.DeliveryMode = 1; //2 = persistent, write on disk properties.CorrelationId = correlationId; properties.ReplyTo = QueueName; channel.BasicPublish(ExchangeDeclareParameters.ExchangeName, routingKey, true, properties, body); }); cancellationToken.Register(() => _callbackMapper.TryRemove(correlationId, out var tmp)); return(await tcs.Task); }
public void Should_retry_connection_for_expected_connection_types_CreateConnection(Type exceptionType) { var mockBuilder = new MockBuilder(); using (mockBuilder.Bus) { mockBuilder.ConnectionFactory.Configuration.ConnectIntervalAttempt = TimeSpan.FromSeconds(1); mockBuilder.ConnectionFactory.Succeeded.Returns(false, true); mockBuilder.ConnectionFactory.CreateConnection().Returns(c => { ThrowException(exceptionType); return(null); }, c => mockBuilder.Connection); var connection = new PersistentConnection(mockBuilder.ConnectionFactory, mockBuilder.EventBus); connection.Initialize(); connection.IsConnected.ShouldEqual(false); Thread.Sleep(TimeSpan.FromSeconds(2)); connection.IsConnected.ShouldEqual(true); mockBuilder.ConnectionFactory.Received(3).CreateConnection(); } }
protected virtual void Dispose(bool disposing) { if (disposed) { return; } if (disposing) { // Dispose managed resources. if (connection == null) { return; } connection.Dispose(); connection = null; } disposed = true; }
private static void ConnectToRemoteShares() { CleanupLog.WriteMethod(); List <string> remoteShares = new List <string>(); ConfigurationSettings.DirectoriesToCleanup.ForEach(path => { if (path.StartsWith(@"\\")) { var rootPath = Path.GetPathRoot(path); remoteShares.Add(rootPath.Trim().ToUpper()); } }); CleanupLog.WriteLine($"{remoteShares.Distinct().Count()} Remote Shares Needed."); remoteShares.Distinct().ToList().ForEach(path => { CleanupLog.WriteLine($"Connecting to Remote Share: {path}, with: Username: {ConfigurationSettings.Username}, Password: {ConfigurationSettings.Password}"); var connection = new PersistentConnection(path, new System.Net.NetworkCredential(ConfigurationSettings.Username, ConfigurationSettings.Password)); }); }
/// <summary> /// /// </summary> /// <param name="services"></param> /// <param name="connectionString"></param> /// <param name="eventBusOptionAction"></param> /// <returns></returns> public static void AddRabbitMQEventBus(this Container container, string connectionString, Action <ConnectionConfigurationBuild> eventBusOptionAction) { ConnectionConfiguration configuration = new ConnectionConfiguration(); ConnectionConfigurationBuild configurationBuild = new ConnectionConfigurationBuild(configuration); eventBusOptionAction?.Invoke(configurationBuild); container.RegisterSingleton <IPersistentConnection>(() => { IConnectionFactory factory = new ConnectionFactory { AutomaticRecoveryEnabled = configuration.AutomaticRecoveryEnabled, NetworkRecoveryInterval = configuration.NetworkRecoveryInterval, Uri = new Uri(connectionString), }; var connection = new PersistentConnection(configuration, factory); connection.TryConnect(); return(connection); }); container.RegisterSingleton <IEventHandlerModuleFactory, EventHandlerModuleFactory>(); container.RegisterSingleton <RabbitMqCore, RabbitMqCore>(); foreach (Type mType in typeof(IEvent).GetAssemblies()) { container.Register(mType); foreach (Type hType in typeof(IEventHandler <>).GetMakeGenericType(mType)) { container.Register(hType); } } }
private IModel CreateConsumerChannelReply(CancellationToken cancel = default) { if (!PersistentConnection.IsConnected) { PersistentConnection.TryConnect(); } var channel = PersistentConnection.CreateModel(); channel.ExchangeDeclare(ExchangeDeclareParameters.ExchangeName, ExchangeDeclareParameters.ExchangeType, ExchangeDeclareParameters.ExchangeDurable, ExchangeDeclareParameters.ExchangeAutoDelete); channel.QueueDeclare(_queueNameReply, QueueDeclareParameters.QueueDurable, QueueDeclareParameters.QueueExclusive, QueueDeclareParameters.QueueAutoDelete, null); channel.BasicQos(0, 1, false); channel.CallbackException += (sender, ea) => { Logger.LogError("CallbackException Rpc: " + ea.Exception.Message); _consumerChannelReply.Dispose(); _consumerChannelReply = CreateConsumerChannelReply(cancel); StartBasicConsumeReply(); }; return(channel); }
public CallHandler(ConnectionConfiguration configuration, PersistentConnection connection) { _configuration = configuration; _connection = connection; }
public AspNetHandler(IDependencyResolver resolver, PersistentConnection connection) { _resolver = resolver; _connection = connection; }
public PersistentChannel CreatePersistentChannel(PersistentConnection connection) { Preconditions.CheckNotNull(connection, "connection"); return(new PersistentChannel(connection, this._configuration)); }
public SignalRMessageHandler(IDependencyResolver resolver, PersistentConnection connection, HttpRouteCollection routes) { this.resolver = resolver; this.connection = connection; this.routes = routes; }
public CallHandler(IDependencyResolver resolver, PersistentConnection connection) { _resolver = resolver; _connection = connection; }
public bool TryGetConnection(Uri uri, out PersistentConnection connection) { return TryGetConnection(uri.LocalPath, out connection); }
public RabbitMqCore(Container ioc, IPersistentConnection persistentConnection, IEventHandlerModuleFactory eventHandlerFactory) { Connection = (PersistentConnection)persistentConnection; Ioc = ioc; }