Exemple #1
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 CommittedEventStream Commit(UncommittedEventStream uncommittedEvents)
        {
            var commit = Persistence.Commit.From(uncommittedEvents, _serializer);

            using (var es = _database.GetContext())
            {
                try
                {
                    es.Commits.Add(commit);
                    es.SaveChanges();
                    return(commit.ToCommittedEventStream(_serializer));
                }
                catch (DbUpdateException ex)
                {
                    if (IsADuplicate(ex))
                    {
                        throw new CommitIsADuplicate("Commit is a duplicate", ex);
                    }
                    if (IsConcurrencyException(ex))
                    {
                        throw new EventSourceConcurrencyConflict(ex.Message, ex);
                    }
                    throw new EventStorePersistenceError("Unknown error", ex);
                }
            }
        }
 public void When_contains_multpile_events_from_different_sources_should_indicate_non_single_source()
 {
     var sut = new UncommittedEventStream(Guid.NewGuid());
     sut.Append(CreateEvent(Guid.NewGuid()));
     sut.Append(CreateEvent(Guid.NewGuid()));
     Assert.IsFalse(sut.HasSingleSource);
 }
        Persistence.Commit ToCommit(UncommittedEventStream uncommittedEvents)
        {
            var events = uncommittedEvents.Events.Select(e =>
                                                         new Persistence.Event
            {
                Id                  = e.Id.Value,
                CorrelationId       = e.Metadata.CorrelationId.Value,
                EventArtifact       = e.Metadata.Artifact.Id.Value,
                Generation          = e.Metadata.Artifact.Generation.Value,
                EventSourceArtifact = uncommittedEvents.Source.Artifact.Value,
                EventSourceId       = e.Metadata.EventSourceId.Value,
                Commit              = e.Metadata.VersionedEventSource.Version.Commit,
                Sequence            = e.Metadata.VersionedEventSource.Version.Sequence,
                Occurred            = e.Metadata.Occurred.ToUnixTimeMilliseconds(),
                OriginalContext     = _serializer.ToJson(Persistence.OriginalContext.From(e.Metadata.OriginalContext)),
                EventData           = PropertyBagSerializer.Serialize(e.Event, _serializer)
            }
                                                         ).ToList();

            var commit = new Commit
            {
                Id                  = 0,
                CorrelationId       = uncommittedEvents.CorrelationId.Value,
                CommitId            = uncommittedEvents.Id.Value,
                Timestamp           = uncommittedEvents.Timestamp.ToUnixTimeMilliseconds(),
                EventSourceId       = uncommittedEvents.Source.EventSource.Value,
                EventSourceArtifact = uncommittedEvents.Source.Artifact.Value,
                CommitNumber        = uncommittedEvents.Source.Version.Commit,
                Sequence            = uncommittedEvents.Source.Version.Sequence,
                Events              = events
            };

            return(commit);
        }
Exemple #5
0
#pragma warning disable 1591 // Xml Comments
        public void Commit(UncommittedEventStream uncommittedEventStream)
        {
            var committedEventStream = _eventStore.Commit(uncommittedEventStream);

            _eventSubscriptionManager.Process(committedEventStream);
            _eventStoreChangeManager.NotifyChanges(_eventStore, committedEventStream);
        }
        public void Retrieved_event_should_having_identical_timestamp_as_persisted()
        {
            var id = Guid.NewGuid();
            var utcNow = DateTime.UtcNow.Date.AddHours(9).AddTicks(-1);

            var stream = new UncommittedEventStream(Guid.NewGuid());
            stream.Append(
                new UncommittedEvent(Guid.NewGuid(), id, typeof(object), 1, 0, utcNow, new CustomerCreatedEvent("Foo", 35),
                                     new Version(1, 0)));

            _store.Store(stream);

            using (var conn = new SQLiteConnection(_connString))
            {
                conn.Open();

                using (var cmd = new SQLiteCommand("SELECT [TimeStamp] FROM [Events]", conn))
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var timestamp = (long)reader["Timestamp"];
                        timestamp.Should().Be(utcNow.Ticks);
                    }
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="events"></param>
        /// <param name="jsonSerializer"></param>
        /// <param name="partitionKey"></param>
        /// <returns></returns>
        public static Commit From(UncommittedEventStream events, ISerializer jsonSerializer, string partitionKey)
        {
            var eventDocs = events.Events.Select(e => new Event
            {
                Id                  = e.Id,
                CorrelationId       = e.Metadata.CorrelationId,
                EventArtifact       = e.Metadata.Artifact.Id,
                EventSourceId       = e.Metadata.EventSourceId,
                Generation          = e.Metadata.Artifact.Generation,
                EventSourceArtifact = events.Source.Artifact,
                Commit              = e.Metadata.VersionedEventSource.Version.Commit,
                Sequence            = e.Metadata.VersionedEventSource.Version.Sequence,
                Occurred            = e.Metadata.Occurred.ToUnixTimeMilliseconds(),
                OriginalContext     = OriginalContext.From(e.Metadata.OriginalContext),
                EventData           = PropertyBagSerializer.Serialize(e.Event, jsonSerializer)
            });

            var commit = new Commit
            {
                Id                  = "0",
                CorrelationId       = events.CorrelationId,
                CommitId            = events.Id,
                Timestamp           = events.Timestamp.ToUnixTimeMilliseconds(),
                EventSourceId       = events.Source.EventSource,
                EventSourceArtifact = events.Source.Artifact,
                CommitNumber        = events.Source.Version.Commit,
                Sequence            = events.Source.Version.Sequence,
                Events              = eventDocs.ToArray(),
                PartitionKey        = partitionKey
            };

            return(commit);
        }
        public void Event_saving_smoke_test()
        {
            var targetStore = new RavenDBEventStore(_documentStore);
            var id          = Guid.NewGuid();

            int sequenceCounter = 0;

            var events = new UncommittedEventStream(Guid.NewGuid());

            events.Append(new UncommittedEvent(Guid.NewGuid(), id, sequenceCounter++, 0, DateTime.UtcNow, new CustomerCreatedEvent("Foo",
                                                                                                                                   35),
                                               new Version(1, 0)));
            events.Append(new UncommittedEvent(Guid.NewGuid(), id, sequenceCounter++, 0, DateTime.UtcNow, new CustomerNameChanged(
                                                   "Name" + sequenceCounter),
                                               new Version(1, 0)));
            events.Append(new UncommittedEvent(Guid.NewGuid(), id, sequenceCounter++, 0, DateTime.UtcNow, new CustomerNameChanged(
                                                   "Name" + sequenceCounter),
                                               new Version(1, 0)));
            events.Append(new UncommittedEvent(Guid.NewGuid(), id, sequenceCounter++, 0, DateTime.UtcNow, new CustomerNameChanged(
                                                   "Name" + sequenceCounter),
                                               new Version(1, 0)));


            targetStore.Store(events);
        }
        public void Rolling_back_transaction_should_remove_inserted_rows()
        {
            var id = Guid.NewGuid();
            var utcNow = DateTime.UtcNow.Date.AddHours(9).AddTicks(-1);

            var stream = new UncommittedEventStream(Guid.NewGuid());
            stream.Append(
                new UncommittedEvent(Guid.NewGuid(), id, 1, 0, utcNow, new CustomerCreatedEvent("Foo", 35),
                                     new Version(1, 0)));

            _store.Store(stream);
            _transaction.Rollback();

            using (var conn = new SQLiteConnection(_connString))
            {
                conn.Open();

                using (var cmd = new SQLiteCommand("SELECT [TimeStamp] FROM [Events]", conn))
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Assert.Fail("No rows should exist");
                    }
                }
            }
        }
Exemple #10
0
        public void When_contains_single_event_should_indicate_a_single_source()
        {
            var sut = new UncommittedEventStream(Guid.NewGuid());

            sut.Append(new UncommittedEvent(Guid.NewGuid(), Guid.NewGuid(), 0, 0, DateTime.UtcNow, new object(), new Version(1, 0)));
            Assert.IsTrue(sut.HasSingleSource);
        }
Exemple #11
0
        public void Retrieving_all_events_should_return_the_same_as_added()
        {
            var id = Guid.NewGuid();
            var sequenceCounter = 0;

            var stream = new UncommittedEventStream(Guid.NewGuid());

            stream.Append(
                new UncommittedEvent(Guid.NewGuid(), id, sequenceCounter++, 0, DateTime.UtcNow, new CustomerCreatedEvent("Foo", 35),
                                     new Version(1, 0)));
            stream.Append(
                new UncommittedEvent(Guid.NewGuid(), id, sequenceCounter++, 0, DateTime.UtcNow,
                                     new CustomerNameChanged("Name" + sequenceCounter), new Version(1, 0)));
            stream.Append(
                new UncommittedEvent(Guid.NewGuid(), id, sequenceCounter++, 0, DateTime.UtcNow,
                                     new CustomerNameChanged("Name" + sequenceCounter), new Version(1, 0)));

            _store.Store(stream);

            var result = _store.ReadFrom(id, long.MinValue, long.MaxValue);

            result.Count().Should().Be(stream.Count());
            result.First().EventIdentifier.Should().Be(stream.First().EventIdentifier);
            //TODO:

            var streamList = stream.ToList();
            var resultList = result.ToList();

            for (int i = 0; i < resultList.Count; i++)
            {
                Assert.IsTrue(AreEqual(streamList[i], resultList[i]));
            }
        }
Exemple #12
0
        public void Rolling_back_transaction_should_remove_inserted_rows()
        {
            var id     = Guid.NewGuid();
            var utcNow = DateTime.UtcNow.Date.AddHours(9).AddTicks(-1);

            var stream = new UncommittedEventStream(Guid.NewGuid());

            stream.Append(
                new UncommittedEvent(Guid.NewGuid(), id, 1, 0, utcNow, new CustomerCreatedEvent("Foo", 35),
                                     new Version(1, 0)));

            _store.Store(stream);
            _transaction.Rollback();

            using (var conn = new SQLiteConnection(_connString))
            {
                conn.Open();

                using (var cmd = new SQLiteCommand("SELECT [TimeStamp] FROM [Events]", conn))
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            Assert.Fail("No rows should exist");
                        }
                    }
            }
        }
Exemple #13
0
 public void Store(UncommittedEventStream eventStream)
 {
     try
     {
         using (var session = _documentStore.OpenSession())
         {
             session.Advanced.UseOptimisticConcurrency = true;
             foreach (var uncommittedEvent in eventStream)
             {
                 session.Store(ToStoredEvent(eventStream.CommitId, uncommittedEvent));
             }
             session.SaveChanges();
         }
     }
     catch (Raven.Abstractions.Exceptions.ConcurrencyException)
     {
         Guid sourceId = Guid.Empty;
         long version  = 0;
         if (eventStream.HasSingleSource)
         {
             sourceId = eventStream.SourceId;
             version  = eventStream.Sources.Single().CurrentVersion;
         }
         throw new ConcurrencyException(sourceId, version);
     }
 }
        /// <summary>
        /// Converts an <see cref="UncommittedEventStream" /> into its <see cref="BsonDocument" /> representation
        /// </summary>
        /// <param name="uncommittedEvents">The <see cref="UncommittedEventStream" /></param>
        /// <returns>A <see cref="BsonDocument" /> representation of the <see cref="UncommittedEventStream" /></returns>
        public static BsonDocument AsBsonCommit(this UncommittedEventStream uncommittedEvents)
        {
            var eventDocs = uncommittedEvents.Events.Select(e =>
            {
                return(new BsonDocument(new Dictionary <string, object>
                {
                    { Constants.ID, e.Id.Value },
                    { Constants.CORRELATION_ID, e.Metadata.CorrelationId.Value },
                    { EventConstants.EVENT_ARTIFACT, e.Metadata.Artifact.Id.Value },
                    { Constants.GENERATION, e.Metadata.Artifact.Generation.Value },
                    { Constants.EVENT_SOURCE_ARTIFACT, uncommittedEvents.Source.Artifact.Value },
                    { Constants.EVENTSOURCE_ID, e.Metadata.EventSourceId.Value },
                    { VersionConstants.COMMIT, e.Metadata.VersionedEventSource.Version.Commit },
                    { VersionConstants.SEQUENCE, e.Metadata.VersionedEventSource.Version.Sequence },
                    { EventConstants.OCCURRED, e.Metadata.Occurred.ToUnixTimeMilliseconds() },
                    { EventConstants.ORIGINAL_CONTEXT, e.Metadata.OriginalContext.AsBson() },
                    { EventConstants.EVENT, PropertyBagBsonSerializer.Serialize(e.Event) }
                }));
            });

            var doc = new BsonDocument(new Dictionary <string, object>
            {
                { Constants.ID, 0 },
                { Constants.CORRELATION_ID, uncommittedEvents.CorrelationId.Value },
                { CommitConstants.COMMIT_ID, uncommittedEvents.Id.Value },
                { CommitConstants.TIMESTAMP, uncommittedEvents.Timestamp.ToUnixTimeMilliseconds() },
                { Constants.EVENTSOURCE_ID, uncommittedEvents.Source.EventSource.Value },
                { Constants.EVENT_SOURCE_ARTIFACT, uncommittedEvents.Source.Artifact.Value },
                { VersionConstants.COMMIT, uncommittedEvents.Source.Version.Commit },
                { VersionConstants.SEQUENCE, uncommittedEvents.Source.Version.Sequence },
                { CommitConstants.EVENTS, new BsonArray(eventDocs) },
            });

            return(doc);
        }
        /// <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);
        }
Exemple #16
0
 public void Store(UncommittedEventStream eventStream)
 {
     try
     {
         using (var session = _documentStore.OpenSession())
         {
             session.Advanced.UseOptimisticConcurrency = true;
             foreach (var uncommittedEvent in eventStream)
             {
                 session.Store(ToStoredEvent(eventStream.CommitId, uncommittedEvent));
             }
             session.SaveChanges();
         }
     }
     catch (Raven.Abstractions.Exceptions.ConcurrencyException)
     {
         Guid sourceId = Guid.Empty;
         long version = 0;
         if (eventStream.HasSingleSource)
         {
             sourceId = eventStream.SourceId;
             version = eventStream.Sources.Single().CurrentVersion;
         }
         throw new ConcurrencyException(sourceId, version);
     }
 }
Exemple #17
0
 private UncommittedEventStream BuildStream(Guid commitId, IEnumerable<UncommittedEvent> events)
 {
     var stream = new UncommittedEventStream(commitId);
     foreach (var evnt in events)
         stream.Append(evnt);
     return stream;
 }
Exemple #18
0
 public void Store(UncommittedEventStream eventStream)
 {
     Parallel.ForEach <Guid>(
         eventStream.Select(es => es.EventSourceId).Distinct(),
         (eventSourceId) => SaveEvents(eventSourceId, eventStream.Where(es => es.EventSourceId == eventSourceId))
         );
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="eventStream"></param>
        /// <param name="jsonSerializer"></param>
        /// <returns></returns>
        public static Commit From(UncommittedEventStream eventStream, ISerializer jsonSerializer)
        {
            var events = eventStream.Events.Select(e => new Event
            {
                Id                  = e.Id,
                CorrelationId       = e.Metadata.CorrelationId,
                EventArtifact       = e.Metadata.Artifact.Id,
                EventSourceId       = e.Metadata.EventSourceId,
                Generation          = e.Metadata.Artifact.Generation,
                EventSourceArtifact = eventStream.Source.Artifact,
                Commit              = e.Metadata.VersionedEventSource.Version.Commit,
                Sequence            = e.Metadata.VersionedEventSource.Version.Sequence,
                Occurred            = e.Metadata.Occurred.ToUnixTimeMilliseconds(),
                OriginalContext     = jsonSerializer.ToJson(OriginalContext.From(e.Metadata.OriginalContext)),
                EventData           = PropertyBagSerializer.Serialize(e.Event, jsonSerializer)
            }).ToList();

            var commit = new Commit
            {
                Id                  = 0,
                CorrelationId       = eventStream.CorrelationId,
                CommitId            = eventStream.Id,
                Timestamp           = eventStream.Timestamp.ToUnixTimeMilliseconds(),
                EventSourceId       = eventStream.Source.EventSource,
                EventSourceArtifact = eventStream.Source.Artifact,
                CommitNumber        = eventStream.Source.Version.Commit,
                Sequence            = eventStream.Source.Version.Sequence,
                Events              = events
            };

            return(commit);
        }
Exemple #20
0
 public void Store(UncommittedEventStream eventStream)
 {
     foreach (var uncommittedEvent in eventStream)
     {
         _session.Save(ToStoredEvent(eventStream.CommitId, uncommittedEvent));
     }
 }
        public void Retrieving_all_events_should_return_the_same_as_added() {
            var id=Guid.NewGuid();
            var sequenceCounter=0;

            var stream = new UncommittedEventStream(Guid.NewGuid());
            stream.Append(
                new UncommittedEvent(Guid.NewGuid(), id, sequenceCounter++, 0, DateTime.UtcNow, new CustomerCreatedEvent("Foo", 35),
                                     new Version(1, 0)));
            stream.Append(
                new UncommittedEvent(Guid.NewGuid(), id, sequenceCounter++, 0, DateTime.UtcNow,
                                     new CustomerNameChanged("Name" + sequenceCounter), new Version(1, 0)));
            stream.Append(
                new UncommittedEvent(Guid.NewGuid(), id, sequenceCounter++, 0, DateTime.UtcNow,
                                     new CustomerNameChanged("Name" + sequenceCounter), new Version(1, 0)));
            
            _store.Store(stream);

            var result=_store.ReadFrom(id, long.MinValue, long.MaxValue);
            result.Count().Should().Be(stream.Count());
            result.First().EventIdentifier.Should().Be(stream.First().EventIdentifier);
            //TODO:

            var streamList = stream.ToList();
            var resultList = result.ToList();

            for (int i = 0; i < resultList.Count; i++)
            {
                Assert.IsTrue(AreEqual(streamList[i], resultList[i]));
            }
        }
Exemple #22
0
        public void Store(UncommittedEventStream eventStream)
        {
            var commit = new MongoCommit
            {
                CommitId      = eventStream.CommitId,
                EventSourceId = eventStream.SourceId,
                FromVersion   = eventStream.InitialVersion,
                ToVersion     = eventStream.Last().EventSequence,
                Events        = eventStream.Select(e => e.EventIdentifier).ToArray(),
                Processed     = false
            };

            try
            {
                try
                {
                    SafellyInsertCommit(commit);
                    InsertEvents(eventStream);
                    MarkCommitAsProcessed(commit.CommitId);
                }
                catch
                {
                    RemoveUnprocessedCommit(commit.CommitId);
                    throw;
                }
            }
            catch (MongoSafeModeException ex)
            {
                if (ex.Message.Contains(CONCURRENCY_ERROR_CODE))
                {
                    throw new ConcurrencyException(eventStream.SourceId, -1);
                }
            }
        }
        public void Event_saving_smoke_test()
        {
            var targetStore = new RavenDBEventStore(_documentStore);
            var id = Guid.NewGuid();

            int sequenceCounter = 0;

            var events = new UncommittedEventStream(Guid.NewGuid());

            events.Append(new UncommittedEvent(Guid.NewGuid(), id, sequenceCounter++, 0, DateTime.UtcNow, new CustomerCreatedEvent("Foo",
                                                                                                                                   35),
                                               new Version(1, 0)));
            events.Append(new UncommittedEvent(Guid.NewGuid(), id, sequenceCounter++, 0, DateTime.UtcNow, new CustomerNameChanged(
                                                                                                              "Name" + sequenceCounter),
                                               new Version(1, 0)));
            events.Append(new UncommittedEvent(Guid.NewGuid(), id, sequenceCounter++, 0, DateTime.UtcNow, new CustomerNameChanged(
                                                                                                              "Name" + sequenceCounter),
                                               new Version(1, 0)));
            events.Append(new UncommittedEvent(Guid.NewGuid(), id, sequenceCounter++, 0, DateTime.UtcNow, new CustomerNameChanged(
                                                                                                              "Name" + sequenceCounter),
                                               new Version(1, 0)));
                             

            targetStore.Store(events);
        }
Exemple #24
0
        public void Retrieved_event_should_having_identical_timestamp_as_persisted()
        {
            var id     = Guid.NewGuid();
            var utcNow = DateTime.UtcNow.Date.AddHours(9).AddTicks(-1);

            var stream = new UncommittedEventStream(Guid.NewGuid());

            stream.Append(
                new UncommittedEvent(Guid.NewGuid(), id, 1, 0, utcNow, new CustomerCreatedEvent("Foo", 35),
                                     new Version(1, 0)));

            _store.Store(stream);

            using (var conn = new SQLiteConnection(_connString))
            {
                conn.Open();

                using (var cmd = new SQLiteCommand("SELECT [TimeStamp] FROM [Events]", conn))
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var timestamp = (long)reader["Timestamp"];
                            timestamp.Should().Be(utcNow.Ticks);
                        }
                    }
            }
        }
Exemple #25
0
        public void Process(CaseReported @event)
        {
            var caseReport = _caseReports.GetById(@event.Id);

            if (caseReport == null)
            {
                caseReport = new CaseReport
                {
                    Id = @event.Id,
                    DataCollectorId     = @event.DataCollectorId,
                    HealthRiskId        = @event.HealthRiskId,
                    Location            = @event.Location,
                    SubmissionTimestamp = @event.CaseOccured
                };
            }
            else
            {
                caseReport.Id = @event.Id;
                caseReport.DataCollectorId     = @event.DataCollectorId;
                caseReport.HealthRiskId        = @event.HealthRiskId;
                caseReport.Location            = @event.Location;
                caseReport.SubmissionTimestamp = @event.CaseOccured;
            }
            _caseReports.Save(caseReport);

            var disease = _healthRisks.GetById(caseReport.HealthRiskId) ?? new HealthRisk
            {
                Id = @event.HealthRiskId,
                ThresholdTimePeriodInDays = 7,
                ThresholdNumberOfCases    = 3
            };

            var latestReports = _caseReports.GetCaseReportsAfterDate(
                DateTime.UtcNow.Subtract(TimeSpan.FromDays(disease.ThresholdTimePeriodInDays)), caseReport.HealthRiskId);

            if (latestReports.Count > disease.ThresholdNumberOfCases)
            {
                var alert = _alerts.Get(caseReport.HealthRiskId, caseReport.Location);
                if (alert == null)
                {
                    alert = new Alert
                    {
                        Id           = Guid.NewGuid(),
                        HealthRiskId = caseReport.HealthRiskId,
                        Location     = caseReport.Location,
                    };
                }
                alert.CaseReports.Add(caseReport);
                _alerts.Save(alert);


                // Todo: Temporary fix - we're not supposed to do this, awaiting the new Policy building block in doLittle to be ready
                var stream = new UncommittedEventStream(null);
                stream.Append(new AlertRaised(), EventSourceVersion.Zero.NextCommit());
                _uncommittedEventStreamCoordinator.Commit(TransactionCorrelationId.New(), stream);

                _feedbackService.SendFeedbackToDataCollecorsAndVerifiers(latestReports);
            }
        }
Exemple #26
0
        void ApplyEvent(IEvent @event)
        {
            // Todo: Temporary fix - we're not supposed to do this, awaiting the new Policy building block in doLittle to be ready
            var stream = new UncommittedEventStream(null);

            stream.Append(@event, EventSourceVersion.Zero.NextCommit());
            _uncommittedEventStreamCoordinator.Commit(TransactionCorrelationId.New(), stream);
        }
 public void When_contains_multpile_events_from_same_source_should_indicate_a_single_source()
 {
     var sut = new UncommittedEventStream(Guid.NewGuid());
     var eventSourceId = Guid.NewGuid();
     sut.Append(CreateEvent(eventSourceId));
     sut.Append(CreateEvent(eventSourceId));
     Assert.IsTrue(sut.HasSingleSource);
 }
Exemple #28
0
        public void When_contains_multpile_events_from_different_sources_should_indicate_non_single_source()
        {
            var sut = new UncommittedEventStream(Guid.NewGuid());

            sut.Append(CreateEvent(Guid.NewGuid()));
            sut.Append(CreateEvent(Guid.NewGuid()));
            Assert.IsFalse(sut.HasSingleSource);
        }
        public void Store(UncommittedEventStream eventStream)
        {
            var tapeStream = new AzureTapeStream.AzureTapeStream(eventStream.SourceId.ToString(), Config.Config.Get("Eventing.AzureConnectionString"), Config.Config.Get("Eventing.AzureContainerName"));

            foreach (var record in eventStream.Select(evt => Streamer.SerializeEvent(evt.Payload as ISourcedEvent)))
            {
                tapeStream.Append(record);
            }
        }
Exemple #30
0
        private static void UpdateEventSources(UncommittedEventStream events, SQLiteTransaction transaction)
        {
            var eventSources = events.Sources;

            foreach (var eventSource in eventSources)
            {
                UpdateEventSourceVersion(eventSource, transaction);
            }
        }
Exemple #31
0
 static UncommittedEventStream build_new_uncommitted_event_stream_from(UncommittedEventStream uncommitted)
 {
     return(new UncommittedEventStream(
                uncommitted.Id,
                uncommitted.CorrelationId,
                uncommitted.Source,
                uncommitted.Timestamp,
                build_new_event_stream_from(uncommitted.Events)));
 }
        public static UncommittedEventStream BuildNext(this UncommittedEventStream eventStream, DateTimeOffset?now = null, CorrelationId correlationId = null)
        {
            Ensure.IsNotNull(nameof(eventStream), eventStream);
            Ensure.ArgumentPropertyIsNotNull("eventStream", "Source", eventStream.Source);
            var committed          = now ?? DateTimeOffset.Now;
            var eventSourceVersion = eventStream.Source.Next();

            return(BuildFrom(eventSourceVersion, committed, correlationId ?? Guid.NewGuid(), eventStream.Events));
        }
Exemple #33
0
        public void When_contains_multpile_events_from_same_source_should_indicate_a_single_source()
        {
            var sut           = new UncommittedEventStream(Guid.NewGuid());
            var eventSourceId = Guid.NewGuid();

            sut.Append(CreateEvent(eventSourceId));
            sut.Append(CreateEvent(eventSourceId));
            Assert.IsTrue(sut.HasSingleSource);
        }
Exemple #34
0
 public void Given(UncommittedEventStream history)
 {
     var historyBySources = history.GroupBy(e => e.EventSourceId);
     foreach (var sourceHistory in historyBySources)
     {
         _underTest.Add(sourceHistory.Key);
         Store(history.CommitId, sourceHistory);
     }
 }
Exemple #35
0
 public void Store(UncommittedEventStream events)
 {
     _context.WithConnection(connection =>
                             _context.WithTransaction(connection, transaction =>
     {
         SaveEventSources(events, transaction);
         SaveEvents(events, transaction);
         UpdateEventSources(events, transaction);
     }));
 }
Exemple #36
0
        public void Given(UncommittedEventStream history)
        {
            var historyBySources = history.GroupBy(e => e.EventSourceId);

            foreach (var sourceHistory in historyBySources)
            {
                _underTest.Add(sourceHistory.Key);
                Store(history.CommitId, sourceHistory);
            }
        }
Exemple #37
0
 private static void GenerateEvents()
 {
     var eventStore = new MsSqlServerEventStore(ConfigurationManager.ConnectionStrings["Main"].ConnectionString);
     for (int i = 0; i < 1000; i++)
     {
         var uncommittedEventStream = new UncommittedEventStream(Guid.NewGuid());
         uncommittedEventStream.Append(new UncommittedEvent(Guid.NewGuid(), Guid.NewGuid(), i, i, DateTime.Now, new object(), new Version(1, 0)));                
         eventStore.Store(uncommittedEventStream);
     }
 }
 public void Store(UncommittedEventStream events)
 {            
     _context.WithConnection(connection => 
     _context.WithTransaction(connection, transaction =>
     {
         SaveEventSources(events, transaction);
         SaveEvents(events, transaction);
         UpdateEventSources(events, transaction);
     }));    
 }
Exemple #39
0
        private UncommittedEventStream BuildStream(Guid commitId, IEnumerable <UncommittedEvent> events)
        {
            var stream = new UncommittedEventStream(commitId);

            foreach (var evnt in events)
            {
                stream.Append(evnt);
            }
            return(stream);
        }
Exemple #40
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);
        }
Exemple #41
0
 public JoesUnitOfWork(Guid commandId, IDomainRepository domainRepository, IStoreEvents eventStore, ISnapshotStore snapshotStore, IEventBus eventBus, ISnapshottingPolicy snapshottingPolicy)
     : base(commandId)
 {
     _eventStream = new UncommittedEventStream(commandId);
     _commitId = commandId;
     _eventStore = eventStore;
     _domainRepository = domainRepository;
     _snapshotStore = snapshotStore;
     _eventBus = eventBus;
     _snapshottingPolicy = snapshottingPolicy;
 }
Exemple #42
0
 public JoesUnitOfWork(Guid commandId, IDomainRepository domainRepository, IStoreEvents eventStore, ISnapshotStore snapshotStore, IEventBus eventBus, ISnapshottingPolicy snapshottingPolicy)
     : base(commandId)
 {
     _eventStream        = new UncommittedEventStream(commandId);
     _commitId           = commandId;
     _eventStore         = eventStore;
     _domainRepository   = domainRepository;
     _snapshotStore      = snapshotStore;
     _eventBus           = eventBus;
     _snapshottingPolicy = snapshottingPolicy;
 }
Exemple #43
0
        private static void GenerateEvents()
        {
            var eventStore = new MsSqlServerEventStore(ConfigurationManager.ConnectionStrings["Main"].ConnectionString);

            for (int i = 0; i < 1000; i++)
            {
                var uncommittedEventStream = new UncommittedEventStream(Guid.NewGuid());
                uncommittedEventStream.Append(new UncommittedEvent(Guid.NewGuid(), Guid.NewGuid(), i, i, DateTime.Now, new object(), new Version(1, 0)));
                eventStore.Store(uncommittedEventStream);
            }
        }
Exemple #44
0
 public void Store(UncommittedEventStream eventStream)
 {
     using (var stream = _store.OpenStream(eventStream.SourceId, 0, int.MaxValue))
     {
         foreach (var uncommittedEvent in eventStream)
         {
             var eventMessage = new EventMessage{ Body = uncommittedEvent.Payload };
             eventMessage.Headers["commitId"] = eventStream.CommitId;
             stream.Add(eventMessage);
         }
         //stream.CommitChanges(Guid.NewGuid());
         stream.CommitChanges(eventStream.CommitId);
     }
 }
Exemple #45
0
        private static void GenerateEventsForAggregateRoots()
        {
            const int aggregateRootCount = 10;
            var aggregateRoots = Enumerable.Range(0, aggregateRootCount).Select(x => Guid.NewGuid()).ToList();
            var random = new Random();

            var eventStore = new MsSqlServerEventStore(ConfigurationManager.ConnectionStrings["Main"].ConnectionString);
            for (int i = 0; i < 1000; i++)
            {
                Guid rootId = aggregateRoots[random.Next(aggregateRootCount)];

                var uncommittedEventStream = new UncommittedEventStream(Guid.NewGuid());
                uncommittedEventStream.Append(new UncommittedEvent(Guid.NewGuid(), rootId, i, i, DateTime.Now, new object(), new Version(1, 0)));                
            }
        }
Exemple #46
0
            public UncommittedEventStream ForSourceUncomitted(Guid id, Guid commitId, int sequenceOffset = 0)
            {                
                int initialVersion = sequenceOffset == 0 ? 1 : sequenceOffset;
                int sequence = initialVersion;

                var comittedEvents = new List<CommittedEvent>();
                var result = new UncommittedEventStream(commitId);
                foreach (var evnt in _events)
                {
                    var uncommittedEvent = new UncommittedEvent(Guid.NewGuid(), id, sequence, initialVersion, DateTime.UtcNow,
                                                            evnt, new Version(1, 0));
                    result.Append(uncommittedEvent);
                    sequence++;
                }
                return result;
            }
        public UnitOfWork(Guid commandId, IDomainRepository domainRepository, IEventStore eventStore, ISnapshotStore snapshotStore, IEventBus eventBus, ISnapshottingPolicy snapshottingPolicy) : base(commandId)
        {
            Contract.Requires<ArgumentNullException>(domainRepository != null);
            Contract.Requires<ArgumentNullException>(snapshotStore != null);
            Contract.Requires<ArgumentNullException>(eventStore != null);
            Contract.Requires<ArgumentNullException>(eventBus != null);
            Contract.Requires<ArgumentNullException>(snapshottingPolicy != null);

            _repository = domainRepository;
            _snapshottingPolicy = snapshottingPolicy;
            _eventBus = eventBus;
            _snapshotStore = snapshotStore;
            _eventStore = eventStore;
            _eventStream = new UncommittedEventStream(commandId);
            _dirtyInstances = new Queue<AggregateRoot>();
        }
 public void Save_SmokeTest()
 {
     var sequenceCounter = 0;
     var id=Guid.NewGuid();
     var stream = new UncommittedEventStream(Guid.NewGuid());
     stream.Append(
         new UncommittedEvent(Guid.NewGuid(), id, sequenceCounter++, 0, DateTime.UtcNow, new CustomerCreatedEvent("Foo", 35),
                              new Version(1, 0)));
     stream.Append(
         new UncommittedEvent(Guid.NewGuid(), id, sequenceCounter++, 0, DateTime.UtcNow,
                              new CustomerNameChanged("Name" + sequenceCounter), new Version(1, 0)));
     stream.Append(
         new UncommittedEvent(Guid.NewGuid(), id, sequenceCounter++, 0, DateTime.UtcNow,
                              new CustomerNameChanged("Name" + sequenceCounter), new Version(1, 0)));
                 
     _store.Store(stream);
 }
 private static void SaveEventSources(UncommittedEventStream events, SQLiteTransaction transaction)
 {
     var eventSources = events.Sources;
     foreach (var eventSource in eventSources)
     {
         var currentVersion = GetVersion(events.SourceId, transaction);
         if (currentVersion == null)
         {
             AddEventSource(eventSource, transaction);
         }
         else if (currentVersion.Value != eventSource.InitialVersion)
         {
             throw new ConcurrencyException(events.SourceId, eventSource.InitialVersion);
         }
     }
     
 }
Exemple #50
0
        public void Store(UncommittedEventStream eventStream)
        {
            Queue<CommittedEvent> events;
            if (eventStream.IsNotEmpty)
            {
                if (!_events.TryGetValue(eventStream.SourceId, out events))
                {
                    events = new Queue<CommittedEvent>();
                    _events.Add(eventStream.SourceId, events);
                }

                foreach (var evnt in eventStream)
                {
                    events.Enqueue(new CommittedEvent(eventStream.CommitId, evnt.EventIdentifier, eventStream.SourceId, evnt.EventSequence,
                                                      evnt.EventTimeStamp, evnt.Payload, evnt.EventVersion));
                }
            }
        }
 public void Store(UncommittedEventStream eventStream)
 {
     if (!eventStream.HasSingleSource)
     {
         throw new NotSupportedException("NoDBEventStore supports only one event source per Unit of Work.");
     }
     var sourceId = eventStream.SourceId;
     FileInfo file = sourceId.GetEventStoreFileInfo(_path);
     if (!file.Exists && !file.Directory.Exists)
         file.Directory.Create();
     try
     {
         sourceId.GetWriteLock();
         if (file.Exists)
         {
             if (GetVersion(sourceId) >= eventStream.Sources.Single().InitialVersion)
             {
                 throw new ConcurrencyException(sourceId, eventStream.Sources.Single().CurrentVersion);
             }
         }
         using (var writer = file.OpenWrite())
         {
             writer.Seek(0, SeekOrigin.End);
             var indicies = new long[eventStream.Count()];
             var i = 0;
             var index = writer.Position;
             foreach (var evnt in eventStream)
             {
                 var bytes = GetBytes(evnt);
                 writer.Write(BitConverter.GetBytes(bytes.Length), 0, 4);
                 writer.Write(bytes, 0, bytes.Length);
                 indicies[i++] = index;
                 index += bytes.Length;
             }
             UpdateEventSourceIndexFile(sourceId, indicies);
             writer.Flush();
         }
     }
     finally
     {
         sourceId.ReleaseWriteLock();
     }
 }
Exemple #52
0
        public static UncommittedEventStream Create()
        {
            var theEventSourceId = Guid.NewGuid();
            var theInitialEventSourceVersion = 0;
            var theCommitId = Guid.NewGuid();
            var theVersion = new Version(1, 0);

            int sequenceCounter = 1;

            var events = new[]
            {
                new UncommittedEvent
                (
                    Guid.NewGuid(), theEventSourceId, typeof(object), sequenceCounter++, theInitialEventSourceVersion, DateTime.Now,
                    new CustomerCreatedEvent(Guid.NewGuid(), theEventSourceId, sequenceCounter, DateTime.UtcNow, "Foo",35),
                    theVersion
                ),
                new UncommittedEvent
                (
                    Guid.NewGuid(), theEventSourceId, typeof(object), sequenceCounter++, theInitialEventSourceVersion, DateTime.Now,
                    new CustomerNameChanged(Guid.NewGuid(), theEventSourceId, sequenceCounter, DateTime.UtcNow, "Name"+sequenceCounter),
                    theVersion
                ),
                new UncommittedEvent
                (
                    Guid.NewGuid(), theEventSourceId, typeof(object), sequenceCounter++, theInitialEventSourceVersion, DateTime.Now,
                    new CustomerNameChanged(Guid.NewGuid(), theEventSourceId, sequenceCounter, DateTime.UtcNow, "Name"+sequenceCounter),
                    theVersion
                ),
                new UncommittedEvent
                (
                    Guid.NewGuid(), theEventSourceId, typeof(object), sequenceCounter++, theInitialEventSourceVersion, DateTime.Now,
                    new CustomerNameChanged(Guid.NewGuid(), theEventSourceId, sequenceCounter, DateTime.UtcNow, "Name"+sequenceCounter),
                    theVersion
                ),
            };

            var eventStream = new UncommittedEventStream(theCommitId);
            foreach (var e in events) eventStream.Append(e);

            return eventStream;
        }
        public void When_getting_all_event_from_an_existing_event_source_the_result_should_be_all_events_stored_for_that_event_source()
        {
            var eventSourceId = Guid.NewGuid();

            var stream1 = new UncommittedEventStream(Guid.NewGuid());
            stream1.Append(new UncommittedEvent(Guid.NewGuid(), eventSourceId, typeof(object), 1, 0, DateTime.UtcNow, new object(), new Version(1, 0)));
            stream1.Append(new UncommittedEvent(Guid.NewGuid(), eventSourceId, typeof(object), 2, 0, DateTime.UtcNow, new object(), new Version(1, 0)));

            var stream2 = new UncommittedEventStream(Guid.NewGuid());
            stream2.Append(new UncommittedEvent(Guid.NewGuid(), eventSourceId, typeof(object), 3, 1, DateTime.UtcNow, new object(), new Version(1, 0)));
            stream2.Append(new UncommittedEvent(Guid.NewGuid(), eventSourceId, typeof(object), 4, 1, DateTime.UtcNow, new object(), new Version(1, 0)));
            stream2.Append(new UncommittedEvent(Guid.NewGuid(), eventSourceId, typeof(object), 5, 1, DateTime.UtcNow, new object(), new Version(1, 0)));

            var store = new InMemoryEventStore();

            store.Store(stream1);
            store.Store(stream2);

            var events = store.ReadFrom(eventSourceId, typeof(object), long.MinValue, long.MaxValue);

            events.Count().Should().Be(5);
        }
        public void Retrieving_all_events_should_return_the_same_as_added()
        {
            var targetStore = new RavenDBEventStore(_documentStore);
            var id = Guid.NewGuid();

            int sequenceCounter = 0;

            var events = new UncommittedEventStream(Guid.NewGuid());

            events.Append(new UncommittedEvent(Guid.NewGuid(), id, typeof(object), sequenceCounter++, 0, DateTime.UtcNow, new CustomerCreatedEvent("Foo",
                                                                                                                                         35),
                                               new Version(1, 0)));
            events.Append(new UncommittedEvent(Guid.NewGuid(), id, typeof(object), sequenceCounter++, 0, DateTime.UtcNow, new CustomerNameChanged(
                                                                                                                    "Name" + sequenceCounter),
                                               new Version(1, 0)));
            events.Append(new UncommittedEvent(Guid.NewGuid(), id, typeof(object), sequenceCounter++, 0, DateTime.UtcNow, new CustomerNameChanged(
                                                                                                                    "Name" + sequenceCounter),
                                               new Version(1, 0)));
            events.Append(new UncommittedEvent(Guid.NewGuid(), id, typeof(object), sequenceCounter++, 0, DateTime.UtcNow, new CustomerNameChanged(
                                                                                                                    "Name" + sequenceCounter),
                                               new Version(1, 0)));

            targetStore.Store(events);

            var result = targetStore.ReadFrom(id, long.MinValue, long.MaxValue);
            result.Count().Should().Be(events.Count());
            result.First().EventIdentifier.Should().Be(events.First().EventIdentifier);

            var streamList = events.ToList();
            var resultList = result.ToList();

            for (int i = 0; i < resultList.Count; i++)
            {
                Assert.IsTrue(AreEqual(streamList[i], resultList[i]));
            }
        }
Exemple #55
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;
        }
Exemple #56
0
 public void Store(UncommittedEventStream eventStream)
 {
     Store(eventStream.CommitId, eventStream);
 }
 private static void UpdateEventSources(UncommittedEventStream events, SQLiteTransaction transaction)
 {
     var eventSources = events.Sources;
     foreach (var eventSource in eventSources)
     {
         UpdateEventSourceVersion(eventSource, transaction);
     }
 }
        public void Store(UncommittedEventStream eventStream)
        {
            var sourcePath = string.Format("{0}{1}{2}", BasePath, Path.DirectorySeparatorChar, eventStream.SourceId);

            if (!Directory.Exists(BasePath))
            {
                Directory.CreateDirectory(BasePath);
            }

            var tapeStream = new FileTapeStream.FileTapeStream(sourcePath);

            foreach (var record in eventStream.Select(evt => Streamer.SerializeEvent(evt.Payload as ISourcedEvent)))
            {
                tapeStream.Append(record);
            }
        }
        public void Store(UncommittedEventStream eventStream)
        {
            var tapeStream = new AzureTapeStream.AzureTapeStream(eventStream.SourceId.ToString(), Settings.Default.AzureConnectionString, Settings.Default.AzureContainerName);

            foreach (var record in eventStream.Select(evt => Streamer.SerializeEvent(evt.Payload as ISourcedEvent)))
            {
                tapeStream.Append(record);
            }
        }
        public void Store(UncommittedEventStream eventStream)
        {
            Parallel.ForEach<Guid>(
                eventStream.Select(es => es.EventSourceId).Distinct(),
                (eventSourceId) => SaveEvents(eventSourceId, eventStream.Where(es => es.EventSourceId == eventSourceId))
            );

        }