예제 #1
0
        protected void Given(List <EventInStream> events, ITurnEventsIntoCommand worker)
        {
            _worker = worker;
            _worker.SubscribeTo(_eventStore);

            var eventInStreams = events.ToList();

            foreach (var @event in eventInStreams)
            {
                var streamEvent = ToStreamEvent(@event);
                _eventStore.Append(streamEvent);
            }
        }
        public void first_test()
        {
            _eventStore.Append(new List <IDomainEvent> {
                Customer1Created, Customer1AddressChanged
            });
            _eventStore.Append(new List <IDomainEvent> {
                Customer2Created, Customer2AddressChanged
            });

            var allEvents = _eventStore.LoadAll().ToList();

            allEvents.Should().BeEquivalentTo(Customer1Created, Customer1AddressChanged, Customer2Created, Customer2AddressChanged);
        }
        protected void Given(IEnumerable <EventInStream> events, T readModel)
        {
            _readModel = readModel;
            _readModel.SubscribeTo(_eventStore);

            var eventInStreams = events.ToList();

            foreach (var @event in eventInStreams)
            {
                var streamEvent = ToStreamEvent(@event);
                _eventStore.Append(streamEvent);
            }
        }
예제 #4
0
        public async Task Execute(string[] args)
        {
            // run to establish an initial connection.
            await Task.Run(() =>
            {
                var id           = Guid.NewGuid();
                var pendingEvent = _factory.Create(new ShoppingCart(id), new ShoppingCartCreated(Guid.NewGuid()));
                return(_store.Append(id, 0, new[] { pendingEvent }));
            });

            Console.WriteLine("=====================================\n");
            Console.WriteLine("Starting event store throughtput test.\n");

            var stopWatch = new Stopwatch();

            var tasks = new List <Task>();

            var max = 10000;

            Console.WriteLine($"Testing {max} events.\n");
            stopWatch.Start();
            for (var x = 0; x < max; x++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var id           = Guid.NewGuid();
                    var pendingEvent = _factory.Create(new ShoppingCart(id), new ShoppingCartCreated(Guid.NewGuid()));
                    return(_store.Append(id, 0, new[] { pendingEvent }));
                }));
            }

            var masterTask = Task.WhenAll(tasks);

            while (!masterTask.IsCompleted)
            {
                var numberCompleted = tasks.Where(e => e.IsCompleted).Count();
                Console.Write($"\r{numberCompleted}");
            }

            stopWatch.Stop();

            var time = stopWatch.Elapsed;

            Console.WriteLine($" shopping carts took {time.TotalSeconds:#.##} seconds.\n");

            Console.WriteLine($"Throughput: {max / time.TotalSeconds:#.##} per second.\n");
            Console.WriteLine("=====================================\n");
        }
예제 #5
0
        /// <inheritdoc />
        public async Task Execute(IMessage message, ExecutionContext context)
        {
            if (context.IsSuccessful)
            {
                foreach (var instance in context.RaisedEvents.Union(new[] { context.Response as EventMessage }).Where(e => e != null))
                {
                    await _eventStore.Append(instance);

                    await _messageGateway.Publish(instance, context);
                }
            }
        }
예제 #6
0
        public async Task Save(TAggregate aggregate, bool takeSnapshot = false)
        {
            await _eventStore.Append(aggregate.GetId(), aggregate.Version, GetPendingEvents(aggregate));

            aggregate.ClearPendingEvents();

            if (takeSnapshot)
            {
                var snapshot = _snapshotFactory.Create <TAggregate, TState>(aggregate);

                await _snapShotStore.TakeSnapshot(snapshot);
            }
        }
        public void SubscribeTo(IEventStore eventStore)
        {
            string date = DateTime.Today.ToString(DateTimeFormat);

            eventStore.SubscribeToStream($"gameLobby-{date}", @event =>
            {
                var e          = (CreateGameRequestApproved)@event.Event;
                var streamName = $"game-{e.GameId}";

                var createStreamEvent = new CreateStreamEvent(streamName, StreamPositions.CreateNewStream, new GameCreated(e.GameId));
                eventStore.Append(createStreamEvent);
            });
        }
예제 #8
0
        /// <inheritdoc />
        public async Task Execute(ExecutionContext context)
        {
            if (context.IsSuccessful)
            {
                var raisedEvents = context.RaisedEvents.Union(new[] { context.Response as EventMessage }).Where(e => e != null).ToArray();
                foreach (var instance in raisedEvents)
                {
                    await _eventStore.Append(instance).ConfigureAwait(false);

#pragma warning disable 4014
                    _tasks.Add(() => Task.Run(() => _messageGateway.Publish(instance, context)));
#pragma warning restore 4014
                }
            }
        }
예제 #9
0
 public void SubscribeTo(IEventStore eventStore)
 {
     eventStore.SubscribeToStream("et-BasketCheckedOut", streamEvent =>
     {
         var e                   = (BasketCheckedOut)streamEvent.GetOriginatingEvent;
         var orderItems          = e.Items.Select(i => new OrderItem(i)).ToList();
         var ordersCreatedStream = eventStore.ReadStream("et-orderCreated");
         var createOrderPolicy   = new CreateOrderHandler();
         createOrderPolicy.Load(ordersCreatedStream);
         var orderCreated =
             createOrderPolicy.Handle(new CreateOrder(e.CustomerId, e.BasketId, orderItems)) as OrderCreated;
         var @event = new StreamEvent(
             $"order-{orderCreated.Order.OrderId}",
             StreamPositions.CreateNewStream,
             StreamPositions.Any,
             DateTime.Now,
             orderCreated);
         eventStore.Append(@event);
     });
 }
        private void TryPersistEvents(EventStreamContext eventStreamContext, ActionInfo successActionInfo)
        {
            Func <EventStreamContext, bool> tryPersistEventsAction = (context) => {
                try {
                    _eventStore.Append(context.EventStream);
                    return(true);
                }
                catch (Exception ex) {
                    if (ex is ConcurrentException && IsEventStreamCommitted(context.EventStream))
                    {
                        return(true);
                    }

                    var errorMessage = string.Format("{0} raised when persisting events:{1}", ex.GetType().Name, context.EventStream.GetStreamInformation());
                    _logger.Error(errorMessage, ex);

                    if (ex is ConcurrentException)
                    {
                        context.SetConcurrentException(new ErrorInfo {
                            ErrorMessage = errorMessage, Exception = ex
                        });
                        return(true);
                    }

                    return(false);
                }
            };

            if (_retryService.TryAction("TryPersistEvents", () => tryPersistEventsAction(eventStreamContext), 3))
            {
                successActionInfo.Action(successActionInfo.Data);
            }
            else
            {
                _retryService.RetryInQueue(new ActionInfo("TryPersistEvents", (obj) => tryPersistEventsAction(obj as EventStreamContext), eventStreamContext, successActionInfo));
            }
        }
예제 #11
0
        public void _1()
        {
            _eventStore.Append(SingleCustomerQueueCreated.SetAnyVersionAndTimestamp());
            _eventStore.Append(CounterA_Added.SetAnyVersionAndTimestamp());
            _eventStore.Append(Ticket1_Added.SetAnyVersionAndTimestamp());
            _eventStore.Append(CustomerWithTicket1_Taken.SetAnyVersionAndTimestamp());
            _eventStore.Append(CustomerWithTicket1_Served.SetAnyVersionAndTimestamp());
            _eventStore.Append(CustomerWithTicket1_Revoked.SetAnyVersionAndTimestamp());

            var allEvents = _eventStore.LoadAllFor <CustomerQueueSubscription>().ToList();

            ListsAreEquivalent(allEvents,
                               SingleCustomerQueueCreated,
                               CounterA_Added,
                               Ticket1_Added,
                               CustomerWithTicket1_Taken,
                               CustomerWithTicket1_Served,
                               CustomerWithTicket1_Revoked);
        }
 public Task Publish(IDomainEvent evt) => _eventStore.Append(evt);
예제 #13
0
 private void ProcessEventMessage(EventMessage eventMessage)
 {
     eventStore.Append(eventMessage.EventId, eventMessage.Message);
 }
 public override Result Handle(AggregateRootCreated e) => _eventStore
 .Append(e)
 .ToOkResult();
예제 #15
0
 public override Result Handle(RemoteEvent e) => _eventStore.Append(e)
 .ToOkResult();
예제 #16
0
 public static Task Append(this IEventStore eventStore, Guid streamId, CancellationToken cancellationToken, params IEvent[] events)
 {
     return(eventStore.Append(streamId, null, cancellationToken, events));
 }
예제 #17
0
 public void Listen()
 {
     DomainEventPublisher.Instance.Subscribe(domainEvent => _eventStore.Append(domainEvent));
 }
예제 #18
0
        public void AppendEvents(T aggregate)
        {
            var events = aggregate.GetUncommittedEvents();

            _eventStore.Append(GetStreamName(aggregate.Id), events);
        }
예제 #19
0
        /// <summary>
        /// Saves the specified aggregate root.
        /// </summary>
        /// <typeparam name="AR">The type of the aggregate root.</typeparam>
        /// <param name="aggregateRoot">The aggregate root.</param>
        /// <exception cref="Elders.Cronus.DomainModeling.AggregateRootException"></exception>
        public void Save <AR>(AR aggregateRoot) where AR : IAggregateRoot
        {
            if (ReferenceEquals(null, aggregateRoot.UncommittedEvents) || aggregateRoot.UncommittedEvents.Count() == 0)
            {
                return;
            }

            var arCommit = new AggregateCommit(aggregateRoot.State.Id as IBlobId, aggregateRoot.Revision, aggregateRoot.UncommittedEvents.ToList());
            var result   = atomicAction.Execute(aggregateRoot.State.Id, aggregateRoot.Revision, () => eventStore.Append(arCommit));

            if (result.IsSuccessful)
            {
                // #prodalzavameNapred
                // #bravoKobra
                // https://www.youtube.com/watch?v=2wWusHu_3w8
            }
            else
            {
                throw new AggregateStateFirstLevelConcurrencyException("", result.Errors.MakeJustOneException());
            }
        }
예제 #20
0
 internal static void Update(this IEventStore eventStore, IAggregate aggregate)
 {
     eventStore.Append(aggregate.Id, aggregate.DequeuePendingEvents());
 }
예제 #21
0
 public override Result Handle(CustomerQueueEvent e) => _eventStore.Append(e)
 .ToOkResult();
예제 #22
0
        public async Task Handle(TEvent @event, CancellationToken cancellationToken)
        {
            await eventStore.Append(@event.StreamId, cancellationToken, @event);

            await eventStore.SaveChanges(cancellationToken);
        }
예제 #23
0
        public async Task Save(T aggregate)
        {
            await _eventStore.Append(aggregate.Id, aggregate.Version, GetPendingEvents(aggregate));

            aggregate.ClearPendingEvents();
        }
예제 #24
0
        /// <summary>
        /// 保存聚合事件。
        /// </summary>
        public void Save(IEventSourced aggregateRoot, string correlationId = null)
        {
            var events = aggregateRoot.GetEvents();

            if (events.IsEmpty())
            {
                return;
            }

            var    aggregateRootType     = aggregateRoot.GetType();
            int    aggregateRootTypeCode = _typeCodeProvider.GetTypeCode(aggregateRootType);
            string aggregateRootId       = aggregateRoot.Id.ToString();

            if (!_eventStore.IsExist(correlationId))
            {
                var sourcedEvents = events.Select(@event => new EventData()
                {
                    AggregateRootId       = aggregateRootId,
                    AggregateRootTypeCode = aggregateRootTypeCode,
                    Version       = @event.Version,
                    CorrelationId = correlationId,
                    Payload       = _serializer.Serialize(@event)
                }).ToArray();
                _eventStore.Append(sourcedEvents);

                _logger.Info("sourcing events persistent completed. aggregateRootId:{0},aggregateRootType:{1}.",
                             aggregateRootId, aggregateRootType.FullName);

                _cache.Set(aggregateRoot, aggregateRoot.Id);
            }
            else
            {
                events = _eventStore.FindAll(correlationId).Select(Deserialize);
                _logger.Info("the command generates events have been saved, load from storage. command id:{0}", correlationId);
            }

            _eventBus.Publish(new EventStream {
                AggregateRootId       = aggregateRootId,
                AggregateRootTypeCode = aggregateRootTypeCode,
                CommandId             = correlationId,
                StartVersion          = events.Min(item => item.Version),
                EndVersion            = events.Max(item => item.Version),
                Events = events.OfType <IEvent>().ToArray()
            });
            _logger.Info("publish all events. event ids: [{0}]", string.Join(",", events.Select(@event => @event.Id).ToArray()));

            if (_snapshotStore.StorageEnabled)
            {
                var snapshot = new SnapshotData(aggregateRootTypeCode, aggregateRootId)
                {
                    Data    = _serializer.Serialize(aggregateRoot),
                    Version = aggregateRoot.Version
                };

                _snapshotStore.Save(snapshot).ContinueWith(task => {
                    if (task.Status == TaskStatus.Faulted)
                    {
                        _logger.Error(task.Exception, "snapshot persistent failed. aggregateRootId:{0},aggregateRootType:{1},version:{2}.", aggregateRootId, aggregateRootType.FullName, aggregateRoot.Version);
                    }
                });
                //Task.Factory.StartNew(() => {
                //    try {
                //        _snapshotStore.Save(snapshot);
                //    }
                //    catch (Exception ex) {
                //        _logger.Error(ex, "snapshot persistent failed. aggregateRootId:{0},aggregateRootType:{1},version:{2}.", aggregateRootId, aggregateRootType.FullName, aggregateRoot.Version);
                //    }
                //});
            }
        }