public async Task Run()
        {
            foreach (var @event in Given())
            {
                Aggregate ??= (TEventSourcedAggregate)Activator.CreateInstance(typeof(TEventSourcedAggregate), true) !;
                Aggregate.ApplyEvent(@event);
            }

            var services = Testing.GetServices();

            ConfigureServices(services);
            var serviceProvider = services.BuildServiceProvider();
            var mediator        = serviceProvider.GetRequiredService <IMediator>();

            try
            {
                await mediator.Send(When());
            }
            catch (Exception e)
            {
                IsErrorExpected(e).Should().BeTrue();
                return;
            }

            IsErrorExpected().Should().BeFalse();
            Aggregate.Should().NotBeNull();
            Aggregate !.UncommittedEvents.Should().BeEquivalentTo(Then(), options => options.RespectingRuntimeTypes());
        }
示例#2
0
    /// <inheritdoc />
    protected override void Setup(IServiceProvider services)
    {
        _eventStore       = services.GetRequiredService <IEventStore>();
        _executionContext = Runtime.CreateExecutionContextFor(ConfiguredTenants.First());

        var events = new List <UncommittedEvent>();

        for (var n = 0; n < EventsToCommit; n++)
        {
            events.Add(new UncommittedEvent(
                           new EventSourceId("8453f4d4-861a-4042-a4e3-c1abf1c8eadd"),
                           new Artifact(new ArtifactId(Guid.Parse("752f88c9-70f0-4ffe-82b6-a69dcc96672e")), ArtifactGeneration.First),
                           false,
                           "{ \"hello\": \"world\" }"));
        }
        _eventsToCommit = new UncommittedEvents(events);

        if (PreExistingEvents < 1)
        {
            return;
        }

        var preExistingEvents = new List <UncommittedEvent>();

        for (var n = 0; n < PreExistingEvents; n++)
        {
            preExistingEvents.Add(new UncommittedEvent(
                                      new EventSourceId("8453f4d4-861a-4042-a4e3-c1abf1c8eadd"),
                                      new Artifact(new ArtifactId(Guid.Parse("752f88c9-70f0-4ffe-82b6-a69dcc96672e")), ArtifactGeneration.First),
                                      false,
                                      "{ \"hello\": \"world\" }"));
        }

        _eventStore.Commit(new UncommittedEvents(preExistingEvents), _executionContext).GetAwaiter().GetResult();
    }
        public override void Commit()
        {
            int eventCount = UncommittedEvents.Count();

            base.Commit();
            Version += eventCount;
        }
示例#4
0
 void ThrowIfNoEventsToCommit(UncommittedEvents events)
 {
     if (!events.HasEvents)
     {
         throw new NoEventsToCommit();
     }
 }
示例#5
0
        public void Delete(Guid userId)
        {
            var userDeletedEvent = new UserDeletedEvent(userId, Version);

            ApplyEvent(userDeletedEvent, Version + 1);
            UncommittedEvents.Add(userDeletedEvent);
        }
        /// <inheritdoc/>
        public void Commit(CorrelationId correlationId, UncommittedEvents uncommittedEvents)
        {
            _logger.Information($"Committing uncommitted event stream with correlationId '{correlationId}'");
            _logger.Trace("Building the Event Store uncommitted event stream");
            var uncommitted = BuildUncommitted(uncommittedEvents, correlationId.Value);

            _logger.Trace("Committing the events");
            CommittedEventStream committed;

            using (var eventStore = _getEventStore())
            {
                committed = eventStore.Commit(uncommitted);
            }
            try
            {
                _logger.Trace("Process events in same bounded context");
                _eventProcessorHub.Process(committed);
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"Error processing CommittedEventStream within local event processors '{committed?.Sequence?.ToString() ??  "[NULL]"}'");
            }
            try
            {
                _logger.Trace("Passing committed events through event horizon");
                _eventHorizon.PassThrough(new CommittedEventStreamWithContext(committed, _executionContextManager.Current));
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"Error processing CommittedEventStream within event horizons '{committed?.Sequence?.ToString() ??  "[NULL]"}'");
            }
        }
示例#7
0
 public void AddEvent(AccountDomainEvent domainEvent)
 {
     domainEvent.StreamId = Id;
     ApplyEvent(domainEvent);
     UncommittedEvents.Add(domainEvent);
     StreamVersion++;
 }
 public virtual void ApplyChange(IDomainEvent @event, bool isRebuild)
 {
     if (!isRebuild)
     {
         UncommittedEvents.Enqueue(@event);
     }
 }
        public void AddEvent(CardDomainEvent domainEvent)
        {
            ApplyEvent(domainEvent);

            UncommittedEvents.Add(domainEvent);

            Version++;
        }
示例#10
0
        public void VerifyEmailAddress(Guid userId)
        {
            var userVerifiedEvent = new UserVerifiedEvent(
                userId, Version, UserStatus.Verified);

            ApplyEvent(userVerifiedEvent, Version + 1);
            UncommittedEvents.Add(userVerifiedEvent);
        }
示例#11
0
        public void AddEvent(CreditCardDomainEvent domainEvent)
        {
            ApplyEvent(domainEvent);

            UncommittedEvents.Add(domainEvent);

            StreamVersion++;
        }
        VersionedEventSource ToVersionedEventSource(UncommittedEvents uncommittedEvents)
        {
            var commit   = Convert.ToUInt64(uncommittedEvents.EventSource.Version.Commit);
            var sequence = Convert.ToUInt32(uncommittedEvents.EventSource.Version.Sequence);
            var key      = new EventSourceKey(uncommittedEvents.EventSource.EventSourceId, _artifactMap.GetArtifactFor(uncommittedEvents.EventSource.GetType()).Id);

            return(new VersionedEventSource(new EventSourceVersion(commit, sequence), key));
        }
    static async Task commit_events(UncommittedEvents uncommitted_events)
    {
        var response = await event_store.Commit(uncommitted_events, Runtime.CreateExecutionContextFor(tenant)).ConfigureAwait(false);

        var newly_committed_events = response.Events.ToCommittedEvents();
        var all_committed_events   = committed_events.ToList();

        all_committed_events.AddRange(newly_committed_events);
        committed_events = new CommittedEvents(all_committed_events);
    }
示例#14
0
 protected void HandleEvent(Event @event)
 {
     @event.Id       = Guid.NewGuid();
     @event.SourceId = Id;
     @event.Created  = DateTime.UtcNow;
     @event.Version  = Version + 1;
     _handlers[@event.GetType()].Invoke(@event);
     Version = @event.Version;
     UncommittedEvents.Add(@event);
 }
示例#15
0
        IUncommittedEvents IAggregate.TakeUncommittedEvents()
        {
            var uncommittedEvents = new UncommittedEvents(
                _originalVersion,
                new ReadOnlyCollection <IUncommittedEvent>(_uncommittedEvents.ToArray()));

            _uncommittedEvents.Clear();
            _originalVersion = Version;
            return(uncommittedEvents);
        }
        public void AddEvent(AccountDomainEvent domainEvent)
        {
            domainEvent.AggregateRootId = Id;

            ApplyEvent(domainEvent);

            UncommittedEvents.Add(domainEvent);

            Version++;
        }
示例#17
0
        public override void Commit()
        {
            int eventCount = UncommittedEvents.Count();

            base.Commit();

            if (eventCount > 0)
            {
                Version++;
            }
        }
示例#18
0
 void Apply(IEvent @event, bool isNew)
 {
     if (isNew)
     {
         @event.EventSource = EventSourceType.AssemblyQualifiedName;
         UncommittedEvents.Append(@event);
         Version        = Version.NextSequence();
         @event.Version = Version;
     }
     HandleInternally(@event);
 }
示例#19
0
        public void UpdateEmailAddress(Guid userId, string emailAddress)
        {
            if (string.IsNullOrWhiteSpace(emailAddress))
            {
                throw new ArgumentException(nameof(emailAddress));
            }

            var userUpdatedEvent = new UserUpdatedEvent(
                userId, Version, emailAddress, UserStatus.VerificationPending);

            ApplyEvent(userUpdatedEvent, Version + 1);
            UncommittedEvents.Add(userUpdatedEvent);
        }
示例#20
0
        public override bool TryResolveConflicts(IEnumerable <DomainEvent> missingEvents)
        {
            if (UncommittedEvents.Any(IsConflictingEvent))
            {
                return(false);
            }

            if (missingEvents.Any(IsConflictingEvent))
            {
                return(false);
            }

            return(true);
        }
示例#21
0
        public void CommitChanges(Guid commitId)
        {
            if (commits.Contains(commitId))
            {
                throw new DuplicateCommitException();
            }

            persistenceEngine.Commit(streamId.BucketId, streamId.Id, commitId, currentSequence, UncommittedEvents, UncommittedHeaders);

            if (!UncommittedHeaders.ContainsKey(PreventCommitDispatchHeader.Key))
            {
                UncommittedEvents.ForEach(e => eventDispatcher.Dispatch(e.Body));
            }

            PopulateStream();
        }
        /// <inheritdoc/>
        public async Task HandlePostRequest(HttpContext context, IEvent @event)
        {
            var eventSourceQuery = context.Request.Query["EventSource-ID"].ToString();

            if (Guid.TryParse(eventSourceQuery, out var eventSourceId))
            {
                var uncommittedEvents = new UncommittedEvents();
                uncommittedEvents.Append(eventSourceId, @event);
                var committedEvents = await _eventStore.Commit(uncommittedEvents).ConfigureAwait(false);

                await context.RespondWithOk($"Event {@event.GetType()} committed. \nCommittedEvents: {committedEvents}").ConfigureAwait(false);
            }
            else
            {
                await context.RespondWithBadRequest($"A valid GUID is required as the EventSource-ID parameter. Received {eventSourceQuery}").ConfigureAwait(false);
            }
        }
示例#23
0
        /// <inheritdoc/>
        public void Commit(CorrelationId correlationId, UncommittedEvents uncommittedEvents)
        {
            _logger.Information($"Committing uncommitted event stream with correlationId '{correlationId}'");
            _logger.Trace("Building the Event Store uncommitted event stream");
            var uncommitted = BuildUncommitted(uncommittedEvents, correlationId.Value);

            _logger.Trace("Committing the events");
            CommittedEventStream committed;

            using (var eventStore = _getEventStore())
            {
                committed = eventStore.Commit(uncommitted);
            }
            _logger.Trace("Process events in same bounded context");
            _eventProcessorHub.Process(committed);
            _logger.Trace("Passing committed events through event horizon");
            _eventHorizon.PassThrough(new CommittedEventStreamWithContext(committed, _executionContextManager.Current));
        }
示例#24
0
        public User(Guid userId, string emailAddress)
        {
            if (userId == Guid.Empty)
            {
                throw new ArgumentException(nameof(userId));
            }

            if (string.IsNullOrWhiteSpace(emailAddress))
            {
                throw new ArgumentNullException(nameof(emailAddress));
            }

            var userSubmittedEvent = new UserSubmittedEvent(userId, Version,
                                                            emailAddress, string.Empty, UserStatus.VerificationPending, DateTime.UtcNow);

            ApplyEvent(userSubmittedEvent, Version + 1);
            UncommittedEvents.Add(userSubmittedEvent);
        }
示例#25
0
        /// <inheritdoc/>
        public async Task <CommittedEvents> CommitEvents(UncommittedEvents events, CancellationToken cancellationToken)
        {
            ThrowIfNoEventsToCommit(events);
            try
            {
                using var session = await _streams.StartSessionAsync(cancellationToken : cancellationToken).ConfigureAwait(false);

                return(await session.WithTransactionAsync(
                           async (transaction, cancel) =>
                {
                    var eventLogSequenceNumber = (ulong)await _streams.DefaultEventLog.CountDocumentsAsync(
                        transaction,
                        _eventFilter.Empty,
                        cancellationToken: cancel).ConfigureAwait(false);
                    var committedEvents = new List <CommittedEvent>();
                    foreach (var @event in events)
                    {
                        var committedEvent = await _eventCommitter.CommitEvent(
                            transaction,
                            eventLogSequenceNumber,
                            DateTimeOffset.UtcNow,
                            _executionContextManager.Current,
                            @event,
                            cancel).ConfigureAwait(false);
                        committedEvents.Add(committedEvent);
                        eventLogSequenceNumber++;
                    }

                    return new CommittedEvents(committedEvents);
                },
                           cancellationToken : cancellationToken).ConfigureAwait(false));
            }
            catch (MongoWaitQueueFullException ex)
            {
                throw new EventStoreUnavailable("Mongo wait queue is full", ex);
            }
        }
示例#26
0
    public static void should_be_the_correct_response(this CommitEventsResponse response, UncommittedEvents uncommitted_events, ExecutionContext execution_context, EventLogSequenceNumber start_sequence_number = null)
    {
        var committedEvents = response.Events.ToCommittedEvents();

        committedEvents.Count.ShouldEqual(uncommitted_events.Count);
        if (uncommitted_events.Count == 0)
        {
            return;
        }

        for (var i = 0; i < committedEvents.Count; i++)
        {
            var committedEvent   = committedEvents[i];
            var uncommittedEvent = uncommitted_events[i];

            if (start_sequence_number != null)
            {
                committedEvent.EventLogSequenceNumber.ShouldEqual(new EventLogSequenceNumber(start_sequence_number + (ulong)i));
            }

            committedEvent.ExecutionContext.ShouldEqual(execution_context);
            committedEvent.Content.ShouldEqual(uncommittedEvent.Content);
            committedEvent.Public.ShouldEqual(uncommittedEvent.Public);
            committedEvent.Type.ShouldEqual(uncommittedEvent.Type);
            committedEvent.EventSource.ShouldEqual(uncommittedEvent.EventSource);
        }
    }
示例#27
0
 public void ClearUncommittedEvents()
 {
     UncommittedEvents.Clear();
 }
示例#28
0
 public IReadOnlyCollection <IEvent> GetUncommittedEvents() => UncommittedEvents.AsReadOnly();
示例#29
0
 protected static IEnumerable <T> AllRaisedEvents <T>() where T : DomainEvent
 {
     return(UncommittedEvents.OfType <T>());
 }
示例#30
0
 protected static T RaisedEvent <T>() where T : DomainEvent
 {
     return((T)UncommittedEvents.Single(x => x.GetType() == typeof(T)));
 }