public bool TryLoadFromSnapshot(Type aggregateRootType, Snapshot snapshot, CommittedEventStream committedEventStream, out AggregateRoot aggregateRoot)
        {
            aggregateRoot = null;

            if (snapshot == null) return false;

            if (AggregateSupportsSnapshot(aggregateRootType, snapshot.Payload.GetType()))
            {
                Log.DebugFormat("Reconstructing aggregate root {0}[{1}] from snapshot", aggregateRootType.FullName,
                                snapshot.EventSourceId.ToString("D"));
                aggregateRoot = _aggregateRootCreator.CreateAggregateRoot(aggregateRootType);
                aggregateRoot.InitializeFromSnapshot(snapshot);

                var memType = aggregateRoot.GetType().GetSnapshotInterfaceType();
                var restoreMethod = memType.GetMethod("RestoreFromSnapshot");

                restoreMethod.Invoke(aggregateRoot, new[] { snapshot.Payload });

                Log.DebugFormat("Applying remaining historic event to reconstructed aggregate root {0}[{1}]",
                    aggregateRootType.FullName, snapshot.EventSourceId.ToString("D"));
                aggregateRoot.InitializeFromHistory(committedEventStream);

                return true;
            }

            return false;
        }
Example #2
0
        public CommittedEventStream Commit(UncommittedEventStream uncommittedEventStream)
        {
            foreach (var @event in uncommittedEventStream)
            {
                var eventSourceName = Type.GetType(@event.EventSource).Name;
                var eventPath       = GetPathFor(eventSourceName, @event.EventSourceId);

                @event.Id = GetNextEventId();

                var json = _serializer.ToJson(new EventHolder
                {
                    Type    = @event.GetType(),
                    Version = @event.Version,
                    Event   = _serializer.ToJson(@event)
                });

                var path = Path.Combine(eventPath, $"{@event.Version.Commit}.{@event.Version.Sequence}");
                File.WriteAllText(path, json);
            }

            var committedEventStream = new CommittedEventStream(uncommittedEventStream.EventSourceId);

            committedEventStream.Append(uncommittedEventStream);
            return(committedEventStream);
        }
        /// <inheritdoc/>
        public void Commit(TransactionCorrelationId correlationId, UncommittedEventStream uncommittedEventStream)
        {
            _logger.Information($"Committing uncommitted event stream with correlationId '{correlationId}'");
            var envelopes        = _eventEnvelopes.CreateFrom(uncommittedEventStream.EventSource, uncommittedEventStream.EventsAndVersion);
            var envelopesAsArray = envelopes.ToArray();
            var eventsAsArray    = uncommittedEventStream.ToArray();

            _logger.Trace("Create an array of events and envelopes");
            var eventsAndEnvelopes = new List <EventAndEnvelope>();

            for (var eventIndex = 0; eventIndex < eventsAsArray.Length; eventIndex++)
            {
                var envelope = envelopesAsArray[eventIndex];
                var @event   = eventsAsArray[eventIndex];
                eventsAndEnvelopes.Add(new EventAndEnvelope(
                                           envelope
                                           .WithTransactionCorrelationId(correlationId)
                                           .WithSequenceNumber(_eventSequenceNumbers.Next())
                                           .WithSequenceNumberForEventType(_eventSequenceNumbers.NextForType(envelope.Event)),
                                           @event
                                           ));
            }

            _logger.Trace("Committing events to event store");
            _eventStore.Commit(eventsAndEnvelopes);

            _logger.Trace($"Set event source versions for the event source '{envelopesAsArray[0].EventSource}' with id '{envelopesAsArray[0].EventSourceId}'");
            _eventSourceVersions.SetFor(envelopesAsArray[0].EventSource, envelopesAsArray[0].EventSourceId, envelopesAsArray[envelopesAsArray.Length - 1].Version);

            _logger.Trace("Create a committed event stream");
            var committedEventStream = new CommittedEventStream(uncommittedEventStream.EventSourceId, eventsAndEnvelopes);

            _logger.Trace("Send the committed event stream");
            _committedEventStreamSender.Send(committedEventStream);
        }
Example #4
0
        /// <summary>
        /// Initializes from history.
        /// </summary>
        /// <param name="history">The history.</param>
        public virtual void InitializeFromHistory(CommittedEventStream history)
        {
            Contract.Requires <ArgumentNullException>(history != null, "The history cannot be null.");
            if (_initialVersion != Version)
            {
                throw new InvalidOperationException("Cannot apply history when instance has uncommitted changes.");
            }
            Log.DebugFormat("Initializing event source {0} from history.", history.SourceId);
            if (history.IsEmpty)
            {
                return;
            }

            _eventSourceId = history.SourceId;

            foreach (var historicalEvent in history)
            {
                Log.DebugFormat("Appying historic event {0} to event source {1}", historicalEvent.EventIdentifier,
                                history.SourceId);
                ApplyEventFromHistory(historicalEvent);
            }

            Log.DebugFormat("Finished initializing event source {0} from history. Current event source version is {1}",
                            history.SourceId, history.CurrentSourceVersion);
            _initialVersion = history.CurrentSourceVersion;
        }
Example #5
0
        public bool TryLoadFromSnapshot(Type aggregateRootType, Snapshot snapshot, CommittedEventStream committedEventStream, out AggregateRoot aggregateRoot)
        {
            aggregateRoot = null;

            if (snapshot == null)
            {
                return(false);
            }

            if (AggregateSupportsSnapshot(aggregateRootType, snapshot.Payload.GetType()))
            {
                Log.DebugFormat("Reconstructing aggregate root {0}[{1}] from snapshot", aggregateRootType.FullName,
                                snapshot.EventSourceId.ToString("D"));
                aggregateRoot = _aggregateRootCreator.CreateAggregateRoot(aggregateRootType);
                aggregateRoot.InitializeFromSnapshot(snapshot);

                var memType       = aggregateRoot.GetType().GetSnapshotInterfaceType();
                var restoreMethod = memType.GetMethod("RestoreFromSnapshot");

                restoreMethod.Invoke(aggregateRoot, new[] { snapshot.Payload });

                Log.DebugFormat("Applying remaining historic event to reconstructed aggregate root {0}[{1}]",
                                aggregateRootType.FullName, snapshot.EventSourceId.ToString("D"));
                aggregateRoot.InitializeFromHistory(committedEventStream);

                return(true);
            }

            return(false);
        }
Example #6
0
        void CommittedEventStreamReceived(CommittedEventStream committedEventStream)
        {
            _logger.Information("Committed event stream received - coordinating it");
            committedEventStream.ForEach(e =>
            {
                _logger.Trace("Event received");

                var results = _eventProcessors.Process(e.Envelope, e.Event);
                Parallel.ForEach(results, result =>
                {
                    if (result.Status == EventProcessingStatus.Success)
                    {
                        _logger.Trace("Event processing succeeded");
                        _eventProcessorStates.ReportSuccessFor(result.EventProcessor, e.Event, e.Envelope);

                        if (result.Messages.Count() > 0)
                        {
                            result.Messages.ForEach(message => _logger.Trace($"Event processor message : '{message.Message}' with severity '{message.Severity}'"));
                            _eventProcessorLog.Info(result.EventProcessor, e.Event, e.Envelope, result.Messages);
                        }
                    }
                    else
                    {
                        _logger.Trace("Event processing failed");
                        _eventProcessorStates.ReportFailureFor(result.EventProcessor, e.Event, e.Envelope);
                        _eventProcessorLog.Failed(result.EventProcessor, e.Event, e.Envelope, result.Messages);
                    }
                });
            });
        }
        public bool TryLoadFromSnapshot(Type aggregateRootType, Snapshot snapshot, CommittedEventStream committedEventStream, out Domain.AggregateRoot aggregateRoot)
        {
            aggregateRoot = null;

            if (snapshot == null) return false;

            if (AggregateSupportsSnapshot(aggregateRootType, snapshot.Payload.GetType()))
            {
                try
                {
                    Log.DebugFormat("Reconstructing aggregate root {0}[{1}] from snapshot", aggregateRootType.FullName,
                                    snapshot.EventSourceId.ToString("D"));
                    aggregateRoot = _aggregateRootCreator.CreateAggregateRoot(aggregateRootType);
                    aggregateRoot.InitializeFromSnapshot(snapshot);
                    aggregateRoot.RestoreFromSnapshot(snapshot.Payload);

                    Log.DebugFormat("Applying remaining historic event to reconstructed aggregate root {0}[{1}]",
                        aggregateRootType.FullName, snapshot.EventSourceId.ToString("D"));
                    aggregateRoot.InitializeFromHistory(committedEventStream);
                }
                catch (Exception ex)
                {
                    Log.ErrorFormat("Cannot load snapshot for '{0}' aggregate. {1}",
                        aggregateRoot.GetType().FullName, ex.Message);
                    aggregateRoot = null;
                    return false;
                }

                return true;
            }

            return false;
        }
 public static void ShouldEqual(CommittedEventStream returned, CommittedEventStream sent)
 {
     returned.Id.ShouldEqual(sent.Id);
     returned.CorrelationId.ShouldEqual(sent.CorrelationId);
     returned.Sequence.ShouldEqual(sent.Sequence);
     returned.Source.ShouldEqual(sent.Source);
     returned.Timestamp.ToUnixTimeMilliseconds().ShouldEqual(sent.Timestamp.ToUnixTimeMilliseconds());
 }
Example #9
0
 void ValidateEventStream(CommittedEventStream eventStream)
 {
     if (!IsForThisEventSource(eventStream.EventSourceId))
     {
         throw new InvalidOperationException("Cannot apply an EventStream belonging to a different event source." +
                                             string.Format(@"Expected events for Id {0} but got events for Id {1}", EventSourceId, eventStream.EventSourceId));
     }
 }
Example #10
0
        public void Initializing_from_history_should_not_throw_an_exception_when_the_history_was_empty()
        {
            var theAggregate = new MyAggregateRoot();

            var history = new CommittedEventStream(Guid.Empty);

            theAggregate.InitializeFromHistory(history);
        }
        public void Init_with_source_id_only_should_set_source_id_and_have_no_events()
        {
            var sourceId = Guid.NewGuid();

            var sut = new CommittedEventStream(sourceId);
            sut.SourceId.Should().Be(sourceId);
            sut.Count().Should().Be(0);
        }
        public static UncommittedEventStream BuildNext(this CommittedEventStream eventStream, DateTimeOffset?now = null, CorrelationId correlationId = null)
        {
            Ensure.IsNotNull(nameof(eventStream), eventStream);
            Ensure.ArgumentPropertyIsNotNull(nameof(eventStream), "Source", eventStream.Source);
            var committed          = now ?? DateTimeOffset.Now;
            var eventSourceVersion = eventStream.Source.Next();

            return(BuildFrom(eventSourceVersion, committed, correlationId ?? Guid.NewGuid(), eventStream.Events));
        }
Example #13
0
        public void Init_with_source_id_only_should_set_source_id_and_have_no_events()
        {
            var sourceId = Guid.NewGuid();

            var sut = new CommittedEventStream(sourceId);

            sut.SourceId.Should().Be(sourceId);
            sut.Count().Should().Be(0);
        }
        public void Init_with_source_id_an_null_stream_should_set_source_id_and_have_no_events()
        {
            var sourceId = Guid.NewGuid();
            var nullStream = (IEnumerable<CommittedEvent>) null;

            var sut = new CommittedEventStream(sourceId, nullStream);
            sut.SourceId.Should().Be(sourceId);
            sut.Count().Should().Be(0);
        }
Example #15
0
 public AggregateRoot Load(Type aggreateRootType, Snapshot snapshot, CommittedEventStream eventStream)
 {
     AggregateRoot aggregate;
     if (!_aggregateSnapshotter.TryLoadFromSnapshot(aggreateRootType, snapshot, eventStream, out aggregate))
     {
         aggregate = GetByIdFromScratch(aggreateRootType, eventStream);
     }
     return aggregate;
 }
Example #16
0
        Task Receive(Message message, CancellationToken token)
        {
            var dynamicEventsAndEnvelopes = new List <dynamic>();
            var json = System.Text.Encoding.UTF8.GetString(message.Body);

            _serializer.FromJson(dynamicEventsAndEnvelopes, json);

            var eventsAndEnvelopes = new List <EventAndEnvelope>();

            foreach (var dynamicEventAndEnvelope in dynamicEventsAndEnvelopes)
            {
                var env = dynamicEventAndEnvelope.Envelope;

                var correlationId              = (TransactionCorrelationId)Guid.Parse(env.CorrelationId.ToString());
                var eventId                    = (EventId)Guid.Parse(env.EventId.ToString());
                var sequenceNumber             = (EventSequenceNumber)long.Parse(env.SequenceNumber.ToString());
                var sequenceNumberForEventType = (EventSequenceNumber)long.Parse(env.SequenceNumberForEventType.ToString());
                var generation                 = (EventGeneration)long.Parse(env.Generation.ToString());
                var @event        = _applicationResourceIdentifierConverter.FromString(env.Event.ToString());
                var eventSourceId = (EventSourceId)Guid.Parse(env.EventSourceId.ToString());
                var eventSource   = _applicationResourceIdentifierConverter.FromString(env.EventSource.ToString());
                var version       = (EventSourceVersion)EventSourceVersion.FromCombined(double.Parse(env.Version.ToString()));
                var causedBy      = (CausedBy)env.CausedBy.ToString();
                var occurred      = DateTimeOffset.Parse(env.Occurred.ToString());

                var envelope = new EventEnvelope(
                    correlationId,
                    eventId,
                    sequenceNumber,
                    sequenceNumberForEventType,
                    generation,
                    @event,
                    eventSourceId,
                    eventSource,
                    version,
                    causedBy,
                    occurred
                    );

                var eventType = _applicationResourceResolver.Resolve(@event);

                var eventInstance = Activator.CreateInstance(eventType, new object[] { eventSourceId }) as IEvent;
                var e             = dynamicEventAndEnvelope.Event.ToString();

                _serializer.FromJson(eventInstance, e);
                eventsAndEnvelopes.Add(new EventAndEnvelope(envelope, eventInstance));
            }

            var stream = new CommittedEventStream(eventsAndEnvelopes.First().Envelope.EventSourceId, eventsAndEnvelopes);

            Received(stream);

            _queueClient.CompleteAsync(message.SystemProperties.LockToken);

            return(Task.CompletedTask);
        }
Example #17
0
        public void Init_with_source_id_an_null_stream_should_set_source_id_and_have_no_events()
        {
            var sourceId   = Guid.NewGuid();
            var nullStream = (IEnumerable <CommittedEvent>)null;

            var sut = new CommittedEventStream(sourceId, nullStream);

            sut.SourceId.Should().Be(sourceId);
            sut.Count().Should().Be(0);
        }
Example #18
0
        public CommittedEventStream GetForEventSource(EventSource eventSource, Guid eventSourceId)
        {
            var eventStream = new CommittedEventStream(eventSourceId);

            if (_aggregatedRootEvents.ContainsKey(eventSourceId))
            {
                eventStream.Append(_aggregatedRootEvents[eventSourceId]);
            }
            return(eventStream);
        }
Example #19
0
 protected AggregateRoot GetByIdFromScratch(Type aggregateRootType, CommittedEventStream committedEventStream)
 {
     if (committedEventStream.IsEmpty)
     {
         return null;
     }
     AggregateRoot aggregateRoot = _aggregateRootCreator.CreateAggregateRoot(aggregateRootType);
     aggregateRoot.InitializeFromHistory(committedEventStream);
     return aggregateRoot;
 }
Example #20
0
        public CommittedEventStream Commit(UncommittedEventStream uncommittedEventStream)
        {
            var events                 = uncommittedEventStream.Select(e => e).ToArray();
            var parameters             = new List <OracleParameter>();
            var insertStatementBuilder = new StringBuilder();

            insertStatementBuilder.Append("BEGIN ");
            for (var position = 0; position < events.Length; position++)
            {
                insertStatementBuilder.Append(GetParameterizedInsertStatement(position));
                parameters.AddRange(_eventParameters.BuildFromEvent(position, events[position]));
            }
            insertStatementBuilder.Append(" END;");

            Tuple <int, long>[] returnedIds;

            try
            {
                OpenConnection();
                var transaction = _connection.BeginTransaction();
                try
                {
                    using (var command = _connection.CreateCommand())
                    {
                        command.Transaction = transaction;
                        command.CommandText = insertStatementBuilder.ToString();
                        command.Parameters.AddRange(parameters.ToArray());
                        command.BindByName = true;
                        command.ExecuteNonQuery();

                        returnedIds = ExtractReturnedIds(parameters);
                        transaction.Commit();
                    }
                }
                catch (Exception)
                {
                    transaction.Rollback();
                    throw;
                }
            }
            finally
            {
                EnsureConnectionClosed(_connection);
            }

            PopulateEventId(returnedIds, events);

            var committedEventStream = new CommittedEventStream(uncommittedEventStream.EventSourceId);

            if (events.Any())
            {
                committedEventStream.Append(events);
            }
            return(committedEventStream);
        }
Example #21
0
        public void Init_should_set_From_and_To_version_information()
        {
            var sourceId        = Guid.NewGuid();
            var eventObjects    = new[] { new Object(), new Object(), new Object() };
            var committedEvents = Prepare.Events(eventObjects).ForSource(sourceId, 5).ToList();

            var sut = new CommittedEventStream(sourceId, committedEvents);

            sut.FromVersion.Should().Be(committedEvents.First().EventSequence);
            sut.ToVersion.Should().Be(committedEvents.Last().EventSequence);
        }
Example #22
0
        void ReApplyEvents(ICommandContext commandContext, T aggregateRoot)
        {
            var identifier = _applicationResources.Identify(typeof(T));
            var events     = _eventStore.GetFor(identifier, aggregateRoot.EventSourceId);
            var stream     = new CommittedEventStream(aggregateRoot.EventSourceId, events);

            if (stream.HasEvents)
            {
                aggregateRoot.ReApply(stream);
            }
        }
Example #23
0
        public AggregateRoot Load(Type aggreateRootType, Snapshot snapshot, CommittedEventStream eventStream)
        {
            AggregateRoot aggregate = null;

            if (!_aggregateSnapshotter.TryLoadFromSnapshot(aggreateRootType, snapshot, eventStream, out aggregate))
            {
                aggregate = GetByIdFromScratch(aggreateRootType, eventStream);
            }

            return(aggregate);
        }
Example #24
0
        public static CommittedEventStream ShouldCorrespondTo(this CommittedEventStream result, UncommittedEventStream uncommittedEventStream)
        {
            Ensure.IsNotNull(nameof(uncommittedEventStream), uncommittedEventStream);
            Ensure.IsNotNull(nameof(result), result);
            Ensure.ArgumentPropertyIsNotNull(nameof(uncommittedEventStream), "Events", uncommittedEventStream.Events);
            Ensure.ArgumentPropertyIsNotNull(nameof(result), "Events", result.Events);

            result.Events.ShouldContainOnly(uncommittedEventStream.Events);
            result.Source.ShouldEqual(uncommittedEventStream.Source);
            return(result);
        }
Example #25
0
        public void Initiazling_from_wrong_history_with_wrong_sequence_should_throw_exception()
        {
            var        theAggregate  = new MyAggregateRoot();
            const long wrongSequence = 3;
            var        stream        = new CommittedEventStream(theAggregate.EventSourceId,
                                                                new CommittedEvent(Guid.NewGuid(), Guid.NewGuid(), theAggregate.EventSourceId, wrongSequence, DateTime.UtcNow, new HandledEvent(), new Version(1, 0)));

            Action act = () => theAggregate.InitializeFromHistory(stream);

            act.ShouldThrow <InvalidOperationException>().And.Message.Should().Contain("sequence");
        }
        public void Init_should_set_From_and_To_version_information()
        {
            var sourceId = Guid.NewGuid();
            var eventObjects = new[] { new Object(), new Object(), new Object() };
            var committedEvents = Prepare.Events(eventObjects).ForSource(sourceId, 5).ToList();

            var sut = new CommittedEventStream(sourceId, committedEvents);

            sut.FromVersion.Should().Be(committedEvents.First().EventSequence);
            sut.ToVersion.Should().Be(committedEvents.Last().EventSequence);
        }
Example #27
0
        /// <inheritdoc/>
        public virtual void ReApply(CommittedEventStream eventStream)
        {
            ValidateEventStream(eventStream);

            foreach (var eventAndEnvelope in eventStream)
            {
                InvokeOnMethod(eventAndEnvelope.Event);
                Version = eventAndEnvelope.Envelope.Version;
            }

            Version = Version.NextCommit();
        }
Example #28
0
        public void Initiazling_from_history_with_correct_sequence_should_not_throw_exception()
        {
            var theAggregate = new MyAggregateRoot();

            var stream = new CommittedEventStream(theAggregate.EventSourceId,
                                                  new CommittedEvent(Guid.NewGuid(), Guid.NewGuid(), theAggregate.EventSourceId, 1, DateTime.UtcNow, new HandledEvent(), new Version(1, 0)),
                                                  new CommittedEvent(Guid.NewGuid(), Guid.NewGuid(), theAggregate.EventSourceId, 2, DateTime.UtcNow, new HandledEvent(), new Version(1, 0)),
                                                  new CommittedEvent(Guid.NewGuid(), Guid.NewGuid(), theAggregate.EventSourceId, 3, DateTime.UtcNow, new HandledEvent(), new Version(1, 0)),
                                                  new CommittedEvent(Guid.NewGuid(), Guid.NewGuid(), theAggregate.EventSourceId, 4, DateTime.UtcNow, new HandledEvent(), new Version(1, 0)),
                                                  new CommittedEvent(Guid.NewGuid(), Guid.NewGuid(), theAggregate.EventSourceId, 5, DateTime.UtcNow, new HandledEvent(), new Version(1, 0)));

            theAggregate.InitializeFromHistory(stream);
        }
        public CommittedEventStream ReadFrom(Guid id, long minVersion, long maxVersion)
        {
            List <CommittedEvent> events = GetAllEventsSinceVersion(id, minVersion)
                                           .Where(n => n.EventSequence <= maxVersion)
                                           .Select(evt => new CommittedEvent(
                                                       Guid.NewGuid(), evt.EventIdentifier, id, evt.EventSequence,
                                                       evt.EventTimeStamp, evt, evt.EventVersion))
                                           .ToList();

            var stream = new CommittedEventStream(id, events);

            return(stream);
        }
        public void Init_with_source_id_and_stream_should_set_source_id_and_contain_all_events_as_given()
        {
            var sourceId = Guid.NewGuid();
            var stream = new[]
            {
                new CommittedEvent(Guid.NewGuid(), Guid.NewGuid(), sourceId, 1, DateTime.Now, new object(),
                                   new Version(1, 0))
            };

            var sut = new CommittedEventStream(sourceId, stream);
            sut.SourceId.Should().Be(sourceId);

            sut.Should().BeEquivalentTo(stream);
        }
Example #31
0
        public CommittedEventStream Commit(UncommittedEventStream uncommittedEventStream)
        {
            if (!_aggregatedRootEvents.ContainsKey(uncommittedEventStream.EventSourceId))
            {
                _aggregatedRootEvents[uncommittedEventStream.EventSourceId] = new List <IEvent>();
            }

            _aggregatedRootEvents[uncommittedEventStream.EventSourceId].AddRange(uncommittedEventStream);

            var committedEventStream = new CommittedEventStream(uncommittedEventStream.EventSourceId);

            committedEventStream.Append(uncommittedEventStream);
            return(committedEventStream);
        }
Example #32
0
        /// <inheritdoc />
        CommittedEventStream Commit(UncommittedEventStream uncommittedEvents, CommitSequenceNumber commitSequenceNumber)
        {
            lock (lock_object)
            {
                ThrowIfDuplicate(uncommittedEvents.Id);
                ThrowIfConcurrencyConflict(uncommittedEvents.Source);

                var commit = new CommittedEventStream(commitSequenceNumber, uncommittedEvents.Source, uncommittedEvents.Id, uncommittedEvents.CorrelationId, uncommittedEvents.Timestamp, uncommittedEvents.Events);
                _commits.Add(commit);
                _duplicates.Add(commit.Id);
                _versions.AddOrUpdate(commit.Source.Key, commit.Source, (id, ver) => commit.Source);
                return(commit);
            }
        }
        protected AggregateRoot GetByIdFromScratch(Type aggregateRootType, CommittedEventStream committedEventStream)
        {
            AggregateRoot aggregateRoot = null;
            Log.DebugFormat("Reconstructing aggregate root {0}[{1}] directly from event stream", aggregateRootType.FullName,
                               committedEventStream.SourceId.ToString("D"));

            if (committedEventStream.Count() > 0)
            {
                aggregateRoot = _aggregateRootCreator.CreateAggregateRoot(aggregateRootType);
                aggregateRoot.InitializeFromHistory(committedEventStream);
            }

            return aggregateRoot;
        }
Example #34
0
        protected AggregateRoot GetByIdFromScratch(Type aggregateRootType, CommittedEventStream committedEventStream)
        {
            AggregateRoot aggregateRoot = null;

            Log.DebugFormat("Reconstructing aggregate root {0}[{1}] directly from event stream", aggregateRootType.FullName,
                            committedEventStream.SourceId.ToString("D"));

            if (committedEventStream.Count() > 0)
            {
                aggregateRoot = _aggregateRootCreator.CreateAggregateRoot(aggregateRootType);
                aggregateRoot.InitializeFromHistory(committedEventStream);
            }

            return(aggregateRoot);
        }
Example #35
0
        public void Init_with_source_id_and_stream_should_set_source_id_and_contain_all_events_as_given()
        {
            var sourceId = Guid.NewGuid();
            var stream   = new[]
            {
                new CommittedEvent(Guid.NewGuid(), Guid.NewGuid(), sourceId, 1, DateTime.Now, new object(),
                                   new Version(1, 0))
            };

            var sut = new CommittedEventStream(sourceId, stream);

            sut.SourceId.Should().Be(sourceId);

            sut.Should().BeEquivalentTo(stream);
        }
Example #36
0
        public CommittedEventStream GetForEventSource(EventSource eventSource, Guid eventSourceId)
        {
            var eventSourceType = eventSource.GetType();
            var query           = Query.And(
                Query.EQ("EventSourceId", eventSourceId),
                Query.EQ("EventSource", eventSourceType.AssemblyQualifiedName)
                );

            var cursor    = _collection.FindAs <BsonDocument>(query);
            var documents = cursor.ToArray();
            var events    = ToEvents(documents);
            var stream    = new CommittedEventStream(eventSourceId);

            stream.Append(events);
            return(stream);
        }
Example #37
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="committedEventStream"></param>
        public void Process(CommittedEventStream committedEventStream)
        {
            var committedEventStreamWithContext = new CommittedEventStreamWithContext(committedEventStream, _executionContextManager.Current);

            _logger.Debug($"Received  stream {committedEventStream.Sequence} {committedEventStream.Id} {committedEventStream.CorrelationId}");
            if (_canProcessEvents.WaitOne(TimeSpan.FromMilliseconds(1)))
            {
                _logger.Debug($"Processing  stream {committedEventStream.Sequence} {committedEventStream.Id} {committedEventStream.CorrelationId}");
                ProcessStream(committedEventStreamWithContext);
            }
            else
            {
                _logger.Debug($"Queuing  stream {committedEventStream.Sequence} {committedEventStream.Id} {committedEventStream.CorrelationId}");
                Enqueue(committedEventStreamWithContext);
            }
        }
Example #38
0
        public CommittedEventStream GetForEventSource(EventSource eventSource, Guid eventSourceId)
        {
            var committedEventStream = new CommittedEventStream(eventSourceId);

            var eventSourceParam = new OracleParameter(EventParameters.EVENTSOURCE, OracleDbType.NVarchar2, 512);

            eventSourceParam.Value = eventSource.GetType().AssemblyQualifiedName;

            var eventSourceIdParam = new OracleParameter(EventParameters.EVENTSOURCEID, OracleDbType.Raw, 16);

            eventSourceIdParam.Value = eventSourceId.ToByteArray();

            var eventDtos = new List <EventDto>();

            try
            {
                OpenConnection();
                using (var command = _connection.CreateCommand())
                {
                    command.CommandText = READ_STATEMENT_FOR_EVENTS_BY_AGGREGATE_ROOT;
                    command.Parameters.Add(eventSourceIdParam);
                    command.Parameters.Add(eventSourceParam);
                    command.BindByName = true;
                    var reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        eventDtos.Add(MapReaderToEventDto(reader));
                    }
                }
            }
            finally
            {
                EnsureConnectionClosed(_connection);
            }

            var retrievedEvents = eventDtos.Select(BuildEventInstanceFromDto)
                                  .Select(@event => _eventMigratorManager.Migrate(@event))
                                  .ToList();

            if (retrievedEvents.Any())
            {
                committedEventStream.Append(retrievedEvents);
            }

            return(committedEventStream);
        }
Example #39
0
        public CommittedEventStream GetForEventSource(EventSource eventSource, Guid eventSourceId)
        {
            using (var session = _documentStore.OpenSession())
            {
                var eventSourceType = eventSource.GetType();

                var events = session.Query <IEvent>()
                             .Where(
                    e => e.EventSourceId == eventSourceId &&
                    e.EventSource == eventSourceType.AssemblyQualifiedName
                    ).ToArray();

                var stream = new CommittedEventStream(eventSourceId);
                stream.Append(events);
                return(stream);
            }
        }
        public bool TryLoadFromSnapshot(Type aggregateRootType, Snapshot snapshot, CommittedEventStream committedEventStream, out AggregateRoot aggregateRoot)
        {
            aggregateRoot = null;
            if (snapshot == null)
                return false;

            if (AggregateSupportsSnapshot(aggregateRootType, snapshot.Payload.GetType()))
            {
                aggregateRoot = _aggregateRootCreator.CreateAggregateRoot(aggregateRootType);
                aggregateRoot.InitializeFromSnapshot(snapshot);

                MethodInfo restoreMethod = aggregateRoot.GetType().GetSnapshotRestoreMethod();
                restoreMethod.Invoke(aggregateRoot, new[] {snapshot.Payload});

                aggregateRoot.InitializeFromHistory(committedEventStream);
                return true;
            }
            return false;
        }
Example #41
0
#pragma warning disable 1591 // Xml Comments
        public CommittedEventStream GetForEventSource(EventSource eventSource, Guid eventSourceId)
        {
            var eventPath = GetPathFor(eventSource.GetType().Name, eventSourceId);
            var files = Directory.GetFiles(eventPath).OrderBy(f => f);

            var stream = new CommittedEventStream(eventSourceId);

            var target = new EventHolder
            {
                Type = typeof(string),
                Version = EventSourceVersion.Zero,
                Event = string.Empty
            };

            foreach (var file in files)
            {
                var json = File.ReadAllText(file);
                _serializer.FromJson(target, json);

                var @event = _serializer.FromJson(target.Type, json) as IEvent;
                stream.Append(new[] { @event });
            }
            return stream;
        }
 public AggregateRoot Load(Type aggreateRootType, Snapshot snapshot, CommittedEventStream eventStream)
 {
     Contract.Requires<ArgumentNullException>(eventStream != null);
     return default(AggregateRoot);
 }
        public void Initializing_from_history_should_not_throw_an_exception_when_the_history_was_empty()
        {
            var theAggregate = new MyAggregateRoot();

            var history = new CommittedEventStream(Guid.Empty);

            theAggregate.InitializeFromHistory(history);
        }
        public void Initiazling_from_wrong_history_with_wrong_sequence_should_throw_exception()
        {
            var theAggregate = new MyAggregateRoot();
            const long wrongSequence = 3;
            var stream = new CommittedEventStream(theAggregate.EventSourceId,
                new CommittedEvent(Guid.NewGuid(), Guid.NewGuid(), theAggregate.EventSourceId, wrongSequence, DateTime.UtcNow, new HandledEvent(), new Version(1, 0)));

            Action act = ()=> theAggregate.InitializeFromHistory(stream);
            act.ShouldThrow<InvalidOperationException>().And.Message.Should().Contain("sequence");
        }
        public void Initiazling_from_history_with_correct_sequence_should_not_throw_exception()
        {
            var theAggregate = new MyAggregateRoot();

            var stream = new CommittedEventStream(theAggregate.EventSourceId,
                new CommittedEvent(Guid.NewGuid(), Guid.NewGuid(), theAggregate.EventSourceId, 1, DateTime.UtcNow, new HandledEvent(), new Version(1, 0)),
                new CommittedEvent(Guid.NewGuid(), Guid.NewGuid(), theAggregate.EventSourceId, 2, DateTime.UtcNow, new HandledEvent(), new Version(1, 0)),
                new CommittedEvent(Guid.NewGuid(), Guid.NewGuid(), theAggregate.EventSourceId, 3, DateTime.UtcNow, new HandledEvent(), new Version(1, 0)),
                new CommittedEvent(Guid.NewGuid(), Guid.NewGuid(), theAggregate.EventSourceId, 4, DateTime.UtcNow, new HandledEvent(), new Version(1, 0)),
                new CommittedEvent(Guid.NewGuid(), Guid.NewGuid(), theAggregate.EventSourceId, 5, DateTime.UtcNow, new HandledEvent(), new Version(1, 0)));

            theAggregate.InitializeFromHistory(stream);
        }
        public CommittedEventStream ReadFrom(Guid eventSourceId, long minVersion, long maxVersion)
        {
            Contract.Requires<ArgumentException>(eventSourceId != Guid.Empty);

            _mongoServer.Connect();

            var db = _mongoServer.GetDatabase(_databaseName);
            var coll = db.GetCollection<MongoCommit>(_collectionName);

            var query = Query.ElemMatch(
                "Events",
                Query.And(
                    Query.EQ("EventSourceId",eventSourceId),
                    Query.GTE("EventSequence", minVersion),
                    Query.LTE("EventSequence", maxVersion)
                    )
                );

            var commits = coll.Find(query);
            var events = commits.SelectMany(
                c =>
                    c.Events.Where(evt=>evt.EventSourceId == eventSourceId) // Get only events related to the correct source Id
                    .Select(evt=> new { c.CommitId, EventData = evt}) // Build a temp object containing the commit id and the event data
                );

            var result = new CommittedEventStream(
                eventSourceId,
                events.Select(evt=>new CommittedEvent(
                    evt.CommitId,
                    evt.EventData.EventIdentifier,
                    evt.EventData.EventSourceId,
                    evt.EventData.EventSequence,
                    evt.EventData.EventTimeStamp,
                    evt.EventData.Data,
                    evt.EventData.Version
                    ))
                );

            _mongoServer.Disconnect();

            return result;
        }
Example #47
0
        /// <summary>
        /// Initializes from history.
        /// </summary>
        /// <param name="history">The history.</param>
        public virtual void InitializeFromHistory(CommittedEventStream history)
        {
            Contract.Requires<ArgumentNullException>(history != null, "The history cannot be null.");
            if (_initialVersion != Version)
            {
                throw new InvalidOperationException("Cannot apply history when instance has uncommitted changes.");
            }
            Log.DebugFormat("Initializing event source {0} from history.", history.SourceId);
            if (history.IsEmpty)
            {
                return;
            }

            _eventSourceId = history.SourceId;

            foreach (var historicalEvent in history)
            {
                Log.DebugFormat("Appying historic event {0} to event source {1}", historicalEvent.EventIdentifier,
                                history.SourceId);
                ApplyEventFromHistory(historicalEvent);
            }

            Log.DebugFormat("Finished initializing event source {0} from history. Current event source version is {1}",
                            history.SourceId, history.CurrentSourceVersion);
            _initialVersion = history.CurrentSourceVersion;
        }
Example #48
0
        public CommittedEventStream Commit(UncommittedEventStream uncommittedEventStream)
        {
            foreach (var @event in uncommittedEventStream)
            {
                var eventSourceName = Type.GetType(@event.EventSource).Name;
                var eventPath = GetPathFor(eventSourceName, @event.EventSourceId);

                @event.Id = GetNextEventId();

                var json = _serializer.ToJson(new EventHolder
                {
                    Type = @event.GetType(),
                    Version = @event.Version,
                    Event = _serializer.ToJson(@event)
                });


                File.WriteAllText(string.Format("{0}\\{1}.{2}",eventPath,@event.Version.Commit, @event.Version.Sequence), json);
            }

            var committedEventStream = new CommittedEventStream(uncommittedEventStream.EventSourceId);
            committedEventStream.Append(uncommittedEventStream);
            return committedEventStream;
        }
 public void InitializeFromHistory(CommittedEventStream history)
 {
     throw new NotImplementedException();
 }
        public CommittedEventStream ReadFrom(Guid id, long minVersion, long maxVersion)
        {
            List<CommittedEvent> events = GetAllEventsSinceVersion(id, minVersion)
                .Where(n => n.EventSequence <= maxVersion)
                .Select(evt => new CommittedEvent(
                    Guid.NewGuid(), evt.EventIdentifier, id, evt.EventSequence,
                    evt.EventTimeStamp, evt, evt.EventVersion))
                .ToList();

            var stream = new CommittedEventStream(id, events);

            return stream;
        }