Ejemplo n.º 1
0
        public void ListenSameCommandOnDifferentEndpointsTest()
        {
            var commandHandler = new CommandsHandler();

            using (var messagingEngine = new MessagingEngine(
                       _logFactory,
                       new TransportResolver(new Dictionary <string, TransportInfo>
            {
                { "InMemory", new TransportInfo("none", "none", "none", null, "InMemory") }
            })))
            {
                using (var engine = new CqrsEngine(
                           _logFactory,
                           messagingEngine,
                           Register.DefaultEndpointResolver(new InMemoryEndpointResolver()),
                           Register.BoundedContext("bc")
                           .PublishingEvents(typeof(int)).With("eventExchange")
                           .ListeningCommands(typeof(string)).On("exchange1")
                           .ListeningCommands(typeof(string)).On("exchange2")
                           .WithCommandsHandler(commandHandler)))
                {
                    engine.StartPublishers();
                    engine.StartSubscribers();
                    messagingEngine.Send("test1", new Endpoint("InMemory", "exchange1", serializationFormat: SerializationFormat.Json));
                    messagingEngine.Send("test2", new Endpoint("InMemory", "exchange2", serializationFormat: SerializationFormat.Json));
                    messagingEngine.Send("test3", new Endpoint("InMemory", "exchange3", serializationFormat: SerializationFormat.Json));
                    Thread.Sleep(7000);

                    Assert.That(commandHandler.HandledCommands, Is.EquivalentTo(new[] { "test1", "test2" }));
                }
            }
        }
Ejemplo n.º 2
0
        private CqrsEngine CreateEngine(IComponentContext ctx, IMessagingEngine messagingEngine)
        {
            var rabbitMqConventionEndpointResolver =
                new RabbitMqConventionEndpointResolver("RabbitMq", SerializationFormat.MessagePack,
                                                       environment: _settings.EnvironmentName);

            var registrations = new List <IRegistration>
            {
                Register.DefaultEndpointResolver(rabbitMqConventionEndpointResolver),
                RegisterDefaultRouting(),
                RegisterSpecialLiquidationSaga(),
                RegisterLiquidationSaga(),
                RegisterContext(),
                Register.CommandInterceptors(new DefaultCommandLoggingInterceptor(_log)),
                Register.EventInterceptors(new DefaultEventLoggingInterceptor(_log))
            };

            var fakeGavel = RegisterGavelContextIfNeeded();

            if (fakeGavel != null)
            {
                registrations.Add(fakeGavel);
            }

            var correlationManager = ctx.Resolve <CqrsCorrelationManager>();
            var engine             = new CqrsEngine(_log, ctx.Resolve <IDependencyResolver>(), messagingEngine,
                                                    new DefaultEndpointProvider(), true, registrations.ToArray());

            engine.SetReadHeadersAction(correlationManager.FetchCorrelationIfExists);
            engine.SetWriteHeadersFunc(correlationManager.BuildCorrelationHeadersIfExists);
            engine.StartPublishers();

            return(engine);
        }
        protected override void Load(ContainerBuilder builder)
        {
            MessagePackSerializerFactory.Defaults.FormatterResolver = MessagePack.Resolvers.ContractlessStandardResolver.Instance;
            var rabbitMqSettings = new RabbitMQ.Client.ConnectionFactory {
                Uri = new Uri(_settings.CurrentValue.SiriusCashoutProcessorJob.Cqrs.RabbitConnectionString)
            };

            builder.Register(context => new AutofacDependencyResolver(context)).As <IDependencyResolver>();
            builder.RegisterType <CashoutCommandHandler>()
            .WithParameter(TypedParameter.From(_settings.CurrentValue.SiriusApiServiceClient.BrokerAccountId))
            .WithParameter(TypedParameter.From(_settings.CurrentValue.SiriusCashoutProcessorJob.RetrySettings.NotEnoughBalanceRetryDelayInSeconds))
            .SingleInstance();

            builder.Register(ctx => new MessagingEngine(ctx.Resolve <ILogFactory>(),
                                                        new TransportResolver(new Dictionary <string, TransportInfo>
            {
                {
                    "RabbitMq",
                    new TransportInfo(rabbitMqSettings.Endpoint.ToString(), rabbitMqSettings.UserName,
                                      rabbitMqSettings.Password, "None", "RabbitMq")
                }
            }),
                                                        new RabbitMqTransportFactory(ctx.Resolve <ILogFactory>()))).As <IMessagingEngine>().SingleInstance();

            const string environment = "lykke";

            builder.Register(ctx =>
            {
                var engine = new CqrsEngine(ctx.Resolve <ILogFactory>(),
                                            ctx.Resolve <IDependencyResolver>(),
                                            ctx.Resolve <IMessagingEngine>(),
                                            new DefaultEndpointProvider(),
                                            true,
                                            Register.DefaultEndpointResolver(new RabbitMqConventionEndpointResolver(
                                                                                 "RabbitMq",
                                                                                 SerializationFormat.MessagePack,
                                                                                 environment: environment)),

                                            Register.EventInterceptors(new DefaultEventLoggingInterceptor(ctx.Resolve <ILogFactory>())),
                                            Register.CommandInterceptors(new DefaultCommandLoggingInterceptor(ctx.Resolve <ILogFactory>())),

                                            Register.BoundedContext(SiriusCashoutProcessorBoundedContext.Name)
                                            .ListeningCommands(typeof(StartCashoutCommand))
                                            .On("commands")
                                            .WithCommandsHandler <CashoutCommandHandler>()
                                            .PublishingEvents(
                                                typeof(CashoutCompletedEvent),
                                                typeof(CashoutFailedEvent)
                                                )
                                            .With("events")
                                            );

                engine.StartPublishers();

                return(engine);
            })
            .As <ICqrsEngine>()
            .SingleInstance()
            .AutoActivate();
        }
Ejemplo n.º 4
0
        protected override void Load(ContainerBuilder builder)
        {
            MessagePackSerializerFactory.Defaults.FormatterResolver = MessagePack.Resolvers.ContractlessStandardResolver.Instance;
            var rabbitMqSettings = new RabbitMQ.Client.ConnectionFactory
            {
                Uri = new Uri(_settings.SagasRabbitMq.RabbitConnectionString)
            };

            builder.Register(context => new AutofacDependencyResolver(context)).As <IDependencyResolver>().SingleInstance();

            builder.RegisterType <HistoryExportProjection>().SingleInstance();

            var messagingEngine = new MessagingEngine(_log,
                                                      new TransportResolver(new Dictionary <string, TransportInfo>
            {
                { "RabbitMq", new TransportInfo(rabbitMqSettings.Endpoint.ToString(), rabbitMqSettings.UserName, rabbitMqSettings.Password, "None", "RabbitMq") }
            }),
                                                      new RabbitMqTransportFactory());

            builder
            .Register(ctx =>
            {
                const string defaultPipeline = "commands";
                const string defaultRoute    = "self";

                var engine = new CqrsEngine(_log,
                                            ctx.Resolve <IDependencyResolver>(),
                                            messagingEngine,
                                            new DefaultEndpointProvider(),
                                            true,
                                            Register.DefaultEndpointResolver(new RabbitMqConventionEndpointResolver(
                                                                                 "RabbitMq",
                                                                                 SerializationFormat.MessagePack,
                                                                                 environment: "lykke",
                                                                                 exclusiveQueuePostfix: "k8s")),

                                            Register.BoundedContext("apiv2")
                                            .PublishingCommands(typeof(CreateCashoutCommand), typeof(CreateSwiftCashoutCommand))
                                            .To(OperationsBoundedContext.Name).With(defaultPipeline)
                                            .ListeningEvents(
                                                typeof(ClientHistoryExpiredEvent),
                                                typeof(ClientHistoryExportedEvent))
                                            .From(HistoryExportBuilderBoundedContext.Name).On(defaultRoute)
                                            .WithProjection(typeof(HistoryExportProjection), HistoryExportBuilderBoundedContext.Name)
                                            .PublishingCommands(typeof(ConfirmCommand))
                                            .To(OperationsBoundedContext.Name).With(defaultPipeline),

                                            Register.DefaultRouting
                                            .PublishingCommands(typeof(ExportClientHistoryCommand))
                                            .To(HistoryExportBuilderBoundedContext.Name).With(defaultPipeline)
                                            );
                engine.StartPublishers();
                return(engine);
            })
            .As <ICqrsEngine>()
            .SingleInstance()
            .AutoActivate();
        }
Ejemplo n.º 5
0
        public void FluentApiTest()
        {
            var endpointProvider = new Mock <IEndpointProvider>();

            endpointProvider.Setup(r => r.Get("high")).Returns(new Endpoint("InMemory", "high", true, SerializationFormat.Json));
            endpointProvider.Setup(r => r.Get("low")).Returns(new Endpoint("InMemory", "low", true, SerializationFormat.Json));
            endpointProvider.Setup(r => r.Get("medium")).Returns(new Endpoint("InMemory", "medium", true, SerializationFormat.Json));

            using (var messagingEngine = new MessagingEngine(
                       _logFactory,
                       new TransportResolver(new Dictionary <string, TransportInfo>
            {
                { "InMemory", new TransportInfo("none", "none", "none", null, "InMemory") },
                { "rmq", new TransportInfo("none", "none", "none", null, "InMemory") }
            })))
            {
                using (var engine = new CqrsEngine(
                           _logFactory,
                           messagingEngine,
                           endpointProvider.Object,
                           Register.BoundedContext("bc")
                           .PublishingCommands(typeof(string)).To("operations").With("operationsCommandsRoute")
                           .ListeningCommands(typeof(string)).On("commandsRoute")
                           //same as .PublishingCommands(typeof(string)).To("bc").With("selfCommandsRoute")
                           .WithLoopback("selfCommandsRoute")
                           .PublishingEvents(typeof(int)).With("eventsRoute")

                           //explicit prioritization
                           .ListeningCommands(typeof(string)).On("explicitlyPrioritizedCommandsRoute")
                           .Prioritized(lowestPriority: 2)
                           .WithEndpoint("high").For(key => key.Priority == 0)
                           .WithEndpoint("medium").For(key => key.Priority == 1)
                           .WithEndpoint("low").For(key => key.Priority == 2)

                           //resolver based prioritization
                           .ListeningCommands(typeof(string)).On("prioritizedCommandsRoute")
                           .Prioritized(lowestPriority: 2)
                           .WithEndpointResolver(new InMemoryEndpointResolver())
                           .WithCommandsHandler(typeof(CommandsHandler))
                           .ProcessingOptions("explicitlyPrioritizedCommandsRoute").MultiThreaded(10)
                           .ProcessingOptions("prioritizedCommandsRoute").MultiThreaded(10).QueueCapacity(1024),
                           Register.Saga <TestSaga>("saga")
                           .PublishingCommands(typeof(string)).To("operations").With("operationsCommandsRoute")
                           .ListeningEvents(typeof(int)).From("operations").On("operationEventsRoute"),
                           Register.DefaultRouting
                           .PublishingCommands(typeof(string)).To("operations").With("defaultCommandsRoute")
                           .PublishingCommands(typeof(int)).To("operations").With("defaultCommandsRoute"),
                           Register.DefaultEndpointResolver(
                               new RabbitMqConventionEndpointResolver("rmq", SerializationFormat.Json))
                           ))
                {
                    engine.StartPublishers();
                    engine.StartSubscribers();
                }
            }
        }
Ejemplo n.º 6
0
        protected override void Load(ContainerBuilder builder)
        {
            var rabbitMqSettings = new RabbitMQ.Client.ConnectionFactory {
                Uri = _appSettings.CurrentValue.SagasRabbitMq.RabbitConnectionString
            };

            builder.Register(context => new AutofacDependencyResolver(context)).As <IDependencyResolver>().SingleInstance();
            MessagePackSerializerFactory.Defaults.FormatterResolver = MessagePack.Resolvers.ContractlessStandardResolver.Instance;

            builder.RegisterType <AssetsProjection>();

            builder.Register(ctx => new MessagingEngine(ctx.Resolve <ILogFactory>(),
                                                        new TransportResolver(new Dictionary <string, TransportInfo>
            {
                { "RabbitMq", new TransportInfo(rabbitMqSettings.Endpoint.ToString(), rabbitMqSettings.UserName, rabbitMqSettings.Password, "None", "RabbitMq") }
            }),
                                                        new RabbitMqTransportFactory(ctx.Resolve <ILogFactory>()))).As <IMessagingEngine>().SingleInstance();

            builder.Register(ctx =>
            {
                var msgPackResolver = new RabbitMqConventionEndpointResolver(
                    "RabbitMq",
                    SerializationFormat.MessagePack,
                    environment: "lykke",
                    exclusiveQueuePostfix: "k8s");

                var engine = new CqrsEngine(
                    ctx.Resolve <ILogFactory>(),
                    ctx.Resolve <IDependencyResolver>(),
                    ctx.Resolve <IMessagingEngine>(),
                    new DefaultEndpointProvider(),
                    true,

                    Register.EventInterceptors(new DefaultEventLoggingInterceptor(ctx.Resolve <ILogFactory>())),

                    Register.DefaultEndpointResolver(msgPackResolver),

                    Register.BoundedContext(LimitationsBoundedContext.Name)
                    .ListeningEvents(typeof(AssetCreatedEvent), typeof(AssetUpdatedEvent))
                    .From(Assets.BoundedContext.Name).On("events")
                    .WithProjection(typeof(AssetsProjection), Assets.BoundedContext.Name)

                    .PublishingEvents(
                        typeof(ClientDepositEvent),
                        typeof(ClientWithdrawEvent)
                        ).With("events")
                    .WithEndpointResolver(msgPackResolver)
                    );

                engine.StartPublishers();
                return(engine);
            })
            .As <ICqrsEngine>()
            .AutoActivate()
            .SingleInstance();
        }
Ejemplo n.º 7
0
        protected override void Load(ContainerBuilder builder)
        {
            MessagePackSerializerFactory.Defaults.FormatterResolver = MessagePack.Resolvers.ContractlessStandardResolver.Instance;
            var rabbitMqSettings = new RabbitMQ.Client.ConnectionFactory
            {
                Uri = new Uri(_settings.RabbitConnectionString)
            };

            builder.Register(context => new AutofacDependencyResolver(context)).As <IDependencyResolver>().SingleInstance();

            builder
            .Register(ctx =>
            {
                var logFactory = ctx.Resolve <ILogFactory>();

                var messagingEngine = new MessagingEngine(
                    logFactory,
                    new TransportResolver(new Dictionary <string, TransportInfo>
                {
                    {
                        "RabbitMq",
                        new TransportInfo(rabbitMqSettings.Endpoint.ToString(),
                                          rabbitMqSettings.UserName,
                                          rabbitMqSettings.Password,
                                          "None",
                                          "RabbitMq")
                    }
                }),
                    new RabbitMqTransportFactory(logFactory));

                const string defaultPipeline = "commands";

                var engine = new CqrsEngine(logFactory,
                                            ctx.Resolve <IDependencyResolver>(),
                                            messagingEngine,
                                            new DefaultEndpointProvider(),
                                            true,
                                            Register.DefaultEndpointResolver(new RabbitMqConventionEndpointResolver(
                                                                                 "RabbitMq",
                                                                                 SerializationFormat.MessagePack,
                                                                                 environment: "lykke",
                                                                                 exclusiveQueuePostfix: "k8s")),

                                            Register.BoundedContext("hft-api")
                                            .PublishingCommands(typeof(CreateCashoutCommand))
                                            .To(OperationsBoundedContext.Name).With(defaultPipeline));
                engine.StartPublishers();
                return(engine);
            })
            .As <ICqrsEngine>()
            .SingleInstance()
            .AutoActivate();
        }
        protected override void Load(ContainerBuilder builder)
        {
            MessagePackSerializerFactory.Defaults.FormatterResolver = MessagePack.Resolvers.ContractlessStandardResolver.Instance;

            builder.Register(context => new AutofacDependencyResolver(context)).As <IDependencyResolver>().SingleInstance();

            var rabbitMqSettings = new RabbitMQ.Client.ConnectionFactory {
                Uri = _settings.CurrentValue.MarketDataService.Cqrs.ConnectionString
            };

            builder.Register(ctx =>
            {
                var logFactory      = ctx.Resolve <ILogFactory>();
                var broker          = rabbitMqSettings.Endpoint.ToString();
                var messagingEngine = new MessagingEngine(logFactory,
                                                          new TransportResolver(new Dictionary <string, TransportInfo>
                {
                    { "RabbitMq", new TransportInfo(broker, rabbitMqSettings.UserName, rabbitMqSettings.Password, "None", "RabbitMq") }
                }),
                                                          new RabbitMqTransportFactory(logFactory));

                var engine = new CqrsEngine(logFactory,
                                            ctx.Resolve <IDependencyResolver>(),
                                            messagingEngine,
                                            new DefaultEndpointProvider(),
                                            true,
                                            Register.DefaultEndpointResolver(new RabbitMqConventionEndpointResolver(
                                                                                 "RabbitMq",
                                                                                 SerializationFormat.MessagePack,
                                                                                 environment: "lykke",
                                                                                 exclusiveQueuePostfix: "marketdata")),

                                            Register.CommandInterceptors(new DefaultCommandLoggingInterceptor(logFactory)),
                                            Register.EventInterceptors(new DefaultEventLoggingInterceptor(logFactory)),

                                            Register.BoundedContext(MarketDataBoundedContext.Name)
                                            .WithAssetsReadModel(route: System.Environment.MachineName)
                                            .PublishingEvents(
                                                typeof(MarketDataChangedEvent)
                                                )
                                            .With("events")
                                            );

                engine.StartPublishers();
                return(engine);
            })
            .As <ICqrsEngine>()
            .AutoActivate()
            .SingleInstance();
        }
Ejemplo n.º 9
0
        public void PrioritizedCommandsProcessingTest()
        {
            var endpointProvider = new Mock <IEndpointProvider>();

            endpointProvider.Setup(r => r.Get("exchange1")).Returns(new Endpoint("InMemory", "bc.exchange1", true, SerializationFormat.Json));
            endpointProvider.Setup(r => r.Get("exchange2")).Returns(new Endpoint("InMemory", "bc.exchange2", true, SerializationFormat.Json));
            var commandHandler = new CommandsHandler(false, 100);

            using (var messagingEngine = new MessagingEngine(
                       _logFactory,
                       new TransportResolver(new Dictionary <string, TransportInfo>
            {
                { "InMemory", new TransportInfo("none", "none", "none", null, "InMemory") }
            })))
            {
                using (var engine = new CqrsEngine(
                           _logFactory,
                           messagingEngine,
                           endpointProvider.Object,
                           Register.DefaultEndpointResolver(new InMemoryEndpointResolver()),
                           Register.BoundedContext("bc")
                           .PublishingEvents(typeof(int)).With("eventExchange")//.WithLoopback("eventQueue")
                           .ListeningCommands(typeof(string)).On("commandsRoute")
                           .Prioritized(lowestPriority: 1)
                           .WithEndpoint("exchange1").For(key => key.Priority == 1)
                           .WithEndpoint("exchange2").For(key => key.Priority == 2)
                           .ProcessingOptions("commandsRoute").MultiThreaded(2)
                           .WithCommandsHandler(commandHandler)))
                {
                    engine.StartPublishers();
                    engine.StartSubscribers();
                    messagingEngine.Send("low1", new Endpoint("InMemory", "bc.exchange2", serializationFormat: SerializationFormat.Json));
                    messagingEngine.Send("low2", new Endpoint("InMemory", "bc.exchange2", serializationFormat: SerializationFormat.Json));
                    messagingEngine.Send("low3", new Endpoint("InMemory", "bc.exchange2", serializationFormat: SerializationFormat.Json));
                    messagingEngine.Send("low4", new Endpoint("InMemory", "bc.exchange2", serializationFormat: SerializationFormat.Json));
                    messagingEngine.Send("low5", new Endpoint("InMemory", "bc.exchange2", serializationFormat: SerializationFormat.Json));
                    messagingEngine.Send("low6", new Endpoint("InMemory", "bc.exchange2", serializationFormat: SerializationFormat.Json));
                    messagingEngine.Send("low7", new Endpoint("InMemory", "bc.exchange2", serializationFormat: SerializationFormat.Json));
                    messagingEngine.Send("low8", new Endpoint("InMemory", "bc.exchange2", serializationFormat: SerializationFormat.Json));
                    messagingEngine.Send("low9", new Endpoint("InMemory", "bc.exchange2", serializationFormat: SerializationFormat.Json));
                    messagingEngine.Send("low10", new Endpoint("InMemory", "bc.exchange2", serializationFormat: SerializationFormat.Json));
                    messagingEngine.Send("high", new Endpoint("InMemory", "bc.exchange1", serializationFormat: SerializationFormat.Json));
                    Thread.Sleep(2000);

                    Assert.True(commandHandler.HandledCommands.Take(2).Any(c => (string)c == "high"));
                }
            }
        }
Ejemplo n.º 10
0
        public void SagaTest()
        {
            var commandHandler = new CustomCommandsHandler();

            using (var messagingEngine = new MessagingEngine(
                       _logFactory,
                       new TransportResolver(new Dictionary <string, TransportInfo>
            {
                { "rmq", new TransportInfo("amqp://localhost/LKK", "guest", "guest", "None", "RabbitMq") }
            }),
                       new RabbitMqTransportFactory(_logFactory)))
            {
                using (var engine = new CqrsEngine(
                           _logFactory,
                           messagingEngine,
                           Register.DefaultEndpointResolver(
                               new RabbitMqConventionEndpointResolver("rmq", SerializationFormat.Json, environment: "dev")),
                           Register.BoundedContext("operations")
                           .PublishingCommands(typeof(CreateCashOutCommand)).To("lykke-wallet").With("operations-commands")
                           .ListeningEvents(typeof(CashOutCreatedEvent)).From("lykke-wallet").On("lykke-wallet-events"),

                           Register.BoundedContext("lykke-wallet")
                           .FailedCommandRetryDelay((long)TimeSpan.FromSeconds(2).TotalMilliseconds)
                           .ListeningCommands(typeof(CreateCashOutCommand)).On("operations-commands")
                           .PublishingEvents(typeof(CashOutCreatedEvent)).With("lykke-wallet-events")
                           .WithCommandsHandler(commandHandler),

                           Register.Saga <TestSaga>("swift-cashout")
                           .ListeningEvents(typeof(CashOutCreatedEvent)).From("lykke-wallet").On("lykke-wallet-events"),

                           Register.DefaultRouting.PublishingCommands(typeof(CreateCashOutCommand)).To("lykke-wallet")
                           .With("operations-commands"))
                       )
                {
                    engine.StartPublishers();
                    engine.StartSubscribers();
                    engine.SendCommand(new CreateCashOutCommand {
                        Payload = "test data"
                    }, null, "lykke-wallet");

                    Assert.True(TestSaga.Complete.WaitOne(2000), "Saga has not got events or failed to send command");
                }
            }
        }
        private CqrsEngine CreateEngine(IComponentContext ctx)
        {
            var rabbitMqSettings = new ConnectionFactory
            {
                Uri = _cqrsSettings.RabbitConnectionString
            };

            var messagingEngine = new MessagingEngine
                                  (
                ctx.Resolve <ILogFactory>(),
                new TransportResolver(new Dictionary <string, TransportInfo>
            {
                {
                    "RabbitMq",
                    new TransportInfo
                    (
                        broker: rabbitMqSettings.Endpoint.ToString(),
                        login: rabbitMqSettings.UserName,
                        password: rabbitMqSettings.Password,
                        jailStrategyName: "None",
                        messaging: "RabbitMq"
                    )
                }
            }),
                new RabbitMqTransportFactory(ctx.Resolve <ILogFactory>())
                                  );

            var engine = new CqrsEngine
                         (
                logFactory: ctx.Resolve <ILogFactory>(),
                dependencyResolver: ctx.Resolve <IDependencyResolver>(),
                messagingEngine: messagingEngine,
                endpointProvider: new DefaultEndpointProvider(),
                createMissingEndpoints: true,
                registrations: ConfigureCqrsEngine()
                         );

            engine.StartPublishers();

            return(engine);
        }
Ejemplo n.º 12
0
        public void ContextUsesDefaultRouteForCommandPublishingIfItDoesNotHaveItsOwnTest()
        {
            var bcCommands      = new Endpoint("InMemory", "bcCommands", serializationFormat: SerializationFormat.Json);
            var defaultCommands = new Endpoint("InMemory", "defaultCommands", serializationFormat: SerializationFormat.Json);

            using (var messagingEngine = new MessagingEngine(
                       _logFactory,
                       new TransportResolver(new Dictionary <string, TransportInfo>
            {
                { "InMemory", new TransportInfo("none", "none", "none", null, "InMemory") }
            })))
            {
                using (var engine = new CqrsEngine(
                           _logFactory,
                           messagingEngine,
                           Register.DefaultEndpointResolver(new InMemoryEndpointResolver()),
                           Register.BoundedContext("bc2")
                           .PublishingCommands(typeof(int)).To("bc1").With("bcCommands"),
                           Register.DefaultRouting
                           .PublishingCommands(typeof(string)).To("bc1").With("defaultCommands")
                           .PublishingCommands(typeof(int)).To("bc1").With("defaultCommands")))
                {
                    engine.StartPublishers();
                    var received = new AutoResetEvent(false);
                    using (messagingEngine.Subscribe(defaultCommands, o => received.Set(), s => { }, typeof(string)))
                    {
                        engine.SendCommand("test", "bc2", "bc1");
                        Assert.That(received.WaitOne(2000), Is.True, "not defined for context command was not routed with default route map");
                    }

                    using (messagingEngine.Subscribe(bcCommands, o => received.Set(), s => { }, typeof(int)))
                    {
                        engine.SendCommand(1, "bc2", "bc1");
                        Assert.That(received.WaitOne(2000), Is.True, "defined for context command was not routed with context route map");
                    }
                }
            }
        }
Ejemplo n.º 13
0
        private CqrsEngine CreateEngine(IComponentContext ctx, IMessagingEngine messagingEngine)
        {
            var rabbitMqConventionEndpointResolver = new RabbitMqConventionEndpointResolver(
                "RabbitMq",
                SerializationFormat.MessagePack,
                environment: _settings.EnvironmentName);

            var engine = new CqrsEngine(
                _log,
                ctx.Resolve <IDependencyResolver>(),
                messagingEngine,
                new DefaultEndpointProvider(),
                true,
                Register.DefaultEndpointResolver(rabbitMqConventionEndpointResolver),
                RegisterDefaultRouting(),
                RegisterContext(),
                Register.CommandInterceptors(new DefaultCommandLoggingInterceptor(_log)),
                Register.EventInterceptors(new DefaultEventLoggingInterceptor(_log)));

            engine.StartPublishers();

            return(engine);
        }
        private CqrsEngine CreateEngine(
            IComponentContext ctx,
            IMessagingEngine messagingEngine,
            ILogFactory logFactory)
        {
            const string defaultPipeline = "commands";
            const string defaultRoute    = "self";

            var sagasMessagePackEndpointResolver = new RabbitMqConventionEndpointResolver(
                "RabbitMq",
                SerializationFormat.MessagePack,
                environment: "lykke");

            var sagasProtobufEndpointResolver = new RabbitMqConventionEndpointResolver(
                "RabbitMq",
                SerializationFormat.ProtoBuf,
                environment: "lykke");

            var engine = new CqrsEngine(
                logFactory,
                ctx.Resolve <IDependencyResolver>(),
                messagingEngine,
                new DefaultEndpointProvider(),
                true,
                Register.DefaultEndpointResolver(sagasMessagePackEndpointResolver),

                Register.EventInterceptors(new DefaultEventLoggingInterceptor(ctx.Resolve <ILogFactory>())),
                Register.CommandInterceptors(new DefaultCommandLoggingInterceptor(ctx.Resolve <ILogFactory>())),

                Register.BoundedContext(BoundedContext.ForwardWithdrawal)
                .ListeningCommands(
                    typeof(ProcessPaymentCommand),
                    typeof(RemoveEntryCommand),
                    typeof(RemoveEntryFromHistoryJobCommand),
                    typeof(RemoveEntryFromHistoryServiceCommand))
                .On(defaultRoute)
                .PublishingEvents(
                    typeof(PaymentEntryRemovedEvent),
                    typeof(CashInRemovedFromHistoryJobEvent),
                    typeof(CashInRemovedFromHistoryServiceEvent),
                    typeof(CashInProcesedEvent))
                .With(defaultPipeline)
                .WithCommandsHandler(typeof(CommandsHandler)),
                Register.Saga <PaymentSaga>("payment-saga")
                .ListeningEvents(
                    typeof(PaymentEntryRemovedEvent),
                    typeof(CashInRemovedFromHistoryJobEvent),
                    typeof(CashInRemovedFromHistoryServiceEvent),
                    typeof(CashInProcesedEvent))
                .From(BoundedContext.ForwardWithdrawal).On(defaultRoute)
                .PublishingCommands(
                    typeof(ProcessPaymentCommand),
                    typeof(RemoveEntryCommand),
                    typeof(RemoveEntryFromHistoryJobCommand),
                    typeof(RemoveEntryFromHistoryServiceCommand))
                .To(BoundedContext.ForwardWithdrawal).With(defaultPipeline)
                .PublishingCommands(
                    typeof(DeleteForwardCashinCommand))
                .To(HistoryBoundedContext.Name)
                .With(defaultPipeline)
                .WithEndpointResolver(sagasProtobufEndpointResolver),
                Register.Saga <CashoutsSaga>("cashouts-saga")
                .ListeningEvents(typeof(CashOutProcessedEvent))
                .From(PostProcessingBoundedContext.Name)
                .On(defaultRoute)
                .WithEndpointResolver(sagasProtobufEndpointResolver)
                .PublishingCommands(
                    typeof(CreateForwardCashinCommand))
                .To(HistoryBoundedContext.Name)
                .With(defaultPipeline)
                .WithEndpointResolver(sagasProtobufEndpointResolver),
                Register.DefaultRouting
                .PublishingCommands(typeof(RemoveEntryCommand))
                .To(BoundedContext.ForwardWithdrawal)
                .With(defaultPipeline));

            engine.StartPublishers();

            return(engine);
        }
Ejemplo n.º 15
0
        protected override void Load(ContainerBuilder builder)
        {
            if (_settings.TransactionHandlerJob.ChaosKitty != null)
            {
                ChaosKitty.StateOfChaos = _settings.TransactionHandlerJob.ChaosKitty.StateOfChaos;
            }

            MessagePackSerializerFactory.Defaults.FormatterResolver = MessagePack.Resolvers.ContractlessStandardResolver.Instance;

            builder.Register(context => new AutofacDependencyResolver(context)).As <IDependencyResolver>().SingleInstance();

            var rabbitMqSettings = new RabbitMQ.Client.ConnectionFactory {
                Uri = _settings.TransactionHandlerJob.SagasRabbitMqConnStr
            };

            builder.Register(ctx =>
            {
                var logFactory = ctx.Resolve <ILogFactory>();
                return(new MessagingEngine(
                           logFactory,
                           new TransportResolver(new Dictionary <string, TransportInfo>
                {
                    {
                        "RabbitMq",
                        new TransportInfo(
                            rabbitMqSettings.Endpoint.ToString(),
                            rabbitMqSettings.UserName,
                            rabbitMqSettings.Password, "None", "RabbitMq")
                    }
                }),
                           new RabbitMqTransportFactory(logFactory)));
            });

            var defaultRetryDelay = _settings.TransactionHandlerJob.RetryDelayInMilliseconds;
            var longRetryDelay    = defaultRetryDelay * 60;

            builder.RegisterType <CashInOutMessageProcessor>();
            builder.RegisterType <ForwardWithdawalSaga>();
            builder.RegisterType <HistorySaga>();
            builder.RegisterType <TradeSaga>();
            builder.RegisterType <TransferSaga>();
            builder.RegisterType <EthereumCoreSaga>();

            builder.RegisterType <ForwardWithdrawalCommandHandler>();
            builder.RegisterType <BitcoinCommandHandler>()
            .WithParameter(TypedParameter.From(TimeSpan.FromMilliseconds(longRetryDelay))).SingleInstance();
            builder.RegisterType <EthereumCommandHandler>()
            .WithParameter(TypedParameter.From(_settings.Ethereum))
            .WithParameter(TypedParameter.From(TimeSpan.FromMilliseconds(longRetryDelay)));
            builder.RegisterType <OffchainCommandHandler>();
            builder.RegisterType <OperationsCommandHandler>()
            .WithParameter(TypedParameter.From(TimeSpan.FromMilliseconds(longRetryDelay)));
            builder.RegisterType <TradeCommandHandler>();

            builder.RegisterType <HistoryCommandHandler>();
            builder.RegisterType <LimitOrderCommandHandler>();
            builder.RegisterType <EthereumCoreCommandHandler>();

            builder.RegisterType <OperationHistoryProjection>();
            builder.RegisterType <OrdersProjection>();

            builder.RegisterType <ContextFactory>().As <IContextFactory>().SingleInstance();
            builder.RegisterType <ClientTradesFactory>().As <IClientTradesFactory>().SingleInstance();

            builder.Register(ctx =>
            {
                const string commandsRoute = "commands";
                const string eventsRoute   = "events";
                const string defaultRoute  = "self";

                var engine = new CqrsEngine(
                    ctx.Resolve <ILogFactory>(),
                    ctx.Resolve <IDependencyResolver>(),
                    ctx.Resolve <MessagingEngine>(),
                    new DefaultEndpointProvider(),
                    true,
                    Register.DefaultEndpointResolver(new RabbitMqConventionEndpointResolver(
                                                         "RabbitMq",
                                                         SerializationFormat.MessagePack,
                                                         environment: "lykke",
                                                         exclusiveQueuePostfix: _settings.TransactionHandlerJob.QueuePostfix)),

                    Register.BoundedContext(BoundedContexts.Trades)
                    .FailedCommandRetryDelay(defaultRetryDelay)
                    .ListeningCommands(typeof(CreateTradeCommand), typeof(CreateTransactionCommand))
                    .On(defaultRoute)
                    .PublishingEvents(typeof(TradeCreatedEvent))
                    .With(eventsRoute)
                    .WithCommandsHandler <TradeCommandHandler>(),

                    Register.BoundedContext(BoundedContexts.Orders)
                    .ListeningEvents(typeof(TradeCreatedEvent))
                    .From(BoundedContexts.Trades).On(defaultRoute)
                    .WithProjection(typeof(OrdersProjection), BoundedContexts.Trades),

                    Register.Saga <TradeSaga>($"{BoundedContexts.TxHandler}.trade-saga")
                    .ListeningEvents(typeof(TradeCreatedEvent))
                    .From(BoundedContexts.Trades).On(defaultRoute)
                    .PublishingCommands(typeof(CreateTransactionCommand))
                    .To(BoundedContexts.Trades).With(commandsRoute),

                    Register.BoundedContext(BoundedContexts.TxHandler)
                    .FailedCommandRetryDelay(defaultRetryDelay)
                    .ListeningCommands(typeof(ProcessLimitOrderCommand))
                    .On(commandsRoute)
                    .WithLoopback()
                    .PublishingEvents(typeof(LimitOrderExecutedEvent))
                    .With(eventsRoute)
                    .WithCommandsHandler <LimitOrderCommandHandler>(),

                    Register.BoundedContext(BoundedContexts.ForwardWithdrawal)
                    .FailedCommandRetryDelay(defaultRetryDelay)
                    .ListeningCommands(typeof(SetLinkedCashInOperationCommand))
                    .On(defaultRoute)
                    .PublishingEvents(typeof(ForwardWithdawalLinkedEvent))
                    .With(eventsRoute)
                    .WithCommandsHandler <ForwardWithdrawalCommandHandler>(),

                    Register.BoundedContext(BoundedContexts.Bitcoin)
                    .FailedCommandRetryDelay(defaultRetryDelay)
                    .ListeningCommands(typeof(SegwitTransferCommand))
                    .On(defaultRoute)
                    .WithCommandsHandler <BitcoinCommandHandler>(),

                    Register.BoundedContext(BoundedContexts.Ethereum)
                    .FailedCommandRetryDelay(defaultRetryDelay)
                    .ListeningCommands(typeof(TransferEthereumCommand))
                    .On(defaultRoute)
                    .PublishingEvents(typeof(EthereumTransferSentEvent))
                    .With(eventsRoute)
                    .WithCommandsHandler <EthereumCommandHandler>(),

                    Register.BoundedContext(BoundedContexts.EthereumCommands)
                    .FailedCommandRetryDelay(defaultRetryDelay)
                    .ListeningCommands(typeof(ProcessEthCoinEventCommand),
                                       typeof(ProcessHotWalletErc20EventCommand))
                    .On(defaultRoute)
                    .WithLoopback(defaultRoute)
                    .ListeningCommands(typeof(EnrollEthCashinToMatchingEngineCommand),
                                       typeof(SaveEthInHistoryCommand))
                    .On(defaultRoute)
                    .PublishingEvents(typeof(CashinDetectedEvent),
                                      typeof(EthCashinEnrolledToMatchingEngineEvent),
                                      typeof(EthCashinSavedInHistoryEvent))
                    .With(eventsRoute)
                    .WithCommandsHandler <EthereumCoreCommandHandler>()
                    .ProcessingOptions(defaultRoute).MultiThreaded(4).QueueCapacity(1024),

                    Register.BoundedContext(BoundedContexts.Offchain)
                    .FailedCommandRetryDelay(defaultRetryDelay)
                    .ListeningCommands(typeof(CreateOffchainCashoutRequestCommand))
                    .On(defaultRoute)
                    .WithCommandsHandler <OffchainCommandHandler>(),

                    Register.BoundedContext(BoundedContexts.Operations)
                    .FailedCommandRetryDelay(defaultRetryDelay)
                    .ListeningCommands(
                        typeof(SaveTransferOperationStateCommand),
                        typeof(SaveManualOperationStateCommand),
                        typeof(SaveCashoutOperationStateCommand),
                        typeof(SaveIssueOperationStateCommand),
                        typeof(CompleteOperationCommand))
                    .On(defaultRoute)
                    .PublishingEvents(
                        typeof(TransferOperationStateSavedEvent),
                        typeof(ManualTransactionStateSavedEvent),
                        typeof(IssueTransactionStateSavedEvent),
                        typeof(CashoutTransactionStateSavedEvent))
                    .With(eventsRoute)
                    .WithCommandsHandler <OperationsCommandHandler>(),

                    Register.BoundedContext(BoundedContexts.OperationsHistory)
                    .FailedCommandRetryDelay(defaultRetryDelay)
                    .ListeningEvents(
                        typeof(TransferOperationStateSavedEvent),
                        typeof(ManualTransactionStateSavedEvent),
                        typeof(IssueTransactionStateSavedEvent),
                        typeof(CashoutTransactionStateSavedEvent))
                    .From(BoundedContexts.Operations).On(defaultRoute)
                    .WithProjection(typeof(OperationHistoryProjection), BoundedContexts.Operations)
                    .ListeningEvents(typeof(ForwardWithdawalLinkedEvent))
                    .From(BoundedContexts.ForwardWithdrawal).On(defaultRoute)
                    .WithProjection(typeof(OperationHistoryProjection), BoundedContexts.ForwardWithdrawal)
                    .ListeningEvents(typeof(TradeCreatedEvent))
                    .From(BoundedContexts.Trades).On(defaultRoute)
                    .WithProjection(typeof(OperationHistoryProjection), BoundedContexts.Trades)
                    .ListeningEvents(typeof(LimitOrderExecutedEvent))
                    .From(BoundedContexts.TxHandler).On(defaultRoute)
                    .WithProjection(typeof(OperationHistoryProjection), BoundedContexts.TxHandler)
                    .ProcessingOptions(defaultRoute).MultiThreaded(4).QueueCapacity(1024)
                    .ListeningCommands(typeof(UpdateLimitOrdersCountCommand))
                    .On(commandsRoute)
                    .WithCommandsHandler <HistoryCommandHandler>(),

                    Register.Saga <ForwardWithdawalSaga>($"{BoundedContexts.TxHandler}.forward-withdrawal-saga")
                    .ListeningEvents(typeof(CashoutTransactionStateSavedEvent))
                    .From(BoundedContexts.Operations).On(defaultRoute)
                    .PublishingCommands(typeof(SetLinkedCashInOperationCommand))
                    .To(BoundedContexts.ForwardWithdrawal).With(commandsRoute),

                    Register.Saga <HistorySaga>("history-saga")
                    .ListeningEvents(typeof(LimitOrderExecutedEvent))
                    .From(BoundedContexts.TxHandler).On("events")
                    .PublishingCommands(typeof(UpdateLimitOrdersCountCommand))
                    .To(BoundedContexts.OperationsHistory).With(commandsRoute),

                    Register.Saga <TransferSaga>("transfers-saga")
                    .ListeningEvents(typeof(TransferOperationStateSavedEvent))
                    .From(BoundedContexts.Operations).On(defaultRoute)
                    .ListeningEvents(typeof(EthereumTransferSentEvent))
                    .From(BoundedContexts.Ethereum).On(defaultRoute)
                    .PublishingCommands(typeof(TransferEthereumCommand))
                    .To(BoundedContexts.Ethereum).With(commandsRoute)
                    .PublishingCommands(typeof(CompleteOperationCommand))
                    .To(BoundedContexts.Operations).With(commandsRoute),

                    Register.Saga <EthereumCoreSaga>("ethereum-core-saga")
                    .ListeningEvents(typeof(CashinDetectedEvent),
                                     typeof(EthCashinEnrolledToMatchingEngineEvent),
                                     typeof(EthCashinSavedInHistoryEvent))
                    .From(BoundedContexts.EthereumCommands).On(defaultRoute)
                    .PublishingCommands(typeof(EnrollEthCashinToMatchingEngineCommand),
                                        typeof(SaveEthInHistoryCommand))
                    .To(BoundedContexts.EthereumCommands).With(commandsRoute)
                    .ProcessingOptions(defaultRoute).MultiThreaded(4).QueueCapacity(1024),

                    Register.DefaultRouting
                    .PublishingCommands(typeof(CreateOffchainCashoutRequestCommand))
                    .To(BoundedContexts.Offchain).With(commandsRoute)
                    .PublishingCommands(typeof(SegwitTransferCommand))
                    .To(BoundedContexts.Bitcoin).With(commandsRoute)
                    .PublishingCommands(typeof(SaveManualOperationStateCommand), typeof(SaveIssueOperationStateCommand), typeof(SaveCashoutOperationStateCommand))
                    .To(BoundedContexts.Operations).With(commandsRoute)
                    .PublishingCommands(typeof(CreateTradeCommand))
                    .To(BoundedContexts.Trades).With(commandsRoute)
                    .PublishingCommands(typeof(SaveTransferOperationStateCommand))
                    .To(BoundedContexts.Operations).With(commandsRoute)
                    );
                engine.StartPublishers();
                return(engine);
            })
            .As <ICqrsEngine>()
            .AutoActivate()
            .SingleInstance();
        }
Ejemplo n.º 16
0
        protected override void Load(ContainerBuilder builder)
        {
            if (_settings.ChaosKitty != null)
            {
                builder
                .RegisterType <ChaosKitty>()
                .WithParameter(TypedParameter.From(_settings.ChaosKitty.StateOfChaos))
                .As <IChaosKitty>()
                .SingleInstance();
            }
            else
            {
                builder
                .RegisterType <SilentChaosKitty>()
                .As <IChaosKitty>()
                .SingleInstance();
            }

            builder.Register(context => new AutofacDependencyResolver(context)).As <IDependencyResolver>().SingleInstance();

            var rabbitMqSettings = new RabbitMQ.Client.ConnectionFactory {
                Uri = _settings.RabbitConnectionString
            };

            builder.Register(ctx => new MessagingEngine(ctx.Resolve <ILogFactory>(),
                                                        new TransportResolver(new Dictionary <string, TransportInfo>
            {
                {
                    "RabbitMq",
                    new TransportInfo(rabbitMqSettings.Endpoint.ToString(), rabbitMqSettings.UserName,
                                      rabbitMqSettings.Password, "None", "RabbitMq")
                }
            }),
                                                        new RabbitMqTransportFactory(ctx.Resolve <ILogFactory>()))).As <IMessagingEngine>().SingleInstance();

            builder.RegisterType <BalancesUpdateProjection>();
            builder.RegisterType <TotalBalanceCommandHandler>();

            builder.Register(ctx =>
            {
                const string defaultRoute    = "self";
                const string defaultPipeline = "commands";

                var engine = new CqrsEngine(ctx.Resolve <ILogFactory>(),
                                            ctx.Resolve <IDependencyResolver>(),
                                            ctx.Resolve <IMessagingEngine>(),
                                            new DefaultEndpointProvider(),
                                            true,
                                            Register.DefaultEndpointResolver(new RabbitMqConventionEndpointResolver(
                                                                                 "RabbitMq",
                                                                                 Messaging.Serialization.SerializationFormat.ProtoBuf,
                                                                                 environment: "lykke",
                                                                                 exclusiveQueuePostfix: "k8s")),

                                            Register.BoundedContext(BoundedContext.Name)
                                            .ListeningCommands(typeof(UpdateTotalBalanceCommand))
                                            .On(defaultPipeline)
                                            .WithCommandsHandler <TotalBalanceCommandHandler>()
                                            .PublishingEvents(typeof(BalanceUpdatedEvent))
                                            .With(defaultRoute)
                                            .ListeningEvents(typeof(BalanceUpdatedEvent))
                                            .From(BoundedContext.Name).On(defaultRoute)
                                            .WithProjection(typeof(BalancesUpdateProjection), BoundedContext.Name),

                                            Register.DefaultRouting
                                            .PublishingCommands(typeof(UpdateTotalBalanceCommand))
                                            .To(BoundedContext.Name).With(defaultPipeline)
                                            );

                engine.StartPublishers();
                return(engine);
            })
            .As <ICqrsEngine>()
            .SingleInstance()
            .AutoActivate();
        }
        protected override void Load(ContainerBuilder builder)
        {
            if (_settings.ChaosKitty != null)
            {
                builder
                .RegisterType <ChaosKitty>()
                .WithParameter(TypedParameter.From(_settings.ChaosKitty.StateOfChaos))
                .As <IChaosKitty>()
                .SingleInstance();
            }
            else
            {
                builder
                .RegisterType <SilentChaosKitty>()
                .As <IChaosKitty>()
                .SingleInstance();
            }

            MessagePackSerializerFactory.Defaults.FormatterResolver =
                MessagePack.Resolvers.ContractlessStandardResolver.Instance;

            builder
            .Register(context => new AutofacDependencyResolver(context))
            .As <IDependencyResolver>()
            .SingleInstance();

            var rabbitMqSettings = new RabbitMQ.Client.ConnectionFactory {
                Uri = new Uri(_settings.SagasRabbitMqConnStr)
            };

            builder.RegisterType <ApiKeyHandler>()
            .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);

            builder.Register(ctx =>
            {
                var logFactory      = ctx.Resolve <ILogFactory>();
                var broker          = rabbitMqSettings.Endpoint.ToString();
                var messagingEngine = new MessagingEngine(logFactory,
                                                          new TransportResolver(new Dictionary <string, TransportInfo>
                {
                    {
                        "RabbitMq",
                        new TransportInfo(broker, rabbitMqSettings.UserName, rabbitMqSettings.Password, "None",
                                          "RabbitMq")
                    }
                }),
                                                          new RabbitMqTransportFactory(logFactory));

                var defaultRetryDelay = (long)_settings.RetryDelay.TotalMilliseconds;

                const string defaultPipeline = "commands";
                const string defaultRoute    = "self";

                var engine = new CqrsEngine(logFactory,
                                            ctx.Resolve <IDependencyResolver>(),
                                            messagingEngine,
                                            new DefaultEndpointProvider(),
                                            true,
                                            Register.DefaultEndpointResolver(new RabbitMqConventionEndpointResolver(
                                                                                 "RabbitMq",
                                                                                 SerializationFormat.MessagePack,
                                                                                 environment: "lykke",
                                                                                 exclusiveQueuePostfix: _settings.QueuePostfix)),

                                            Register.EventInterceptors(new DefaultEventLoggingInterceptor(ctx.Resolve <ILogFactory>())),

                                            Register.BoundedContext("api-key")
                                            .FailedCommandRetryDelay(defaultRetryDelay)
                                            .ListeningCommands(
                                                typeof(CreateApiKeyCommand),
                                                typeof(DisableApiKeyCommand),
                                                typeof(SetTokensCommand)
                                                )
                                            .On(defaultRoute)
                                            .PublishingEvents(
                                                typeof(ApiKeyUpdatedEvent))
                                            .With(defaultPipeline)
                                            .WithCommandsHandler <ApiKeyHandler>(),

                                            Register.DefaultRouting
                                            .PublishingCommands(
                                                typeof(CreateApiKeyCommand),
                                                typeof(DisableApiKeyCommand),
                                                typeof(SetTokensCommand)
                                                )
                                            .To("api-key").With(defaultPipeline)
                                            );

                engine.StartPublishers();
                return(engine);
            })
            .As <ICqrsEngine>()
            .AutoActivate()
            .SingleInstance();
        }
Ejemplo n.º 18
0
        private CqrsEngine CreateEngine(IComponentContext ctx)
        {
            var logFactory        = ctx.Resolve <ILogFactory>();
            var messagingEngine   = RegisterMessagingEngine(ctx);
            var defaultRetryDelay = (long)_settings.RetryDelay.TotalMilliseconds;

            const string defaultPipeline = "commands";
            const string defaultRoute    = "self";
            const string eventsRoute     = "evets";

            var registration = new List <IRegistration>()
            {
                Register.DefaultEndpointResolver(GetDefaultEndpointResolver()),
                Register.BoundedContext(Self)
                .FailedCommandRetryDelay(defaultRetryDelay)

                .ListeningCommands(typeof(LockDepositWalletCommand))
                .On(defaultRoute)
                .WithLoopback()    //When it is sent not from saga
                .WithCommandsHandler <LockDepositWalletCommandsHandler>()
                .PublishingEvents(typeof(DepositWalletLockedEvent))
                .With(defaultPipeline)

                .ListeningCommands(typeof(RetrieveClientCommand))
                .On(defaultRoute)
                .WithCommandsHandler <RetrieveClientCommandHandler>()
                .PublishingEvents(typeof(ClientRetrievedEvent))
                .With(defaultPipeline)

                .ListeningCommands(typeof(EnrollToMatchingEngineCommand))
                .On(defaultRoute)
                .WithCommandsHandler <EnrollToMatchingEngineCommandsHandler>()
                .PublishingEvents(typeof(CashinEnrolledToMatchingEngineEvent))
                .With(defaultPipeline)

                .ListeningCommands(typeof(SetEnrolledBalanceCommand))
                .On(defaultRoute)
                .WithCommandsHandler <SetEnrolledBalanceCommandHandler>()
                .PublishingEvents(typeof(EnrolledBalanceSetEvent))
                .With(defaultPipeline)

                .ListeningCommands(typeof(ResetEnrolledBalanceCommand))
                .On(defaultRoute)
                .WithCommandsHandler <ResetEnrolledBalanceCommandHandler>()
                .PublishingEvents(typeof(EnrolledBalanceResetEvent))
                .With(defaultPipeline)

                .ListeningCommands(typeof(ReleaseDepositWalletLockCommand))
                .On(defaultRoute)
                .WithCommandsHandler <ReleaseDepositWalletLockCommandHandler>()
                .PublishingEvents(typeof(DepositWalletLockReleasedEvent))
                .With(defaultPipeline)

                .ListeningCommands(typeof(NotifyCashinCompletedCommand))
                .On(defaultRoute)
                .WithCommandsHandler <NotifyCashinCompletedCommandsHandler>()
                .PublishingEvents(typeof(CashinCompletedEvent))
                .With(eventsRoute)

                .ListeningCommands(typeof(NotifyCashinFailedCommand))
                .On(defaultRoute)
                .WithCommandsHandler <NotifyCashinFailedCommandsHandler>()
                .PublishingEvents(typeof(CashinFailedEvent))
                .With(eventsRoute)


                .ListeningEvents(typeof(EnrolledBalanceSetEvent))
                .From(Self)
                .On(eventsRoute)
                .WithProjection(typeof(MatchingEngineCallDeduplicationsProjection), Self)

                .ListeningEvents(typeof(BlockchainOperationsExecutor.Contract.Events.OperationExecutionCompletedEvent))
                .From(BlockchainOperationsExecutorBoundedContext.Name)
                .On(eventsRoute)
                .WithProjection(typeof(MatchingEngineCallDeduplicationsProjection),
                                BlockchainOperationsExecutorBoundedContext.Name)

                .ListeningEvents(typeof(BlockchainOperationsExecutor.Contract.Events.OperationExecutionFailedEvent))
                .From(BlockchainOperationsExecutorBoundedContext.Name)
                .On(eventsRoute)
                .WithProjection(typeof(MatchingEngineCallDeduplicationsProjection), BlockchainOperationsExecutorBoundedContext.Name)

                .ProcessingOptions(defaultRoute).MultiThreaded(8).QueueCapacity(1024)
                .ProcessingOptions(eventsRoute).MultiThreaded(8).QueueCapacity(1024),

                Register.Saga <CashinSaga>($"{Self}.saga")
                .ListeningEvents(typeof(DepositWalletLockedEvent))
                .From(Self)
                .On(defaultRoute)
                .PublishingCommands(
                    typeof(RetrieveClientCommand),
                    typeof(ReleaseDepositWalletLockCommand))
                .To(Self)
                .With(defaultPipeline)

                .ListeningEvents(typeof(ClientRetrievedEvent))
                .From(Self)
                .On(defaultRoute)
                .PublishingCommands(typeof(BlockchainRiskControl.Contract.Commands.ValidateOperationCommand))
                .To(BlockchainRiskControl.Contract.BlockchainRiskControlBoundedContext.Name)
                .With(defaultPipeline)

                .ListeningEvents(typeof(BlockchainRiskControl.Contract.Events.OperationAcceptedEvent))
                .From(BlockchainRiskControl.Contract.BlockchainRiskControlBoundedContext.Name)
                .On(defaultRoute)
                .PublishingCommands(typeof(EnrollToMatchingEngineCommand))
                .To(Self)
                .With(defaultPipeline)

                .ListeningEvents(typeof(BlockchainRiskControl.Contract.Events.OperationRejectedEvent))
                .From(BlockchainRiskControl.Contract.BlockchainRiskControlBoundedContext.Name)
                .On(defaultRoute)
                .PublishingCommands(typeof(ReleaseDepositWalletLockCommand))
                .To(Self)
                .With(defaultPipeline)

                .ListeningEvents(typeof(CashinEnrolledToMatchingEngineEvent))
                .From(Self)
                .On(defaultRoute)
                .PublishingCommands(typeof(SetEnrolledBalanceCommand))
                .To(Self)
                .With(defaultPipeline)

                .ListeningEvents(typeof(EnrolledBalanceSetEvent))
                .From(Self)
                .On(defaultRoute)
                .PublishingCommands(typeof(BlockchainOperationsExecutor.Contract.Commands.StartOperationExecutionCommand))
                .To(BlockchainOperationsExecutorBoundedContext.Name)
                .With(defaultPipeline)

                .ListeningEvents(typeof(BlockchainOperationsExecutor.Contract.Events.OperationExecutionCompletedEvent))
                .From(BlockchainOperationsExecutorBoundedContext.Name)
                .On(defaultRoute)
                .PublishingCommands(typeof(ResetEnrolledBalanceCommand))
                .To(Self)
                .With(defaultPipeline)

                .ListeningEvents(typeof(EnrolledBalanceResetEvent))
                .From(Self)
                .On(defaultRoute)
                .PublishingCommands(typeof(ReleaseDepositWalletLockCommand))
                .To(Self)
                .With(defaultPipeline)

                .ListeningEvents(typeof(BlockchainOperationsExecutor.Contract.Events.OperationExecutionFailedEvent))
                .From(BlockchainOperationsExecutorBoundedContext.Name)
                .On(defaultRoute)

                .ListeningEvents(typeof(DepositWalletLockReleasedEvent))
                .From(Self)
                .On(defaultRoute)
                .PublishingCommands(
                    typeof(NotifyCashinFailedCommand),
                    typeof(NotifyCashinCompletedCommand))
                .To(Self)
                .With(defaultPipeline)

                .ProcessingOptions(defaultRoute).MultiThreaded(8).QueueCapacity(1024),

                Register.BoundedContext(BlockchainRiskControl.Contract.BlockchainRiskControlBoundedContext.Name)
                .FailedCommandRetryDelay(defaultRetryDelay)
                .PublishingEvents(typeof(BlockchainRiskControl.Contract.Events.OperationRejectedEvent))
                .With(eventsRoute)
            };

            var interceptors = GetInterceptors();

            if (interceptors != null)
            {
                registration.AddRange(interceptors);
            }

            var cqrsEngine = new CqrsEngine(
                logFactory,
                ctx.Resolve <IDependencyResolver>(),
                messagingEngine,
                new DefaultEndpointProvider(),
                true,
                registration.ToArray());

            cqrsEngine.StartPublishers();

            return(cqrsEngine);
        }
Ejemplo n.º 19
0
        protected override void Load(ContainerBuilder builder)
        {
            string selfRoute     = "self";
            string commandsRoute = "commands";
            string eventsRoute   = "events";

            MessagePackSerializerFactory.Defaults.FormatterResolver = MessagePack.Resolvers.ContractlessStandardResolver.Instance;
            var rabbitMqSagasSettings = new RabbitMQ.Client.ConnectionFactory {
                Uri = _sagasRabbitMq.CurrentValue.RabbitConnectionString
            };

            builder.Register(context => new AutofacDependencyResolver(context)).As <IDependencyResolver>();

            builder
            .RegisterType <ValidationCommandHandler>()
            .SingleInstance();

            builder.Register(ctx =>
            {
                var logFactory = ctx.Resolve <ILogFactory>();

                return(new MessagingEngine(
                           logFactory,
                           new TransportResolver(new Dictionary <string, TransportInfo>
                {
                    {
                        "RabbitMq",
                        new TransportInfo(rabbitMqSagasSettings.Endpoint.ToString(),
                                          rabbitMqSagasSettings.UserName, rabbitMqSagasSettings.Password, "None", "RabbitMq")
                    }
                }),
                           new RabbitMqTransportFactory(logFactory)));
            })
            .As <IMessagingEngine>()
            .SingleInstance();

            builder.Register(ctx =>
            {
                var logFactory = ctx.Resolve <ILogFactory>();

                var engine = new CqrsEngine(logFactory,
                                            ctx.Resolve <IDependencyResolver>(),
                                            ctx.Resolve <IMessagingEngine>(),
                                            new DefaultEndpointProvider(),
                                            true,
                                            Register.DefaultEndpointResolver(new RabbitMqConventionEndpointResolver(
                                                                                 "RabbitMq",
                                                                                 SerializationFormat.MessagePack,
                                                                                 environment: "lykke",
                                                                                 exclusiveQueuePostfix: "k8s")),
                                            Register.BoundedContext(ConfirmationCodesBoundedContext.Name)
                                            .ListeningCommands(typeof(ValidateConfirmationCommand))
                                            .On(commandsRoute)
                                            .WithCommandsHandler <ValidationCommandHandler>()
                                            .PublishingEvents(
                                                typeof(ConfirmationValidationPassedEvent),
                                                typeof(ConfirmationValidationFailedEvent))
                                            .With(eventsRoute)
                                            );
                engine.StartPublishers();
                return(engine);
            })
            .As <ICqrsEngine>()
            .SingleInstance()
            .AutoActivate();
        }
Ejemplo n.º 20
0
        protected override void Load(ContainerBuilder builder)
        {
            MessagePackSerializerFactory.Defaults.FormatterResolver = MessagePack.Resolvers.ContractlessStandardResolver.Instance;
            var rabbitMqSettings = new RabbitMQ.Client.ConnectionFactory {
                Uri = _settings.CurrentValue.TierService.Cqrs.RabbitConnectionString
            };

            builder.Register(context => new AutofacDependencyResolver(context)).As <IDependencyResolver>();

            builder.Register(ctx => new MessagingEngine(ctx.Resolve <ILogFactory>(),
                                                        new TransportResolver(new Dictionary <string, TransportInfo>
            {
                {
                    "Transports",
                    new TransportInfo(rabbitMqSettings.Endpoint.ToString(), rabbitMqSettings.UserName,
                                      rabbitMqSettings.Password, "None", "RabbitMq")
                }
            }),
                                                        new RabbitMqTransportFactory(ctx.Resolve <ILogFactory>()))).As <IMessagingEngine>().SingleInstance();

            builder.RegisterType <ClientDepositsSaga>();
            builder.RegisterType <TierUpgradeRequestSaga>();
            builder.RegisterType <KycStatusChangedProjection>();
            builder.RegisterType <DepositOperationRemovedProjection>();

            const string environment   = "lykke";
            const string queuePostfix  = "k8s";
            const string commandsRoute = "commands";
            const string eventsRoute   = "events";
            const string selfRoute     = "self";

            builder.Register(ctx =>
            {
                var engine = new CqrsEngine(ctx.Resolve <ILogFactory>(),
                                            ctx.Resolve <IDependencyResolver>(),
                                            ctx.Resolve <IMessagingEngine>(),
                                            new DefaultEndpointProvider(),
                                            true,
                                            Register.DefaultEndpointResolver(new RabbitMqConventionEndpointResolver(
                                                                                 "Transports",
                                                                                 SerializationFormat.MessagePack,
                                                                                 environment: environment,
                                                                                 exclusiveQueuePostfix: queuePostfix)),

                                            Register.EventInterceptors(new DefaultEventLoggingInterceptor(ctx.Resolve <ILogFactory>())),

                                            Register.BoundedContext(TierBoundedContext.Name)
                                            .PublishingEvents(
                                                typeof(TierUpgradeRequestChangedEvent),
                                                typeof(ClientDepositedEvent)
                                                )
                                            .With(selfRoute)

                                            .ListeningEvents(typeof(KycStatusChangedEvent))
                                            .From(KycBoundedContext.Name).On(eventsRoute)
                                            .WithProjection(typeof(KycStatusChangedProjection), KycBoundedContext.Name)

                                            .ListeningEvents(typeof(ClientOperationRemovedEvent))
                                            .From(LimitationsBoundedContext.Name).On(eventsRoute)
                                            .WithProjection(typeof(DepositOperationRemovedProjection), LimitationsBoundedContext.Name),

                                            Register.Saga <TierUpgradeRequestSaga>("upgrade-request-saga")
                                            .ListeningEvents(typeof(TierUpgradeRequestChangedEvent))
                                            .From(TierBoundedContext.Name).On(selfRoute)
                                            .PublishingCommands(typeof(TextNotificationCommand)).To(PushNotificationsBoundedContext.Name)
                                            .With(commandsRoute)
                                            .ProcessingOptions(commandsRoute).MultiThreaded(2).QueueCapacity(256),

                                            Register.Saga <ClientDepositsSaga>("client-deposits-saga")
                                            .ListeningEvents(typeof(ClientDepositedEvent))
                                            .From(TierBoundedContext.Name).On(selfRoute)
                                            .PublishingCommands(typeof(TextNotificationCommand)).To(PushNotificationsBoundedContext.Name)
                                            .With(commandsRoute)
                                            .ProcessingOptions(commandsRoute).MultiThreaded(2).QueueCapacity(256)
                                            );

                engine.StartPublishers();

                return(engine);
            })
            .As <ICqrsEngine>()
            .SingleInstance()
            .AutoActivate();
        }
        protected override void Load(ContainerBuilder builder)
        {
            builder.Register(context => new AutofacDependencyResolver(context)).As <IDependencyResolver>().SingleInstance();

            var rabbitMqSettings = new RabbitMQ.Client.ConnectionFactory
            {
                Uri = new Uri(_settings.RabbitConnString)
            };
            var rabbitMqEndpoint = rabbitMqSettings.Endpoint.ToString();

            builder.Register(ctx =>
            {
                var logFactory = ctx.Resolve <ILogFactory>();
                return(new MessagingEngine(
                           logFactory,
                           new TransportResolver(new Dictionary <string, TransportInfo>
                {
                    {
                        "RabbitMq",
                        new TransportInfo(
                            rabbitMqEndpoint,
                            rabbitMqSettings.UserName,
                            rabbitMqSettings.Password, "None", "RabbitMq")
                    }
                }),
                           new RabbitMqTransportFactory(logFactory)));
            });

            builder.Register(ctx =>
            {
                const string defaultRoute = "self";

                var logFactory = ctx.Resolve <ILogFactory>();

                var cqrsEngine = new CqrsEngine(
                    logFactory,
                    ctx.Resolve <IDependencyResolver>(),
                    ctx.Resolve <MessagingEngine>(),
                    new DefaultEndpointProvider(),
                    true,
                    Register.DefaultEndpointResolver(new RabbitMqConventionEndpointResolver(
                                                         "RabbitMq",
                                                         Messaging.Serialization.SerializationFormat.ProtoBuf,
                                                         environment: "lykke")),

                    Register.CommandInterceptors(new DefaultCommandLoggingInterceptor(logFactory)),
                    Register.EventInterceptors(new DefaultEventLoggingInterceptor(logFactory)),

                    Register.BoundedContext(BoundedContext.Name)
                    .PublishingEvents(
                        typeof(FeeChargedEvent),
                        typeof(CashInProcessedEvent),
                        typeof(CashOutProcessedEvent),
                        typeof(CashTransferProcessedEvent),
                        typeof(ExecutionProcessedEvent),
                        typeof(ManualOrderTradeProcessedEvent),
                        typeof(OrderPlacedEvent),
                        typeof(OrderCancelledEvent))
                    .With(defaultRoute),

                    Register.DefaultRouting);

                cqrsEngine.StartPublishers();
                return(cqrsEngine);
            })
            .As <ICqrsEngine>()
            .AutoActivate()
            .SingleInstance();
        }
Ejemplo n.º 22
0
        protected override void Load(ContainerBuilder builder)
        {
            if (_settings.ChaosKitty != null)
            {
                builder
                .RegisterType <ChaosKitty>()
                .WithParameter(TypedParameter.From(_settings.ChaosKitty.StateOfChaos))
                .As <IChaosKitty>()
                .SingleInstance();
            }
            else
            {
                builder
                .RegisterType <SilentChaosKitty>()
                .As <IChaosKitty>()
                .SingleInstance();
            }

            MessagePackSerializerFactory.Defaults.FormatterResolver = MessagePack.Resolvers.ContractlessStandardResolver.Instance;

            builder.Register(context => new AutofacDependencyResolver(context)).As <IDependencyResolver>().SingleInstance();

            var rabbitMqSettings = new RabbitMQ.Client.ConnectionFactory {
                Uri = _settings.CqrsRabbitConnString
            };

            builder.RegisterType <ApiKeyProjection>()
            .WithParameter(
                new ResolvedParameter(
                    (pi, ctx) => pi.ParameterType == typeof(IDistributedCache),
                    (pi, ctx) => ctx.ResolveKeyed <IDistributedCache>(_settings.Cache.ApiKeyCacheInstance)));

            builder.Register(ctx =>
            {
                var logFactory      = ctx.Resolve <ILogFactory>();
                var broker          = rabbitMqSettings.Endpoint.ToString();
                var messagingEngine = new MessagingEngine(logFactory,
                                                          new TransportResolver(new Dictionary <string, TransportInfo>
                {
                    { "RabbitMq", new TransportInfo(broker, rabbitMqSettings.UserName, rabbitMqSettings.Password, "None", "RabbitMq") }
                }),
                                                          new RabbitMqTransportFactory(logFactory));

                const string defaultRoute = "self";

                var cqrsEngine = new CqrsEngine(logFactory,
                                                ctx.Resolve <IDependencyResolver>(),
                                                messagingEngine,
                                                new DefaultEndpointProvider(),
                                                true,
                                                Register.DefaultEndpointResolver(new RabbitMqConventionEndpointResolver(
                                                                                     "RabbitMq",
                                                                                     SerializationFormat.MessagePack,
                                                                                     environment: "lykke",
                                                                                     exclusiveQueuePostfix: _settings.QueuePostfix)),

                                                Register.EventInterceptors(new DefaultEventLoggingInterceptor(ctx.Resolve <ILogFactory>())),

                                                Register.BoundedContext("hft-api")
                                                .ListeningEvents(
                                                    typeof(ApiKeyUpdatedEvent))
                                                .From("api-key").On(defaultRoute)
                                                .WithProjection(typeof(ApiKeyProjection), "api-key")
                                                .WithAssetsReadModel(route: System.Environment.MachineName)
                                                );

                cqrsEngine.StartPublishers();
                return(cqrsEngine);
            })
            .As <ICqrsEngine>()
            .AutoActivate()
            .SingleInstance();
        }
Ejemplo n.º 23
0
        protected override void Load(ContainerBuilder builder)
        {
            Messaging.Serialization.MessagePackSerializerFactory.Defaults.FormatterResolver = MessagePack.Resolvers.ContractlessStandardResolver.Instance;
            var rabbitMqSettings = new RabbitMQ.Client.ConnectionFactory
            {
                Uri = _settings.CurrentValue.SagasRabbitMqSettings.ConnectionString
            };

            builder.Register(context => new AutofacDependencyResolver(context)).As <IDependencyResolver>().SingleInstance();

            builder.Register(c =>
                             new MessagingEngine(_log,
                                                 new TransportResolver(new Dictionary <string, TransportInfo>
            {
                { "RabbitMq", new TransportInfo(rabbitMqSettings.Endpoint.ToString(), rabbitMqSettings.UserName, rabbitMqSettings.Password, "None", "RabbitMq") }
            }),
                                                 new RabbitMqTransportFactory()))
            .As <IMessagingEngine>();

            builder.RegisterType <ConfirmationCommandHandler>();

            builder.RegisterType <AssetsProjection>();
            builder.RegisterType <HistoryExportProjection>();
            builder.RegisterType <OperationsProjection>();
            builder.RegisterType <MarketDataProjection>()
            .WithParameter(TypedParameter.From(_settings.CurrentValue.CacheSettings.MarketDataCacheInterval));

            var protobufEndpointResolver = new RabbitMqConventionEndpointResolver(
                "RabbitMq",
                SerializationFormat.ProtoBuf,
                environment: "lykke",
                exclusiveQueuePostfix: _env);

            builder.Register(ctx =>
            {
                const string defaultRoute = "self";

                var engine = new CqrsEngine(
                    _log,
                    ctx.Resolve <IDependencyResolver>(),
                    ctx.Resolve <IMessagingEngine>(),
                    new DefaultEndpointProvider(),
                    true,
                    Register.DefaultEndpointResolver(new RabbitMqConventionEndpointResolver(
                                                         "RabbitMq",
                                                         SerializationFormat.MessagePack,
                                                         environment: "lykke",
                                                         exclusiveQueuePostfix: _env)),

                    Register.BoundedContext(WampHostBoundedContext.Name)
                    .ListeningEvents(
                        typeof(AssetCreatedEvent),
                        typeof(AssetUpdatedEvent),
                        typeof(AssetPairCreatedEvent),
                        typeof(AssetPairUpdatedEvent))
                    .From(BoundedContexts.Assets).On(defaultRoute)
                    .WithProjection(typeof(AssetsProjection), BoundedContexts.Assets)
                    .ListeningEvents(
                        typeof(ClientHistoryExportedEvent))
                    .From(HistoryExportBuilderBoundedContext.Name).On(defaultRoute)
                    .WithProjection(typeof(HistoryExportProjection), HistoryExportBuilderBoundedContext.Name)
                    .ListeningEvents(typeof(OperationFailedEvent), typeof(OperationConfirmedEvent), typeof(OperationCompletedEvent), typeof(OperationCorruptedEvent))
                    .From(OperationsBoundedContext.Name).On(defaultRoute)
                    .WithProjection(typeof(OperationsProjection), OperationsBoundedContext.Name)
                    .ListeningEvents(typeof(MarketDataChangedEvent))
                    .From(MarketDataBoundedContext.Name).On(defaultRoute)
                    .WithProjection(typeof(MarketDataProjection), MarketDataBoundedContext.Name)
                    .ListeningCommands(typeof(RequestConfirmationCommand)).On("commands")
                    .WithEndpointResolver(protobufEndpointResolver)
                    .WithCommandsHandler <ConfirmationCommandHandler>()
                    );
                engine.StartPublishers();
                return(engine);
            })
            .As <ICqrsEngine>()
            .SingleInstance()
            .AutoActivate();
        }