protected override void ConfigureTransportAndPersistence(IBusConfigurator cfg)
        {
            var kafkaConfig = _kafkaFixture.BuildKafkaConfiguration(_topicName);

            cfg.UseKafkaTransport(kafkaConfig)
            .UsePostgreSqlPersistence(_sqlConfig);
        }
Beispiel #2
0
        protected override void ConfigureTransportAndPersistence(IBusConfigurator cfg)
        {
            var sqlCfg = new SqlConfiguration(_fixture.ConnectionString);

            cfg.UseInMemoryTransport()
            .UseSqlPersistence(sqlCfg);
        }
Beispiel #3
0
        public static IBusConfigurator UseRabbitMQTransport(this IBusConfigurator busConfigurator,
                                                            RabbitConfiguration config,
                                                            Action <IRabbitBusConfigurationBuilder> builderFunc)
        {
            busConfigurator.Services.AddSingleton <IQueueReferenceFactory, QueueReferenceFactory>();
            busConfigurator.Services.AddSingleton <IMessageParser, MessageParser>();
            busConfigurator.Services.AddSingleton <IPublisher, RabbitPublisher>();
            busConfigurator.Services.AddSingleton <IPublisherChannelContextPool, PublisherChannelContextPool>();
            busConfigurator.Services.AddSingleton <IPublisherChannelFactory, PublisherChannelFactory>();

            busConfigurator.Services.AddSingleton <IConnectionFactory>(ctx =>
            {
                var connectionFactory = new ConnectionFactory()
                {
                    HostName = config.HostName,
                    UserName = config.UserName,
                    Password = config.Password,
                    Port     = AmqpTcpEndpoint.UseDefaultPort,
                    DispatchConsumersAsync = true
                };
                return(connectionFactory);
            });

            busConfigurator.Services.AddSingleton <IBusConnection, RabbitPersistentConnection>();

            builderFunc?.Invoke(new DefaultRabbitBusConfigurationBuilder(busConfigurator));

            return(busConfigurator);
        }
Beispiel #4
0
        /// <summary>
        /// Устанавливает параметры <c>Quality of service (QoS)</c> по умолчанию для всех получателей.
        /// </summary>
        /// <param name="busConfigurator">Конфигуратор шины сообщений.</param>
        /// <param name="prefetchCount">Количество сообщений получаемых из шины за одно обращение, т.е. размер порции данных.</param>
        /// <param name="prefetchSize">Количество сообщений, которые должен обработать получатель, прежде чем получит новую порцию данных.</param>
        /// <returns>Конфигурация экземпляра шины сообщений.</returns>
        public static IBusConfigurator SetDefaultQoS(this IBusConfigurator busConfigurator, ushort prefetchCount, uint prefetchSize = 0)
        {
            // TODO: beautify
            ((RabbitReceiverOptions)((BusConfiguration)busConfigurator).ReceiverDefaults).QoS = new QoSParams(prefetchCount, prefetchSize);

            return(busConfigurator);
        }
Beispiel #5
0
        public static IBusConfigurator UseInMemoryTransport(
            this IBusConfigurator busConfigurator)
        {
            busConfigurator.Services.AddSingleton <IPublisher, InMemoryPublisher>()
            .AddSingleton <IChannelFactory, ChannelFactory>();

            return(busConfigurator);
        }
Beispiel #6
0
 protected override void ConfigureTransportAndPersistence(IBusConfigurator cfg)
 {
     cfg.UseAzureServiceBusTransport(_fixture.Configuration, builder =>
     {
         builder.UseMessageNamingPolicy <StartSimpleSaga>(() =>
                                                          new QueueReferences(_topicName, _subscriptionName));
     })
     .UseInMemoryPersistence();
 }
 protected override void ConfigureTransportAndPersistence(IBusConfigurator cfg)
 {
     cfg.UseAzureServiceBusTransport(_fixture.Configuration, builder =>
     {
         QueueReferencesPolicy <DummyEvent> policy = () => new QueueReferences(_topicName, _subscriptionName);
         builder.UseMessageNamingPolicy(policy);
     })
     .UseInMemoryPersistence();
 }
Beispiel #8
0
        public static IBusConfigurator UseInMemoryPersistence(
            this IBusConfigurator busConfigurator)
        {
            busConfigurator.Services.AddSingleton <ISagaStateRepository, InMemorySagaStateRepository>()
            .AddSingleton <IOutboxRepository, InMemoryOutboxRepository>()
            .AddSingleton <ITransactionManager, InMemoryTransactionManager>();

            return(busConfigurator);
        }
Beispiel #9
0
        public static IBusConfigurator UseKafkaTransport(this IBusConfigurator busConfigurator,
                                                         KafkaConfiguration config,
                                                         Action <IKafkaBusConfigurationBuilder> builderFunc)
        {
            busConfigurator.Services.AddSingleton(config);

            busConfigurator.Services.AddSingleton <IQueueReferenceFactory>(ctx => new QueueReferenceFactory(ctx, config.DefaultQueueReferenceCreator));

            busConfigurator.Services.AddSingleton(ctx =>
            {
                var kafkaConfig = ctx.GetRequiredService <KafkaConfiguration>();
                return(new AdminClientConfig()
                {
                    BootstrapServers = kafkaConfig.ConnectionString
                });
            });
            busConfigurator.Services.AddSingleton(ctx =>
            {
                var adminClientConfig = ctx.GetRequiredService <AdminClientConfig>();
                return(new AdminClientBuilder(adminClientConfig));
            });

            busConfigurator.Services.AddSingleton(ctx =>
            {
                var kafkaConfig = ctx.GetRequiredService <KafkaConfiguration>();
                return(new ProducerConfig()
                {
                    BootstrapServers = kafkaConfig.ConnectionString
                });
            });
            busConfigurator.Services.AddSingleton(ctx =>
            {
                var config  = ctx.GetRequiredService <ProducerConfig>();
                var builder = new ProducerBuilder <Guid, byte[]>(config);
                builder.SetKeySerializer(new KeySerializer <Guid>());

                return(builder);
            });
            busConfigurator.Services.AddSingleton <IProducer <Guid, byte[]> >(ctx =>
            {
                var builder = ctx.GetRequiredService <ProducerBuilder <Guid, byte[]> >();
                return(builder.Build());
            });
            busConfigurator.Services.AddTransient <IKafkaPublisherExecutor, KafkaPublisherExecutor>();
            busConfigurator.Services.AddTransient <IPublisher, KafkaPublisher>();

            busConfigurator.Services.AddTransient <IMessageParser, MessageParser>();
            busConfigurator.Services.AddSingleton <IKafkaMessageHandler, KafkaMessageHandler>();

            busConfigurator.Services.AddSingleton <IGroupIdFactory, DefaultGroupIdFactory>();
            busConfigurator.Services.AddSingleton <IConsumerBuilderFactory, ConsumerBuilderFactory>();

            builderFunc?.Invoke(new DefaultKafkaBusConfigurationBuilder(busConfigurator));

            return(busConfigurator);
        }
Beispiel #10
0
        protected override void ConfigureTransportAndPersistence(IBusConfigurator cfg)
        {
            var(_, connStr) = _dbFixture.CreateDbContext();
            var sqlCfg = new SqlConfiguration(connStr);

            var kafkaConfig = _kafkaFixture.BuildKafkaConfiguration(_topicPrefix);

            cfg.UseKafkaTransport(kafkaConfig)
            .UseSqlPersistence(sqlCfg);
        }
        protected override void ConfigureTransportAndPersistence(IBusConfigurator cfg)
        {
            var mongoCfg = new MongoConfiguration(_fixture.ConnectionString,
                                                  _fixture.DbName,
                                                  MongoSagaStateRepositoryOptions.Default,
                                                  MongoOutboxRepositoryOptions.Default);

            cfg.UseInMemoryTransport()
            .UseMongoPersistence(mongoCfg);
        }
        protected override void ConfigureTransportAndPersistence(IBusConfigurator cfg)
        {
            var cosmosCfg = new CosmosConfiguration(_fixture.ConnectionString,
                                                    _fixture.DbName,
                                                    CosmosSagaStateRepositoryOptions.Default,
                                                    CosmosOutboxRepositoryOptions.Default);

            cfg.UseInMemoryTransport()
            .UseCosmosPersistence(cosmosCfg);
        }
        /// <inheritdoc />
        public IBusConfigurator Configure(string endpointName, IBusConfigurator currentConfiguration)
        {
            var outgoingConfiguration = this.cacheConfigProvider.GetOutgoingCacheConfig(endpointName);

            var cachingFilter = new CachingFilterDecorator(outgoingConfiguration, (currentConfiguration as BusConfiguration)?.MetricsCollector);

            currentConfiguration.RegisterDecoratorOf <SendingExchangeFilter>(cachingFilter);

            return(currentConfiguration);
        }
        protected void AddSaga <TS, TD, TM>(IBusConfigurator cfg, Func <TM, TD> stateFactory)
            where TD : SagaState
            where TS : Saga <TD>
            where TM : IMessage
        {
            var sagaCfg = cfg.AddSaga <TS, TD>()
                          .UseStateFactory(stateFactory);

            ConfigureSagaTransport(sagaCfg);
        }
Beispiel #15
0
        protected override void ConfigureTransportAndPersistence(IBusConfigurator cfg)
        {
            var(_, dbName) = _cosmosFixture.CreateDbContext();
            var sqlCfg = new CosmosSqlConfiguration(_cosmosFixture.ConnectionString, dbName);

            cfg.UseAzureServiceBusTransport(_sbFixture.Configuration, builder =>
            {
                builder.UseMessageNamingPolicy <StartSimpleSaga>(() =>
                                                                 new QueueReferences(_topicName, _subscriptionName));
            })
            .UseCosmosSqlPersistence(sqlCfg);
        }
        public static ISagaConfigurator <TS, TM, TK> AsSagaStep <TS, TM, TK>(this IBusConfigurator busConfigurator, MessageLabel label) where TM : class
        {
            var receiverConfigurator = busConfigurator.On <TM>(label);

            return(new SagaConfiguration <TS, TM, TK>(
                       receiverConfigurator,
                       SingletonSagaRepository <TS, TK> .Instance,
                       new CorrelationIdSeparator <TM, TK>(),
                       SingletonSagaFactory <TS, TK> .Instance,
                       new LambdaSagaStep <TS, TM, TK>((sc, cc) => { }),
                       new LambdaFailedHandler <TS, TM, TK>(cc => { throw new ArgumentException("Сага не найдена."); }, (sc, cc, e) => { })));
        }
Beispiel #17
0
        protected override void ConfigureTransportAndPersistence(IBusConfigurator cfg)
        {
            var(_, name) = _mongoFixture.CreateDbContext();
            var mongoCfg = new MongoConfiguration(_mongoFixture.ConnectionString,
                                                  name,
                                                  MongoSagaStateRepositoryOptions.Default,
                                                  MongoOutboxRepositoryOptions.Default);

            var kafkaConfig = _kafkaFixture.BuildKafkaConfiguration(_topicName);

            cfg.UseKafkaTransport(kafkaConfig)
            .UseMongoPersistence(mongoCfg);
        }
Beispiel #18
0
        protected override void ConfigureTransportAndPersistence(IBusConfigurator cfg)
        {
            var(_, connStr) = _dbFixture.CreateDbContext();
            var sqlCfg = new SqlConfiguration(connStr);

            cfg.UseRabbitMQTransport(_rabbitFixture.RabbitConfiguration, builder => {
                builder.UseMessageNamingPolicy <StartSimpleSaga>(() =>
                                                                 new QueueReferences(_exchangeName,
                                                                                     _exchangeName,
                                                                                     $"{_exchangeName}.dead",
                                                                                     $"{_exchangeName}.dead"));
            })
            .UseSqlPersistence(sqlCfg);
        }
Beispiel #19
0
        public static IBusConfigurator UseSqlServerPersistence(
            this IBusConfigurator busConfigurator, SqlConfiguration config)
        {
            busConfigurator.Services.AddDbContextPool <SagaDbContext>(builder =>
            {
                builder.UseSqlServer(config.ConnectionString);
            }).AddScoped <ISagaDbContext>(ctx => ctx.GetRequiredService <SagaDbContext>())
            .AddScoped <ITransactionManager, SqlTransactionManager>()
            .AddSingleton(config.SagaRepositoryOptions)
            .AddSingleton(config.OutboxRepositoryOptions)
            .AddScoped <IOutboxRepository, SqlOutboxRepository>()
            .AddScoped <ISagaStateRepository, SqlSagaStateRepository>();

            return(busConfigurator);
        }
Beispiel #20
0
        public static IBusConfigurator UseAzureServiceBusTransport(this IBusConfigurator busConfigurator,
                                                                   AzureServiceBusConfiguration config,
                                                                   Action <IAzureServiceBusConfigurationBuilder> builderFunc = null)
        {
            //https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-performance-improvements?tabs=net-standard-sdk-2#reusing-factories-and-clients
            busConfigurator.Services
            .AddSingleton(config)
            .AddSingleton(ctx => new ServiceBusClient(config.ConnectionString, new ServiceBusClientOptions()))
            .AddSingleton <IQueueReferenceFactory, QueueReferenceFactory>()
            .AddSingleton <IServiceBusSenderFactory, ServiceBusSenderFactory>()
            .AddSingleton <IPublisher, ServiceBusPublisher>();

            builderFunc?.Invoke(new DefaultAzureServiceBusConfigurationBuilder(busConfigurator));

            return(busConfigurator);
        }
Beispiel #21
0
        protected override void ConfigureTransportAndPersistence(IBusConfigurator cfg)
        {
            var(_, dbName) = _cosmosFixture.CreateDbContext();
            var sqlCfg = new CosmosSqlConfiguration(_cosmosFixture.ConnectionString, dbName);

            cfg.UseAzureServiceBusTransport(_sbFixture.Configuration, builder =>
            {
                QueueReferencesPolicy <DummyEvent> policy = () =>
                {
                    var sp               = cfg.Services.BuildServiceProvider();
                    var sysInfo          = sp.GetService <SystemInfo>();
                    var subscriptionName = sysInfo.ClientGroup;
                    return(new QueueReferences(_topicName, subscriptionName));
                };
                builder.UseMessageNamingPolicy(policy);
            })
            .UseCosmosSqlPersistence(sqlCfg);
        }
        protected override void ConfigureTransportAndPersistence(IBusConfigurator cfg)
        {
            var(_, connStr) = _dbFixture.CreateDbContext();
            var sqlCfg = new SqlConfiguration(connStr);

            cfg.UseRabbitMQTransport(_rabbitFixture.RabbitConfiguration, builder =>
            {
                builder.UseMessageNamingPolicy <DummyEvent>(() =>
                {
                    var sp      = cfg.Services.BuildServiceProvider();
                    var sysInfo = sp.GetService <SystemInfo>();
                    return(new QueueReferences(_exchangeName,
                                               $"{_exchangeName}.{sysInfo.ClientGroup}",
                                               $"{_exchangeName}.dead",
                                               $"{_exchangeName}.dead"));
                });
            })
            .UseSqlPersistence(sqlCfg);
        }
Beispiel #23
0
        /// <summary>
        /// The configure bus.
        /// </summary>
        /// <param name="cfg">
        /// The cfg.
        /// </param>
        private static void ConfigureBus(IBusConfigurator cfg)
        {
            cfg.UseRabbitMq();
            cfg.SetEndpoint(Params.Endpoint);
            cfg.SetConnectionString(Params.ConnectionString);
            cfg.UseParallelismLevel(Params.ParallelismLevel);

            ISenderConfigurator routeCfg = cfg.Route(Params.Type).
                WithDefaultCallbackEndpoint().
                Persistently();
            if (Params.RequireConfirmation)
            {
                routeCfg.WithConfirmation();
            }

            routeCfg = cfg.Route("bad.msg").
                WithDefaultCallbackEndpoint();
            if (Params.RequireConfirmation)
            {
                routeCfg.WithConfirmation();
            }
        }
Beispiel #24
0
        /// <summary>
        /// The configure bus.
        /// </summary>
        /// <param name="cfg">
        /// The cfg.
        /// </param>
        private static void ConfigureBus(IBusConfigurator cfg)
        {
            cfg.UseRabbitMq();
            cfg.SetEndpoint(Params.Endpoint);
            cfg.SetConnectionString(Params.ConnectionString);
            cfg.UseParallelismLevel(Params.ParallelismLevel);

            ISenderConfigurator routeCfg = cfg.Route(Params.Type).
                                           WithDefaultCallbackEndpoint().
                                           Persistently();

            if (Params.RequireConfirmation)
            {
                routeCfg.WithConfirmation();
            }

            routeCfg = cfg.Route("bad.msg").
                       WithDefaultCallbackEndpoint();
            if (Params.RequireConfirmation)
            {
                routeCfg.WithConfirmation();
            }
        }
Beispiel #25
0
 protected override void AddSagas(IBusConfigurator cfg)
 {
     AddSaga <ParentSaga, ParentSagaState, StartParentSaga>(cfg, msg => new ParentSagaState(msg.CorrelationId));
     AddSaga <ChildSaga, ChildSagaState, StartChildSaga>(cfg, msg => new ChildSagaState(msg.CorrelationId));
 }
Beispiel #26
0
 protected override void AddSagas(IBusConfigurator cfg)
 {
     AddSaga <SimpleSaga, SimpleSagaState, StartSimpleSaga>(cfg, msg => new SimpleSagaState(msg.CorrelationId));
 }
        /// <summary>
        /// Конфигурирует клиента шины сообщений.
        /// </summary>
        /// <param name="endpointName">
        /// Имя точки подключения к шине.
        /// </param>
        /// <param name="cfg">
        /// Конфигуратор клиента шины.
        /// </param>
        /// <returns>
        /// Конфигуратор клиента шины, после применения к нему всех настроек.
        /// </returns>
        public IBusConfigurator Configure(string endpointName, IBusConfigurator cfg)
        {
            if (cfg == null)
            {
                throw new ArgumentNullException("cfg", "Файл конфигурации не может быть null");
            }

            var endpointConfig = this.GetEndPointByName(endpointName);

            IConnectionStringProvider connectionStringProvider = null;

            if (!string.IsNullOrEmpty(endpointConfig.ConnectionStringProvider))
            {
                connectionStringProvider = this.GetConnectionStringProvider(endpointConfig.ConnectionStringProvider);
            }

            cfg.SetEndpoint(endpointConfig.Name);
            cfg.SetConnectionString(endpointConfig.ConnectionString);
            cfg.SetExcludedIncomingHeaders(endpointConfig.ExcludedHeaders);

            if (endpointConfig.ReuseConnection.HasValue)
            {
                cfg.ReuseConnection(endpointConfig.ReuseConnection.Value);
            }

            if (!string.IsNullOrWhiteSpace(endpointConfig.LifecycleHandler))
            {
                cfg.HandleLifecycleWith(this.ResolveLifecycleHandler(endpointConfig.LifecycleHandler));
            }

            if (endpointConfig.ParallelismLevel.HasValue)
            {
                cfg.UseParallelismLevel(endpointConfig.ParallelismLevel.Value);
            }

            if (endpointConfig.FaultQueueTtl.HasValue)
            {
                cfg.UseFaultQueueTtl(endpointConfig.FaultQueueTtl.Value);
            }

            if (endpointConfig.FaultQueueLimit.HasValue)
            {
                cfg.UseFaultQueueLimit(endpointConfig.FaultQueueLimit.Value);
            }

            if (endpointConfig.Dynamic != null)
            {
                if (endpointConfig.Dynamic.Outgoing.HasValue)
                {
                    if (endpointConfig.Dynamic.Outgoing.Value)
                    {
                        cfg.Route(MessageLabel.Any)
                        .ConfiguredWith(
                            builder => new LambdaRouteResolver(
                                (endpoint, label) =>
                        {
                            builder.Topology.Declare(Exchange.Named(label.Name).Durable.Fanout);
                            return(new RabbitRoute(label.Name));
                        }));
                    }
                }
            }

            if (endpointConfig.Qos != null)
            {
                if (endpointConfig.Qos.PrefetchCount.HasValue)
                {
                    cfg.SetDefaultQoS(endpointConfig.Qos.PrefetchCount.Value);
                }
            }

            foreach (ValidatorElement validator in endpointConfig.Validators)
            {
                if (validator.Group)
                {
                    MessageValidatorGroup v = this.ResolveValidatorGroup(validator.Name);
                    cfg.RegisterValidators(v);
                }
                else
                {
                    IMessageValidator v = this.ResolveValidator(validator.Name);
                    cfg.RegisterValidator(v);
                }
            }

            foreach (OutgoingElement outgoingElement in endpointConfig.Outgoing)
            {
                var configurator = cfg.Route(outgoingElement.Label).WithAlias(outgoingElement.Key);

                if (outgoingElement.Confirm)
                {
                    configurator.WithConfirmation();
                }

                if (outgoingElement.Persist)
                {
                    configurator.Persistently();
                }

                if (outgoingElement.Ttl.HasValue)
                {
                    configurator.WithTtl(outgoingElement.Ttl.Value);
                }

                if (outgoingElement.CallbackEndpoint.Default)
                {
                    configurator.WithDefaultCallbackEndpoint();
                }

                if (outgoingElement.Timeout.HasValue)
                {
                    configurator.WithRequestTimeout(outgoingElement.Timeout);
                }

                if (outgoingElement.Delayed || outgoingElement.Delay.HasValue || endpointConfig.Delayed)
                {
                    configurator.WithDelay(outgoingElement.Delay ?? TimeSpan.Zero);
                }

                // Connection string
                var connectionString = endpointConfig.ConnectionString;
                if (!string.IsNullOrEmpty(outgoingElement.ConnectionString))
                {
                    connectionString = outgoingElement.ConnectionString;
                }

                connectionString = connectionStringProvider?.GetConnectionString(outgoingElement.Label.ToMessageLabel()) ?? connectionString;


                configurator.WithConnectionString(connectionString);

                // Reuse connection
                if (outgoingElement.ReuseConnection.HasValue)
                {
                    configurator.ReuseConnection(outgoingElement.ReuseConnection.Value);
                }
            }

            foreach (IncomingElement incomingElement in endpointConfig.Incoming)
            {
                var configurator = cfg.On(incomingElement.Label).WithAlias(incomingElement.Key);

                uint   size  = 0;
                ushort count = 50;

                // This should be the default values provided by RabbitMQ configurator (BusConsumerConfigurationEx);
                var qos = configurator.GetQoS();
                if (qos.HasValue)
                {
                    size  = qos.Value.PrefetchSize;
                    count = qos.Value.PrefetchCount;
                }

                // Prefetch size
                if (endpointConfig.Qos.PrefetchSize.HasValue)
                {
                    size = endpointConfig.Qos.PrefetchSize.Value;
                }

                if (incomingElement.Qos.PrefetchSize.HasValue)
                {
                    size = incomingElement.Qos.PrefetchSize.Value;
                }

                // Prefetch count
                if (endpointConfig.Qos.PrefetchCount.HasValue)
                {
                    count = endpointConfig.Qos.PrefetchCount.Value;
                }

                if (incomingElement.Qos.PrefetchCount.HasValue)
                {
                    count = incomingElement.Qos.PrefetchCount.Value;
                }

                configurator.WithQoS(new QoSParams(count, size));

                // Parallelism level
                if (endpointConfig.ParallelismLevel.HasValue)
                {
                    configurator.WithParallelismLevel(endpointConfig.ParallelismLevel.Value);
                }

                if (incomingElement.ParallelismLevel.HasValue)
                {
                    configurator.WithParallelismLevel(incomingElement.ParallelismLevel.Value);
                }

                // Accept
                if (incomingElement.RequiresAccept)
                {
                    configurator.RequiresAccept();
                }

                if (incomingElement.Delayed)
                {
                    configurator.Delayed();
                }

                // Connection string
                var connectionString = endpointConfig.ConnectionString;
                if (!string.IsNullOrEmpty(incomingElement.ConnectionString))
                {
                    connectionString = incomingElement.ConnectionString;
                }
                connectionString = connectionStringProvider?.GetConnectionString(incomingElement.Label.ToMessageLabel()) ?? connectionString;


                configurator.WithConnectionString(connectionString);

                // Reuse connection
                if (incomingElement.ReuseConnection.HasValue)
                {
                    configurator.ReuseConnection(incomingElement.ReuseConnection.Value);
                }

                Type messageType = typeof(ExpandoObject);
                if (!string.IsNullOrWhiteSpace(incomingElement.Type))
                {
                    messageType = ResolveType(incomingElement.Type);
                }

                var consumerFactory = this.BuildConsumerFactory(incomingElement, messageType, endpointName);

                object consumer = BuildConsumer(consumerFactory, messageType, incomingElement.Lifestyle);

                RegisterConsumer(configurator, messageType, consumer);

                if (!string.IsNullOrWhiteSpace(incomingElement.Validate))
                {
                    IMessageValidator validator = this.ResolveValidator(incomingElement.Validate, messageType);

                    configurator.WhenVerifiedBy(validator);
                }
            }

            var collectorType = endpointConfig.Metrics?.Collector;

            if (!string.IsNullOrEmpty(collectorType))
            {
                try
                {
                    var metricsCollector = (IMetricsCollector)this.dependencyResolver.Resolve(collectorType, typeof(IMetricsCollector));
                    cfg.CollectMetrics(metricsCollector);
                }
                catch (Exception e)
                {
                    Log.Warn(m => m("Could not load metric collector '{0}'", collectorType), e);
                }
            }
            else
            {
                Log.Trace(m => m("Metric collector is not specified"));
            }

            foreach (var configurator in this.childConfigurators)
            {
                configurator.Configure(endpointName, cfg);
            }

            return(cfg);
        }
Beispiel #28
0
 protected override void ConfigureTransportAndPersistence(IBusConfigurator cfg)
 {
     cfg.UseRabbitMQTransport(_fixture.RabbitConfiguration)
     .UseInMemoryPersistence();
 }
        /// <summary>
        /// Конфигурирует клиента шины сообщений.
        /// </summary>
        /// <param name="endpointName">
        /// Имя точки подключения к шине.
        /// </param>
        /// <param name="cfg">
        /// Конфигуратор клиента шины.
        /// </param>
        /// <returns>
        /// Конфигуратор клиента шины, после применения к нему всех настроек.
        /// </returns>
        public IBusConfigurator Configure(string endpointName, IBusConfigurator cfg)
        {
            if (cfg == null)
            {
                throw new ArgumentNullException("cfg", "Файл конфигурации не может быть null");
            }

            EndpointElement endpointConfig = this.GetEndPointByName(endpointName);

            cfg.SetEndpoint(endpointConfig.Name);

            cfg.SetConnectionString(endpointConfig.ConnectionString);

            if (!string.IsNullOrWhiteSpace(endpointConfig.LifecycleHandler))
            {
                cfg.HandleLifecycleWith(this.ResolveLifecycleHandler(endpointConfig.LifecycleHandler));
            }

            if (endpointConfig.Caching != null && endpointConfig.Caching.Enabled)
            {
                cfg.EnableCaching();
            }

            if (endpointConfig.ParallelismLevel.HasValue)
            {
                cfg.UseParallelismLevel(endpointConfig.ParallelismLevel.Value);
            }

            if (endpointConfig.Dynamic != null)
            {
                if (endpointConfig.Dynamic.Outgoing.HasValue)
                {
                    if (endpointConfig.Dynamic.Outgoing.Value)
                    {
                        cfg.Route(MessageLabel.Any)
                            .ConfiguredWith(builder => new LambdaRouteResolver(
                                    (endpoint, label) =>
                                        {
                                            builder.Topology.Declare(
                                                Exchange.Named(label.Name)
                                                    .Durable.Fanout);
                                            return new RabbitRoute(label.Name);
                                        }));
                    }
                }
            }

            if (endpointConfig.Qos != null)
            {
                if (endpointConfig.Qos.PrefetchCount.HasValue)
                {
                    cfg.SetDefaultQoS(endpointConfig.Qos.PrefetchCount.Value);
                }
            }

            foreach (ValidatorElement validator in endpointConfig.Validators)
            {
                if (validator.Group)
                {
                    MessageValidatorGroup v = this.ResolveValidatorGroup(validator.Name);
                    cfg.RegisterValidators(v);
                }
                else
                {
                    IMessageValidator v = this.ResolveValidator(validator.Name);
                    cfg.RegisterValidator(v);
                }
            }

            foreach (OutgoingElement message in endpointConfig.Outgoing)
            {
                ISenderConfigurator senderCfg = cfg.Route(message.Label).
                    WithAlias(message.Key);

                if (message.Confirm)
                {
                    senderCfg.WithConfirmation();
                }

                if (message.Persist)
                {
                    senderCfg.Persistently();
                }

                if (message.Ttl.HasValue)
                {
                    senderCfg.WithTtl(message.Ttl.Value);
                }

                if (message.CallbackEndpoint.Default)
                {
                    senderCfg.WithDefaultCallbackEndpoint();
                }

                if (message.Timeout.HasValue)
                {
                    senderCfg.WithRequestTimeout(message.Timeout);
                }
            }

            foreach (IncomingElement message in endpointConfig.Incoming)
            {
                IReceiverConfigurator receiver = cfg.On(message.Label).
                    WithAlias(message.Key);

                if (message.RequiresAccept)
                {
                    receiver.RequiresAccept();
                }

                Type messageType = typeof(ExpandoObject);
                if (!string.IsNullOrWhiteSpace(message.Type))
                {
                    messageType = ResolveType(message.Type);
                }

                var consumerFactory = this.BuildConsumerFactory(message.React, messageType);

                object consumer = BuildConsumer(consumerFactory, messageType, message.Lifestyle);

                RegisterConsumer(receiver, messageType, consumer);

                if (!string.IsNullOrWhiteSpace(message.Validate))
                {
                    IMessageValidator validator = this.ResolveValidator(message.Validate, messageType);

                    receiver.WhenVerifiedBy(validator);
                }
            }

            return cfg;
        }
Beispiel #30
0
        /// <summary>
        /// Включает использование брокера <c>RabbitMQ</c>.
        /// </summary>
        /// <param name="busConfigurator">Конфигуратор шины сообщений.</param>
        /// <returns>Конфигуратор шины сообщений с включенной поддержкой брокера.</returns>
        public static IBusConfigurator UseRabbitMq(this IBusConfigurator busConfigurator)
        {
            var c = (BusConfiguration)busConfigurator;

            if (c.BusFactoryFunc != null)
            {
                return(busConfigurator);
            }

            c.BuildBusUsing(bc => new RabbitBus(c));

            var blockedHeaders = new List <string>
            {
                Headers.Expires,
                Headers.MessageLabel,
                Headers.Persist,
                Headers.QueueMessageTtl,
                Headers.ReplyRoute,
                Headers.Timeout,
                Headers.Ttl,
                Headers.Delay
            };

            var messageHeaderStorage = new MessageHeaderStorage(blockedHeaders);

            c.UseIncomingMessageHeaderStorage(messageHeaderStorage);

            c.SenderDefaults = new RabbitSenderOptions(c.EndpointOptions)
            {
                ConfirmationIsRequired = false,
                Persistently           = false,
                RequestTimeout         = TimeSpan.FromSeconds(30),
                Ttl = default(TimeSpan?),
                RouteResolverBuilder    = RabbitBusDefaults.RouteResolverBuilder,
                ReuseConnection         = true,
                ProducerSelectorBuilder = RabbitBusDefaults.ProducerSelectorBuilder,
                FailoverAttempts        = 7,
                MaxRetryDelay           = 30,
                InactivityResetDelay    = 120
            };

            c.ReceiverDefaults = new RabbitReceiverOptions(c.EndpointOptions)
            {
                AcceptIsRequired = false,
                ParallelismLevel = 1,
                EndpointBuilder  = RabbitBusDefaults.SubscriptionEndpointBuilder,
                QoS             = new QoSParams(50, 0),
                ReuseConnection = true
            };

            c.UseMessageLabelHandler(new DefaultRabbitMessageLabelHandler());

            // TODO: extract, combine routing and handler definition
            Func <IRouteResolverBuilder, IRouteResolver> faultRouteResolverBuilder = b =>
            {
                TimeSpan messageTtl = c.ReceiverDefaults.GetFaultQueueTtl().HasValue
                                              ? c.ReceiverDefaults.GetFaultQueueTtl().Value
                                              : TimeSpan.FromDays(FaultMessageTtlDays);

                string       name    = b.Endpoint.Address + ".Fault";
                Exchange     e       = b.Topology.Declare(Exchange.Named(name).Durable.Topic);
                QueueBuilder builder = Queue.Named(name).Durable.WithTtl(messageTtl);

                if (c.ReceiverDefaults.GetFaultQueueLimit().HasValue)
                {
                    builder = builder.WithLimit(c.ReceiverDefaults.GetFaultQueueLimit().Value);
                }
                Queue q = b.Topology.Declare(builder);
                b.Topology.Bind(e, q);
                return(e);
            };

            c.Route("document.Contour.unhandled").Persistently().ConfiguredWith(faultRouteResolverBuilder).ReuseConnection();
            c.Route("document.Contour.failed").Persistently().ConfiguredWith(faultRouteResolverBuilder).ReuseConnection();

            c.OnUnhandled(
                d =>
            {
                d.Forward("document.Contour.unhandled", d.BuildFaultMessage());
                d.Accept();
            });
            c.OnFailed(
                d =>
            {
                d.Forward("document.Contour.failed", d.BuildFaultMessage());
                d.Accept();
            });

            return(busConfigurator);
        }
 protected abstract void AddSagas(IBusConfigurator cfg);
Beispiel #32
0
        /// <summary>
        /// The configure bus.
        /// </summary>
        /// <param name="cfg">
        /// The cfg.
        /// </param>
        /// <exception cref="AccessViolationException">
        /// </exception>
        /// <exception cref="NotSupportedException">
        /// </exception>
        private static void ConfigureBus(IBusConfigurator cfg)
        {
            cfg.UseRabbitMq();
            cfg.SetEndpoint(Params.Endpoint);
            cfg.SetConnectionString(Params.ConnectionString);
            cfg.UseParallelismLevel(Params.ParallelismLevel);

            IReceiverConfigurator subscriberCfg = cfg.On(Params.Type);
            if (Params.RequireAccept)
            {
                subscriberCfg.RequiresAccept();
            }

            switch (Params.Type)
            {
                case ConsumerParams.OneWay:
                    subscriberCfg.ReactWith<OneWay>(
                        (m, ctx) =>
                            {
                                Console.WriteLine("Received {0} with label [{1}].", m.Number, ctx.Message.Label);

                                Thread.Sleep((int)Params.ConsumingDelay);

                                if (Params.Misbehave)
                                {
                                    if (Random.Next(10) == 0)
                                    {
                                        throw new AccessViolationException("un oh...");
                                    }
                                }

                                ctx.Accept();
                            });
                    break;
                case ConsumerParams.Request:

                    /*
                    subscriberCfg.ReactWith<WrongRequest>((m, ctx) =>
                    {
                        Console.WriteLine("Received {0}. Sending response...", m.Number);
                        ctx.Reply(new Response(666));
                        ctx.Accept();
                    });
            */
                    subscriberCfg.ReactWith<Request>(
                        (m, ctx) =>
                            {
                                Console.WriteLine("Received {0}. Sending response...", m.Number);

                                if (Params.Misbehave)
                                {
                                    if (Random.Next(10) == 0)
                                    {
                                        throw new AccessViolationException("un oh...");
                                    }
                                }

                                // Thread.Sleep(50000);
                                ctx.Reply(new Response(m.Number));
                                ctx.Accept();
                            });
                    break;
                default:
                    throw new NotSupportedException("Unknown consumer type: " + Params.Type);
            }
        }
        /// <summary>
        /// Конфигурирует клиента шины сообщений.
        /// </summary>
        /// <param name="endpointName">
        /// Имя точки подключения к шине.
        /// </param>
        /// <param name="cfg">
        /// Конфигуратор клиента шины.
        /// </param>
        /// <returns>
        /// Конфигуратор клиента шины, после применения к нему всех настроек.
        /// </returns>
        public IBusConfigurator Configure(string endpointName, IBusConfigurator cfg)
        {
            if (cfg == null)
            {
                throw new ArgumentNullException("cfg", "Файл конфигурации не может быть null");
            }

            EndpointElement endpointConfig = this.GetEndPointByName(endpointName);

            cfg.SetEndpoint(endpointConfig.Name);

            cfg.SetConnectionString(endpointConfig.ConnectionString);

            if (!string.IsNullOrWhiteSpace(endpointConfig.LifecycleHandler))
            {
                cfg.HandleLifecycleWith(this.ResolveLifecycleHandler(endpointConfig.LifecycleHandler));
            }

            if (endpointConfig.Caching != null && endpointConfig.Caching.Enabled)
            {
                cfg.EnableCaching();
            }

            if (endpointConfig.ParallelismLevel.HasValue)
            {
                cfg.UseParallelismLevel(endpointConfig.ParallelismLevel.Value);
            }

            if (endpointConfig.Dynamic != null)
            {
                if (endpointConfig.Dynamic.Outgoing.HasValue)
                {
                    if (endpointConfig.Dynamic.Outgoing.Value)
                    {
                        cfg.Route(MessageLabel.Any)
                        .ConfiguredWith(builder => new LambdaRouteResolver(
                                            (endpoint, label) =>
                        {
                            builder.Topology.Declare(
                                Exchange.Named(label.Name)
                                .Durable.Fanout);
                            return(new RabbitRoute(label.Name));
                        }));
                    }
                }
            }

            if (endpointConfig.Qos != null)
            {
                if (endpointConfig.Qos.PrefetchCount.HasValue)
                {
                    cfg.SetDefaultQoS(endpointConfig.Qos.PrefetchCount.Value);
                }
            }

            foreach (ValidatorElement validator in endpointConfig.Validators)
            {
                if (validator.Group)
                {
                    MessageValidatorGroup v = this.ResolveValidatorGroup(validator.Name);
                    cfg.RegisterValidators(v);
                }
                else
                {
                    IMessageValidator v = this.ResolveValidator(validator.Name);
                    cfg.RegisterValidator(v);
                }
            }

            foreach (OutgoingElement message in endpointConfig.Outgoing)
            {
                ISenderConfigurator senderCfg = cfg.Route(message.Label).
                                                WithAlias(message.Key);

                if (message.Confirm)
                {
                    senderCfg.WithConfirmation();
                }

                if (message.Persist)
                {
                    senderCfg.Persistently();
                }

                if (message.Ttl.HasValue)
                {
                    senderCfg.WithTtl(message.Ttl.Value);
                }

                if (message.CallbackEndpoint.Default)
                {
                    senderCfg.WithDefaultCallbackEndpoint();
                }

                if (message.Timeout.HasValue)
                {
                    senderCfg.WithRequestTimeout(message.Timeout);
                }
            }

            foreach (IncomingElement message in endpointConfig.Incoming)
            {
                IReceiverConfigurator receiver = cfg.On(message.Label).
                                                 WithAlias(message.Key);

                if (message.RequiresAccept)
                {
                    receiver.RequiresAccept();
                }

                Type messageType = typeof(ExpandoObject);
                if (!string.IsNullOrWhiteSpace(message.Type))
                {
                    messageType = ResolveType(message.Type);
                }

                var consumerFactory = this.BuildConsumerFactory(message.React, messageType);

                object consumer = BuildConsumer(consumerFactory, messageType, message.Lifestyle);

                RegisterConsumer(receiver, messageType, consumer);

                if (!string.IsNullOrWhiteSpace(message.Validate))
                {
                    IMessageValidator validator = this.ResolveValidator(message.Validate, messageType);

                    receiver.WhenVerifiedBy(validator);
                }
            }

            return(cfg);
        }
Beispiel #34
0
 public static void WithEventAggregator(IBusConfigurator configurator, IEventAggregator aggregator)
 {
     Transport transport = new Transport();
     transport.EventAggregator = aggregator;
 }