Exemplo n.º 1
0
        public void TwoSimpleEventInterceptorsTest()
        {
            var simpleEventInterceptorOne = new EventSimpleInterceptor();
            var simpleEventInterceptorTwo = new EventSimpleInterceptor();

            using (var messagingEngine = new MessagingEngine(
                       _logFactory,
                       new TransportResolver(new Dictionary <string, TransportInfo>
            {
                { "InMemory", new TransportInfo("none", "none", "none", null) }
            })))
            {
                using (var engine = new CqrsEngine(
                           _logFactory,
                           messagingEngine,
                           Register.DefaultEndpointResolver(new InMemoryEndpointResolver()),
                           Register.EventInterceptors(simpleEventInterceptorOne),
                           Register.EventInterceptors(simpleEventInterceptorTwo),
                           Register.Saga <TestSaga>("test2")
                           .ListeningEvents(typeof(string)).From("lykke-wallet").On("lykke-wallet-events")))
                {
                    engine.StartSubscribers();
                    messagingEngine.Send("2", new Endpoint("InMemory", "lykke-wallet-events", serializationFormat: SerializationFormat.Json));
                    Thread.Sleep(1000);

                    Assert.True(simpleEventInterceptorOne.Intercepted);
                    Assert.True(simpleEventInterceptorTwo.Intercepted);
                    Assert.NotNull(simpleEventInterceptorOne.InterceptionTimestamp);
                    Assert.NotNull(simpleEventInterceptorTwo.InterceptionTimestamp);
                    Assert.True(simpleEventInterceptorOne.InterceptionTimestamp < simpleEventInterceptorTwo.InterceptionTimestamp);
                    Assert.True(TestSaga.Messages.Contains("2"));
                }
            }
        }
        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();
        }
Exemplo n.º 3
0
        public void EventLoggingInterceptorDoesNotBreakProcessingChain()
        {
            var eventLoggingInterceptor = new DefaultEventLoggingInterceptor(_logFactory);
            var simpleEventInterceptor  = new EventSimpleInterceptor();

            using (var messagingEngine = new MessagingEngine(
                       _logFactory,
                       new TransportResolver(new Dictionary <string, TransportInfo>
            {
                { "InMemory", new TransportInfo("none", "none", "none", null) }
            })))
            {
                using (var engine = new CqrsEngine(
                           _logFactory,
                           messagingEngine,
                           Register.DefaultEndpointResolver(new InMemoryEndpointResolver()),
                           Register.EventInterceptors(eventLoggingInterceptor, simpleEventInterceptor),
                           Register.Saga <TestSaga>("test1")
                           .ListeningEvents(typeof(string)).From("lykke-wallet").On("lykke-wallet-events")))
                {
                    engine.StartSubscribers();
                    messagingEngine.Send("1", new Endpoint("InMemory", "lykke-wallet-events", serializationFormat: SerializationFormat.Json));
                    Thread.Sleep(1000);

                    Assert.True(simpleEventInterceptor.Intercepted);
                }
            }
        }
Exemplo n.º 4
0
        public void CommandLoggingInterceptorDoesNotBreakProcessingChain()
        {
            var commandLoggingInterceptor = new DefaultCommandLoggingInterceptor(_logFactory);
            var commandSimpleInterceptor  = new CommandSimpleInterceptor();
            var commandsHandler           = new CommandsHandler();

            using (var messagingEngine = new MessagingEngine(
                       _logFactory,
                       new TransportResolver(new Dictionary <string, TransportInfo>
            {
                { "InMemory", new TransportInfo("none", "none", "none", null) }
            })))
            {
                using (var engine = new CqrsEngine(
                           _logFactory,
                           messagingEngine,
                           Register.DefaultEndpointResolver(new InMemoryEndpointResolver()),
                           Register.CommandInterceptors(commandLoggingInterceptor, commandSimpleInterceptor),
                           Register.BoundedContext("test1")
                           .ListeningCommands(typeof(int)).On("lykke-wallet-events")
                           .WithCommandsHandler(commandsHandler)))
                {
                    engine.StartSubscribers();
                    messagingEngine.Send(1, new Endpoint("InMemory", "lykke-wallet-events", serializationFormat: SerializationFormat.Json));
                    Thread.Sleep(1000);

                    Assert.True(commandSimpleInterceptor.Intercepted);
                }
            }
        }
Exemplo n.º 5
0
        public void EventLoggingInterceptorTest()
        {
            int eventLoggedCount = 0;

            var eventLoggingInterceptor = new CustomEventLoggingInterceptor(
                _logFactory,
                new Dictionary <Type, EventLoggingDelegate>
            {
                { typeof(string), (l, h, e) => ++ eventLoggedCount }
            });

            using (var messagingEngine = new MessagingEngine(
                       _logFactory,
                       new TransportResolver(new Dictionary <string, TransportInfo>
            {
                { "InMemory", new TransportInfo("none", "none", "none", null) }
            })))
            {
                using (var engine = new CqrsEngine(
                           _logFactory,
                           messagingEngine,
                           Register.DefaultEndpointResolver(new InMemoryEndpointResolver()),
                           Register.EventInterceptors(eventLoggingInterceptor),
                           Register.Saga <TestSaga>("test1")
                           .ListeningEvents(typeof(string)).From("lykke-wallet").On("lykke-wallet-events")))
                {
                    engine.StartSubscribers();
                    messagingEngine.Send("1", new Endpoint("InMemory", "lykke-wallet-events", serializationFormat: SerializationFormat.Json));
                    Thread.Sleep(1000);

                    Assert.True(eventLoggedCount > 0, "Event was not logged");
                    Assert.True(eventLoggedCount == 1, "Event was logged more than once");
                }
            }
        }
Exemplo n.º 6
0
        public void EventLoggingInterceptorTestForDefaultLogging()
        {
            var eventLoggingInterceptor = new DefaultEventLoggingInterceptor(_logFactory);

            using (var messagingEngine = new MessagingEngine(
                       _logFactory,
                       new TransportResolver(new Dictionary <string, TransportInfo>
            {
                { "InMemory", new TransportInfo("none", "none", "none", null) }
            })))
            {
                using (var engine = new CqrsEngine(
                           _logFactory,
                           messagingEngine,
                           Register.DefaultEndpointResolver(new InMemoryEndpointResolver()),
                           Register.EventInterceptors(eventLoggingInterceptor),
                           Register.Saga <TestSaga>("test1")
                           .ListeningEvents(typeof(string)).From("lykke-wallet").On("lykke-wallet-events")))
                {
                    engine.StartSubscribers();
                    using (var writer = new StringWriter())
                    {
                        var prevOut = Console.Out;
                        Console.SetOut(writer);
                        messagingEngine.Send("1", new Endpoint("InMemory", "lykke-wallet-events", serializationFormat: SerializationFormat.Json));
                        Thread.Sleep(1000);
                        Console.SetOut(prevOut);

                        var output = writer.ToString();
                        Assert.IsFalse(output.IsNullOrEmpty(), "Event was not logged");
                    }
                }
            }
        }
Exemplo n.º 7
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);
        }
Exemplo n.º 8
0
 void IRegistration.Process(CqrsEngine cqrsEngine)
 {
     foreach (var descriptor in m_Descriptors)
     {
         descriptor.Process(m_Subject, cqrsEngine);
     }
 }
Exemplo n.º 9
0
 public override void Process(Context context, CqrsEngine cqrsEngine)
 {
     foreach (var handler in ResolvedDependencies)
     {
         context.CommandDispatcher.Wire(handler, new OptionalParameter <IEventPublisher>(context.EventsPublisher));
     }
 }
Exemplo n.º 10
0
 public void ListenSameCommandOnDifferentEndpointsTest()
 {
     using (var messagingEngine = new MessagingEngine(
                _logFactory,
                new TransportResolver(new Dictionary <string, TransportInfo>
     {
         { "InMemory", new TransportInfo("none", "none", "none", null, "InMemory") }
     })))
     {
         var commandHandler = new CommandHandler();
         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.Start();
             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(6000);
             Assert.That(commandHandler.AcceptedCommands, Is.EquivalentTo(new[] { "test1", "test2" }));
         }
     }
 }
 public override void Process(Context context, CqrsEngine cqrsEngine)
 {
     foreach (var process in ResolvedDependencies)
     {
         context.Processes.Add(((IProcess)process));
     }
 }
Exemplo n.º 12
0
        public void AllThreadsAreStoppedAfterCqrsDisposeTest()
        {
            var initialThreadCount = Process.GetCurrentProcess().Threads.Count;


            Console.WriteLine(initialThreadCount);
            using (
                var messagingEngine =
                    new MessagingEngine(
                        new TransportResolver(new Dictionary <string, TransportInfo>
            {
                { "InMemory", new TransportInfo("none", "none", "none", null, "InMemory") }
            })))
            {
                using (var engine = new CqrsEngine(messagingEngine,
                                                   new InMemoryEndpointResolver(),
                                                   LocalBoundedContext.Named("bc").ConcurrencyLevel(1)
                                                   .PublishingEvents(typeof(int))
                                                   .To("eventExchange")
                                                   .RoutedTo("eventQueue")
                                                   .ListeningCommands(typeof(string))
                                                   .On("exchange1", CommandPriority.Low)
                                                   .On("exchange2", CommandPriority.High)
                                                   .RoutedFrom("commandQueue")

                                                   .WithCommandsHandler(new CommandHandler(100)))
                       )
                {
                    Console.WriteLine(Process.GetCurrentProcess().Threads.Count);
                }
            }
            Assert.That(Process.GetCurrentProcess().Threads.Count, Is.EqualTo(initialThreadCount),
                        "Some threads were not stopped");
        }
Exemplo n.º 13
0
 public void ListenSameCommandOnDifferentEndpointsTest()
 {
     using (
         var messagingEngine =
             new MessagingEngine(
                 new TransportResolver(new Dictionary <string, TransportInfo>
     {
         { "InMemory", new TransportInfo("none", "none", "none", null, "InMemory") }
     })))
     {
         var commandHandler = new CommandHandler();
         using (var engine = new CqrsEngine(messagingEngine,
                                            new InMemoryEndpointResolver(),
                                            LocalBoundedContext.Named("bc")
                                            .PublishingEvents(typeof(int)).To("eventExchange").RoutedTo("eventQueue")
                                            .ListeningCommands(typeof(string)).On("exchange1").On("exchange2").RoutedFrom("commandQueue")
                                            .WithCommandsHandler(commandHandler))
                )
         {
             messagingEngine.Send("test1", new Endpoint("InMemory", "bc.exchange1", serializationFormat: "json"));
             messagingEngine.Send("test2", new Endpoint("InMemory", "bc.exchange2", serializationFormat: "json"));
             messagingEngine.Send("test3", new Endpoint("InMemory", "bc.exchange3", serializationFormat: "json"));
             Thread.Sleep(2000);
             Assert.That(commandHandler.AcceptedCommands, Is.EquivalentTo(new[] { "test1", "test2" }));
         }
     }
 }
Exemplo n.º 14
0
        protected sealed override Context GetSubject(CqrsEngine cqrsEngine)
        {
            var context = CreateContext(cqrsEngine);

            cqrsEngine.Contexts.Add(context);
            return(context);
        }
Exemplo n.º 15
0
        public void TwoSimpleCommandInterceptorsTest()
        {
            var commandSimpleInterceptorOne = new CommandSimpleInterceptor();
            var commandSimpleInterceptorTwo = new CommandSimpleInterceptor();
            var commandsHandler             = new CommandsHandler();

            using (var messagingEngine = new MessagingEngine(
                       _logFactory,
                       new TransportResolver(new Dictionary <string, TransportInfo>
            {
                { "InMemory", new TransportInfo("none", "none", "none", null) }
            })))
            {
                using (var engine = new CqrsEngine(
                           _logFactory,
                           messagingEngine,
                           Register.DefaultEndpointResolver(new InMemoryEndpointResolver()),
                           Register.CommandInterceptors(commandSimpleInterceptorOne, commandSimpleInterceptorTwo),
                           Register.BoundedContext("swift-cashout")
                           .ListeningCommands(typeof(int)).On("lykke-wallet-events")
                           .WithCommandsHandler(commandsHandler)))
                {
                    engine.StartSubscribers();
                    messagingEngine.Send(1, new Endpoint("InMemory", "lykke-wallet-events", serializationFormat: SerializationFormat.Json));
                    Thread.Sleep(1000);

                    Assert.True(commandSimpleInterceptorOne.Intercepted);
                    Assert.True(commandSimpleInterceptorTwo.Intercepted);
                    Assert.NotNull(commandSimpleInterceptorOne.InterceptionTimestamp);
                    Assert.NotNull(commandSimpleInterceptorTwo.InterceptionTimestamp);
                    Assert.True(commandSimpleInterceptorOne.InterceptionTimestamp < commandSimpleInterceptorTwo.InterceptionTimestamp);
                    Assert.True(commandsHandler.HandledCommands.Count > 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(),
                RegisterWithdrawalSaga(),
                RegisterDepositSaga(),
                RegisterClosePositionSaga(),
                RegisterNegativeProtectionSaga(),
                RegisterGiveTemporaryCapitalSaga(),
                RegisterRevokeTemporaryCapitalSaga(),
                RegisterDeleteAccountsSaga(),
                RegisterContext(),
                Register.CommandInterceptors(new DefaultCommandLoggingInterceptor(_log)),
                Register.EventInterceptors(new DefaultEventLoggingInterceptor(_log)));
            var correlationManager = ctx.Resolve <CqrsCorrelationManager>();

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

            return(engine);
        }
Exemplo n.º 17
0
 void IRegistration.Create(CqrsEngine cqrsEngine)
 {
     m_Subject = GetSubject(cqrsEngine);
     foreach (var descriptor in m_Descriptors)
     {
         descriptor.Create(m_Subject, cqrsEngine.DependencyResolver);
     }
 }
Exemplo n.º 18
0
 public void Process(CqrsEngine cqrsEngine)
 {
     foreach (var boundContext in m_BoundContexts)
     {
         var context = cqrsEngine.BoundedContexts.FirstOrDefault(bc => bc.Name == boundContext);
         context.EventDispatcher.Wire(m_Saga, new OptionalParameter <ICommandSender>(cqrsEngine));
     }
 }
Exemplo n.º 19
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();
        }
Exemplo n.º 20
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")
                           .ListeningEvents(typeof(int)).From("operations").On("operationEventsRoute")
                           .ListeningCommands(typeof(string)).On("commandsRoute")
                           //same as .PublishingCommands(typeof(string)).To("bc").With("selfCommandsRoute")
                           .WithLoopback("selfCommandsRoute")
                           .PublishingEvents(typeof(int)).With("eventsRoute")
                           //same as.ListeningEvents(typeof(int)).From("bc").On("selfEventsRoute")
                           .WithLoopback("selfEventsRoute")

                           //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())
                           .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.Start();
                }
            }
        }
Exemplo n.º 21
0
        void IRegistration.Process(CqrsEngine cqrsEngine)
        {
            var boundedContext = cqrsEngine.BoundedContexts.FirstOrDefault(bc => bc.Name == Name);

            foreach (var descriptor in m_Configurators)
            {
                descriptor.Process(boundedContext, cqrsEngine);
            }
        }
Exemplo n.º 22
0
        /// <inheritdoc cref="IRegistration"/>
        public void Create(CqrsEngine cqrsEngine)
        {
            if (m_Resolver == null)
            {
                m_Resolver = cqrsEngine.DependencyResolver.GetService(Dependencies.First()) as IEndpointResolver;
            }

            cqrsEngine.EndpointResolver = m_Resolver;
        }
Exemplo n.º 23
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();
        }
Exemplo n.º 24
0
        public void CqrsEngineTest()
        {
            var serializationManager = new SerializationManager();

            serializationManager.RegisterSerializerFactory(new JsonSerializerFactory());
            var transportResolver =
                new TransportResolver(new Dictionary <string, TransportInfo>
            {
                { "test", new TransportInfo("localhost", "guest", "guest", null, "RabbitMq") }
            });
            var messagingEngine = new MessagingEngine(transportResolver, new RabbitMqTransportFactory());


            using (messagingEngine)
            {
                var cqrsEngine = new CqrsEngine(messagingEngine, new FakeEndpointResolver(),
                                                LocalBoundedContext.Named("integration")
                                                .PublishingEvents(typeof(int)).To("eventExchange").RoutedTo("eventQueue")
                                                .ListeningCommands(typeof(string)).On("commandExchange").RoutedFrom("commandQueue")
                                                .WithCommandsHandler <CommandsHandler>(),
                                                LocalBoundedContext.Named("bc").WithProjection <EventListener>("integration")
                                                );

/*                var cqrsEngine = new CqrsEngine(messagingEngine, new RabbitMqConventionEndpointResolver("test","json",new EndpointResolver(new Dictionary<string, Endpoint>())),
 *                                              LocalBoundedContext.Named("integration")
 *                                                                 .PublishingEvents(typeof (int)).To("events").RoutedToSameEndpoint()
 *                                                                 .ListeningCommands(typeof (string)).On("commands").RoutedFromSameEndpoint()
 *                                                                 .WithCommandsHandler<CommandsHandler>(),
 *                                              LocalBoundedContext.Named("bc").WithProjection<EventListener>("integration")
 *                  );*/
                /* var c=new commandSender(messagingEngine, RemoteBoundedContext.Named("integration")
                 *                                  .ListeningCommands(typeof(TestCommand)).On(new Endpoint())
                 *                                  .PublishingEvents(typeof(TransferCreatedEvent)).To(new Endpoint()),
                 *                                  LocalBoundedContext.Named("testBC")
                 *                                  .ListeningCommands(typeof(TestCommand)).On(new Endpoint("test", "unistream.u1.commands", true))
                 *                                  .ListeningCommands(typeof(int)).On(new Endpoint("test", "unistream.u1.commands", true))
                 *                                  .PublishingEvents(typeof (int)).To(new Endpoint()).RoutedTo(new Endpoint())
                 *                                  .PublishingEvents(typeof (string)).To(new Endpoint())
                 *                                  .WithEventStore(dispatchCommits => Wireup.Init()
                 *                                                                           .LogToOutputWindow()
                 *                                                                           .UsingInMemoryPersistence()
                 *                                                                           .InitializeStorageEngine()
                 *                                                                           .UsingJsonSerialization()
                 *                                                                           .UsingSynchronousDispatchScheduler()
                 *                                                                               .DispatchTo(dispatchCommits))
                 *                              ); */



                //  messagingEngine.Send("test", new Endpoint("test", "unistream.u1.commands", true,"json"));
                cqrsEngine.SendCommand("test", "integration");
                Thread.Sleep(3000);
            }
        }
Exemplo n.º 25
0
 public override void Process(BoundedContext boundedContext, CqrsEngine cqrsEngine)
 {
     foreach (var handler in ResolvedDependencies)
     {
         IRepository repository = boundedContext.EventStore == null?null:boundedContext.EventStore.Repository;
         boundedContext.CommandDispatcher.Wire(handler,
                                               new OptionalParameter <IEventPublisher>(boundedContext.EventsPublisher),
                                               new OptionalParameter <IRepository>(repository)
                                               );
     }
 }
Exemplo n.º 26
0
        void IRegistration.Create(CqrsEngine cqrsEngine)
        {
            var boundedContext = new BoundedContext(cqrsEngine, Name, ThreadCount, FailedCommandRetryDelayInternal, m_IsLocal, m_LocalBoundedContext);

            foreach (var descriptor in m_Configurators)
            {
                descriptor.Create(boundedContext, cqrsEngine.DependencyResolver);
            }

            cqrsEngine.BoundedContexts.Add(boundedContext);
        }
Exemplo n.º 27
0
 internal BoundedContext(CqrsEngine cqrsEngine, string name, int threadCount, long failedCommandRetryDelay, bool isLocal, string localBoundedContext)
 {
     ThreadCount             = threadCount;
     FailedCommandRetryDelay = failedCommandRetryDelay;
     IsLocal             = isLocal;
     LocalBoundedContext = localBoundedContext;
     Name              = name;
     EventsPublisher   = new EventsPublisher(cqrsEngine, this);
     CommandDispatcher = new CommandDispatcher(Name, threadCount, failedCommandRetryDelay);
     EventDispatcher   = new EventDispatcher(Name);
     Processes         = new List <IProcess>();
 }
        public override void Process(Context context, CqrsEngine cqrsEngine)
        {
            EndpointResolver.SetFallbackResolver(cqrsEngine.EndpointResolver);

            var notHandledEventTypes = context.EventDispatcher.GetUnhandledEventTypes(m_BoundedContext, m_Types);

            if (notHandledEventTypes.Count > 0)
            {
                throw new InvalidOperationException(
                          $"Event types ({string.Join(", ", notHandledEventTypes.Select(t => t.Name))}) that are listened from context '{m_BoundedContext}' on route '{Route}' have no handler");
            }
        }
Exemplo n.º 29
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();
        }