Example #1
0
        private void SendHttpFailed <T>(IAppEvent <T> appEvent, Dictionary <string, object> values) where T : Event
        {
            var requestStatus =
                RequestStatus.CreateFromCommandContext(appEvent.CommandBase.CommandContext, Status.FAILED, values);

            _httpQueuedCommandStatusStorage.UpdateCommandStatus(requestStatus, appEvent.CommandBase);
        }
Example #2
0
        public override void Consume(IAppEvent <AuctionRaised> message)
        {
            AuctionRaised ev = message.Event;

            using (var session = _dbContext.Client.StartSession())
            {
                var opt = new TransactionOptions(
                    writeConcern: new WriteConcern(mode: "majority", journal: true)
                    );

                try
                {
                    _ = session.WithTransaction((handle, token) =>
                    {
                        UpdateAuction(ev, handle);
                        UpdateUser(ev, handle);
                        return(0);
                    }, transactionOptions: opt);
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "Cannot update read collections, appEvent: {@appEvent}", message);
                    _requestStatusService.TrySendRequestFailureToUser(message, ev.Bid.UserIdentity);
                    throw;
                }

                _requestStatusService.TrySendReqestCompletionToUser(message, ev.Bid.UserIdentity);
            }
        }
        public override void Consume(IAppEvent <AuctionImageAdded> appEvent)
        {
            AddImg(appEvent.Event);


            _requestStatusService.TrySendReqestCompletionToUser(appEvent, appEvent.Event.AuctionOwner);
        }
 public override void Consume(IAppEvent <TestEvent> appEvent)
 {
     OnConsume?.Invoke(appEvent);
     if (Throws)
     {
         throw new Exception();
     }
 }
 public virtual void Rollback(IAppEvent <Event> commandEvent)
 {
     OnRollback?.Invoke(commandEvent);
     if (Throws)
     {
         throw new Exception();
     }
 }
Example #6
0
        public void SendRequestCompletionToAll <T>(IAppEvent <T> appEvent, Dictionary <string, object> values = null) where T : Event
        {
            if (appEvent.CommandBase.HttpQueued)
            {
                throw new QueryException("Cannot send request status to all of http queued command");
            }

            _wsRequestStatusService.SendRequestCompletionToAll(appEvent, values);
        }
Example #7
0
        void IEventConsumer.Dispatch(object message)
        {
            IAppEvent <Event> appEventBase = (IAppEvent <Event>)message;

            this.Consume(_appEventBuilder
                         .WithCorrelationId(appEventBase.CorrelationId)
                         .WithEvent(appEventBase.Event)
                         .WithCommand(appEventBase.CommandBase)
                         .Build <T>());
        }
 public void TrySendRequestFailureToUser <T>(IAppEvent <T> appEvent, UserIdentity user, Dictionary <string, object> values = null) where T : Event
 {
     try
     {
         SendRequestFailureToUser(appEvent, user, values);
     }
     catch (Exception)
     {
         _logger.LogDebug($"Cannot send event completion to user {user.UserName}");
     }
 }
 private void _TimerEvnetHandler(IAppEvent e)
 {
     if (e.type == TimerEvent.TIMER_COMPLETE && this._isRequesting && this._www != null && this._request != null)
     {
         this._timeOutTimer.Reset();
         this._behaviour.StopAllCoroutines();
         this._www.Dispose();
         ResultVO requestVO = this._request.data as ResultVO;
         this.Result(new ResultVO(requestVO.id, requestVO.service, ErrorCode.TIME_OUT, null, requestVO.uniqueID));
     }
 }
        public void Rollback(IAppEvent <Event> commandEvent)
        {
            var ev = (CreditsAdded)commandEvent.Event;

            _logger.LogWarning("Canceling buyCredits command for user {@user}", ev.UserIdentity);

            var user = _userRepository.FindUser(ev.UserIdentity);

            user.CancelCredits(ev.CreditsCount);
            _userRepository.UpdateUser(user);
        }
Example #11
0
 public void SendRequestFailureToUser <T>(IAppEvent <T> appEvent, UserIdentity user, Dictionary <string, object> values = null) where T : Event
 {
     if (appEvent.CommandBase.HttpQueued)
     {
         SendHttpFailed(appEvent, values);
     }
     else
     {
         _wsRequestStatusService.SendRequestFailureToUser(appEvent, user, values);
     }
 }
Example #12
0
 private void TrySendHttpFailed <T>(IAppEvent <T> appEvent, Dictionary <string, object> values)
     where T : Event
 {
     try
     {
         SendHttpFailed(appEvent, values);
     }
     catch (Exception)
     {
     }
 }
Example #13
0
 private void TryExecuteCommandRollback(ICommandRollbackHandler handler, IAppEvent <Event> commandEvent)
 {
     //TODO Command rollback request status msg
     try
     {
         handler.Rollback(commandEvent);
     }
     catch (Exception e)
     {
         _logger.LogError(e, "Catched exception in command rollback handler. Command: {@command}", commandEvent);
     }
 }
Example #14
0
 public virtual void Rollback(IAppEvent <Event> commandEvent)
 {
     try
     {
         var cmd = (CreateAuctionCommand)commandEvent.CommandBase;
         var ev  = (AuctionCreated)commandEvent.Event;
         _auctionRepository.RemoveAuction(ev.AuctionId);
     }
     catch (Exception)
     {
         throw;
     }
 }
Example #15
0
        private static IEnumerable <IAppEvent> GetHandler(AppEventType eventType)
        {
            Type             interfaceType = typeof(IAppEvent);
            List <IAppEvent> result        = new List <IAppEvent>();

            foreach (var item in Assembly.GetExecutingAssembly().GetTypes().Where(t => interfaceType.IsAssignableFrom(t) && !t.IsInterface))
            {
                IAppEvent handler = (IAppEvent)Activator.CreateInstance(item);
                result.Add(handler);
            }

            return(result.Where(i => i.EvenType == eventType));
        }
        public void Rollback(IAppEvent <Event> commandEvent)
        {
            var ev      = (AuctionRaised)commandEvent.Event;
            var auction = _auctionRepository.FindAuction(ev.Bid.AuctionId);

            if (auction != null)
            {
                auction.RemoveBid(ev.Bid);
            }
            else
            {
                _logger.LogDebug("Bid rollback handler error, commandEvent: {@commandEvent}", commandEvent);
                throw new CommandException($"Cannot find auction with id: {ev.Bid.AuctionId}");
            }
            _auctionRepository.UpdateAuction(auction);
        }
        public override void Consume(IAppEvent <BidCanceled> appEvent)
        {
            var session = _dbContext.Client.StartSession();

            session.StartTransaction();
            try
            {
                UpdateAuction(session, appEvent.Event);
                UpdateUser(session, appEvent.Event);
                session.CommitTransaction();
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Cannot cancel bid, appEvent: {@appEvent}", appEvent);
                throw;
            }
        }
Example #18
0
        public override void Consume(IAppEvent <UserRegistered> message)
        {
            UserRegistered ev = message.Event;

            var userReadModel = new UserRead();

            userReadModel.UserIdentity = new UserIdentityRead(ev.UserIdentity);

            try
            {
                _dbContext.UsersReadModel.InsertOne(userReadModel);
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #19
0
        public override void Consume(IAppEvent <AuctionCompleted> message)
        {
            AuctionCompleted ev = message.Event;

            using (var session = _dbContext.Client.StartSession())
            {
                var opt = new TransactionOptions(
                    writeConcern: new WriteConcern(mode: "majority", journal: true)
                    );

                _ = session.WithTransaction((handle, token) =>
                {
                    UpdateAuction(handle, ev);
                    UserBidsUpdate(handle, ev);
                    return(0);
                }, opt);
            }
        }
Example #20
0
 private void HandleErrorMessage(IMessage <Error> message, MessageReceivedInfo info)
 {
     try
     {
         _logger.LogWarning("Handling error message: {@message} with routingKey: {routingKey}", message, info.RoutingKey);
         IAppEvent <Event> commandEvent = ParseEventFromMessage(message);
         if (commandEvent != null)
         {
             var commandName = commandEvent.CommandBase?.GetType()
                               .Name;
             var handler = RollbackHandlerRegistry.GetCommandRollbackHandler(commandName);
             TryExecuteCommandRollback(handler, commandEvent);
         }
         else
         {
             _logger.LogError("Parsed command event is null! RoutingKey: {routingKey}", info.RoutingKey);
         }
     }
     catch (Exception)
     {
         _logger.LogError("Cannot handle error message");
     }
 }
Example #21
0
        public override void Consume(IAppEvent <AuctionUpdateEventGroup> appEvent)
        {
            var filter = Builders <AuctionRead> .Filter.Eq(f => f.AuctionId, appEvent.Event.AggregateId.ToString());

            var updates = new List <UpdateDefinition <AuctionRead> >();

            appEvent.Event.UpdateEvents.ForEach(ev =>
                                                updates.Add((UpdateDefinition <AuctionRead>) this.AsDynamic().UpdateAuction(appEvent.Event, ev)));

            var update = Builders <AuctionRead> .Update.Combine(updates);

            try
            {
                _dbContext.AuctionsReadModel.UpdateMany(filter, update);
                _requestStatusService.TrySendReqestCompletionToUser(appEvent, appEvent.Event.AuctionOwner);
            }
            catch (Exception)
            {
                _logger.LogError("Cannot add image to read model");
                _requestStatusService.TrySendRequestFailureToUser(appEvent, appEvent.Event.AuctionOwner);
                throw;
            }
        }
        public override void Consume(IAppEvent <AuctionBought> appEvent)
        {
            var ev = appEvent.Event;

            using (var session = _readModelDbContext.Client.StartSession())
            {
                try
                {
                    _ = session.WithTransaction((handle, token) =>
                    {
                        UpdateAuction(handle, ev);
                        UpdateBids(handle, ev);
                        return(0);
                    });
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "Cannot update read collections, appEvent: {@appEvent}", appEvent);
                    _requestStatusService.TrySendRequestFailureToUser(appEvent, ev.UserIdentity);
                    throw;
                }
                _requestStatusService.TrySendReqestCompletionToUser(appEvent, ev.UserIdentity);
            }
        }
Example #23
0
        public static UserRead AddCredits <T>(ReadModelDbContext dbContext, IAppEvent <T> appEvent,
                                              decimal creditsCount, UserIdentity user,
                                              IRequestStatusService requestStatusService) where T : Event
        {
            var filter = Builders <UserRead> .Filter.Eq(read => read.UserIdentity.UserId,
                                                        user.UserId.ToString());

            var update = Builders <UserRead> .Update.Inc(read => read.Credits, creditsCount);

            var userRead = dbContext.UsersReadModel.FindOneAndUpdate(filter, update);

            if (userRead == null)
            {
                requestStatusService.TrySendRequestFailureToUser(appEvent, user);
                throw new QueryException("Null userReadModel");
            }

            requestStatusService.TrySendReqestCompletionToUser(appEvent, user,
                                                               new Dictionary <string, object>()
            {
                { "ammount", creditsCount }
            });
            return(userRead);
        }
Example #24
0
        public override void Consume(IAppEvent <AuctionCreated> message)
        {
            var ev      = message.Event;
            var mapper  = MapperConfigHolder.Configuration.CreateMapper();
            var auction = mapper.Map <AuctionCreated, AuctionRead>(ev,
                                                                   opt => opt.AfterMap((created, read) => mapper.Map(created.AuctionArgs, read)));

            auction.DateCreated = DateTime.UtcNow;


            try
            {
                _dbContext.AuctionsReadModel.WithWriteConcern(new WriteConcern(mode: "majority", journal: true))
                .InsertOne(auction);
            }
            catch (Exception e)
            {
                _logger.LogWarning(e, "Cannot create an auction");
                _requestStatusService.TrySendRequestFailureToUser(message, ev.AuctionArgs.Creator);
                throw;
            }

            _requestStatusService.TrySendReqestCompletionToUser(message, ev.AuctionArgs.Creator);
        }
        public void METHOD()
        {
            var services = TestDepedencies.Instance.Value;
            var user     = new User();

            user.Register("testUserName");
            user.MarkPendingEventsAsHandled();
            var product       = new Product("test product name", "example description", Condition.New);
            var sem           = new SemaphoreSlim(0, 1);
            var sem2          = new SemaphoreSlim(0, 1);
            var correlationId = new CorrelationId("test_correlationId");
            var categories    = new List <string>()
            {
                "Fake category", "Fake subcategory", "Fake subsubcategory 0"
            };

            var userRepository = new Mock <IUserRepository>();

            userRepository.Setup(f => f.FindUser(It.IsAny <UserIdentity>()))
            .Returns(user);

            var command = new CreateAuctionCommand(20.0m, product, DateTime.UtcNow.AddMinutes(10),
                                                   DateTime.UtcNow.AddDays(12),
                                                   categories, Tag.From(new[] { "tag1" }), "test auction name", false);

            command.SignedInUser = user.UserIdentity;

            IAppEvent <AuctionCreated> publishedEvent = null;


            var eventHandler = new Mock <TestAuctionCreatedHandler>(
                services.AppEventBuilder,
                services.DbContext,
                Mock.Of <IRequestStatusService>()
                );

            eventHandler.CallBase = true;
            eventHandler
            .Setup(f => f.Consume(It.IsAny <IAppEvent <AuctionCreated> >())
                   )
            .Callback((IAppEvent <AuctionCreated> ev) =>
            {
                publishedEvent = ev;
                sem.Release();
            })
            .CallBase();
            services.SetupEventBus(eventHandler.Object);

            var implProv = new Mock <IImplProvider>();

            implProv
            .Setup(f => f.Get <IAuctionRepository>())
            .Returns(services.AuctionRepository);
            RollbackHandlerRegistry.ImplProvider = implProv.Object;
            var testRollbackHandler = new Mock <TestCreateAuctionRollbackHandler>(implProv.Object);

            testRollbackHandler.CallBase = true;
            testRollbackHandler
            .Setup(f => f.Rollback(It.IsAny <IAppEvent <Event> >()))
            .CallBase();
            testRollbackHandler.Object.AfterAction = () => { sem2.Release(); };


            var session = user.UserIdentity.GetAuctionCreateSession();

            command.AuctionCreateSession = session;

            var handlerDepedencies = new CreateAuctionCommandHandlerDepedencies()
            {
                auctionRepository       = services.AuctionRepository,
                auctionSchedulerService = services.SchedulerService,
                eventBusService         = services.EventBus,
                logger = Mock.Of <ILogger <CreateAuctionCommandHandler> >(),
                auctionCreateSessionService = services.GetAuctionCreateSessionService(session),
                auctionImageRepository      = services.AuctionImageRepository,
                categoryBuilder             = new CategoryBuilder(services.CategoryTreeService),
                userRepository = userRepository.Object
            };
            var commandHandler = new TestCreateAuctionCommandHandler(handlerDepedencies, testRollbackHandler.Object);

            commandHandler.Handle(command, CancellationToken.None);
            if (!sem.Wait(TimeSpan.FromSeconds(60)))
            {
                Assert.Fail();
            }
            ;


            var createdAuciton = services.AuctionRepository.FindAuction(publishedEvent.Event.AuctionId);

            if (!sem2.Wait(TimeSpan.FromSeconds(60)))
            {
                Assert.Fail();
            }
            ;
            var auctionAfterRollback = services.AuctionRepository.FindAuction(publishedEvent.Event.AuctionId);

            testRollbackHandler.Verify(f => f.Rollback(It.IsAny <IAppEvent <Event> >()), Times.Once());
            createdAuciton.Should()
            .NotBe(null);
            auctionAfterRollback.Should()
            .Be(null);
        }
 public override void Consume(IAppEvent <AuctionCreated> message)
 {
     throw new Exception();
 }
 public override void Rollback(IAppEvent <Event> commandEvent)
 {
     base.Rollback(commandEvent);
     AfterAction?.Invoke();
 }
 private bool CheckRollbackAppEvent(IAppEvent <Event> ev)
 {
     return(ev.CommandBase.GetType()
            .Equals(typeof(TestCommandBase)) && ev.CorrelationId.Value.Equals("123") && ev.Event.GetType()
            .Equals(typeof(TestEvent)));
 }
Example #29
0
 public void AddListener(IAppEvent listener)
 {
     listeners.Add(listener);
 }
 public void Rollback(IAppEvent <Event> commandEvent)
 {
     _logger.LogDebug("Default command rollback handler for commandEvent: {commandEvent}", commandEvent);
 }