private void DetectDuplicate(CommitAttempt attempt)
 {
     if (_potentialDuplicates.Contains(new IdentityForDuplicationDetection(attempt)))
     {
         throw new DuplicateCommitException(String.Format(Messages.DuplicateCommitIdException, attempt.StreamId, attempt.BucketId, attempt.CommitId));
     }
 }
        private ICommit PersistCommit(CommitAttempt attempt)
        {
            Logger.Debug(Messages.AttemptingToCommit, attempt.Events.Count, attempt.StreamId, attempt.CommitSequence, attempt.BucketId);
            string streamId = attempt.StreamId.ToHash();

            return(ExecuteCommand(cmd =>
            {
                cmd.AddParameter(_dialect.BucketId, attempt.BucketId);
                cmd.AddParameter(_dialect.StreamId, streamId);
                cmd.AddParameter(_dialect.StreamIdOriginal, attempt.StreamId);
                cmd.AddParameter(_dialect.StreamRevision, attempt.StreamRevision);
                cmd.AddParameter(_dialect.Items, attempt.Events.Count);
                cmd.AddParameter(_dialect.CommitId, attempt.CommitId);
                cmd.AddParameter(_dialect.CommitSequence, attempt.CommitSequence);
                cmd.AddParameter(_dialect.CommitStamp, attempt.CommitStamp);
                cmd.AddParameter(_dialect.Headers, _serializer.Serialize(attempt.Headers));
                cmd.AddParameter(_dialect.Payload, _serializer.Serialize(attempt.Events.ToList()));
                var checkpointNumber = cmd.ExecuteScalar(_dialect.PersistCommit).ToInt();
                return new Commit(
                    attempt.BucketId,
                    attempt.StreamId,
                    attempt.StreamRevision,
                    attempt.CommitId,
                    attempt.CommitSequence,
                    attempt.CommitStamp,
                    checkpointNumber.ToString(CultureInfo.InvariantCulture),
                    attempt.Headers,
                    attempt.Events);
            }));
        }
 public ICommit Commit(CommitAttempt attempt, Int64 checkpoint)
 {
     lock (_commits)
     {
         DetectDuplicate(attempt);
         var commit = new InMemoryCommit(attempt.BucketId,
                                         attempt.StreamId,
                                         attempt.StreamRevision,
                                         attempt.CommitId,
                                         attempt.CommitSequence,
                                         attempt.CommitStamp,
                                         checkpoint,
                                         attempt.Headers,
                                         attempt.Events);
         if (_potentialConflicts.Contains(new IdentityForConcurrencyConflictDetection(commit)))
         {
             throw new ConcurrencyException();
         }
         _stamps[commit.CommitId] = commit.CommitStamp;
         _commits.Add(commit);
         _potentialDuplicates.Add(new IdentityForDuplicationDetection(commit));
         _potentialConflicts.Add(new IdentityForConcurrencyConflictDetection(commit));
         IStreamHead head = _heads.FirstOrDefault(x => x.StreamId == commit.StreamId);
         _heads.Remove(head);
         Logger.LogDebug(Resources.UpdatingStreamHead, commit.StreamId);
         int snapshotRevision = head?.SnapshotRevision ?? 0;
         _heads.Add(new StreamHead(commit.BucketId, commit.StreamId, commit.StreamRevision, snapshotRevision));
         return(commit);
     }
 }
Ejemplo n.º 4
0
        public ICommit Commit(CommitAttempt attempt)
        {
            Logger.Debug(Messages.AttemptingToCommit, attempt.Events.Count, attempt.StreamId, attempt.CommitSequence, attempt.BucketId);
            try
            {
                return(TryExecute(() =>
                {
                    var doc = attempt.ToDocumentCommit(this.Serializer);

                    var collection = this.EnsureCollection(this.Options.CommitCollectionName).Result;
                    var document = this.Client.CreateDocumentAsync(collection.SelfLink, doc).Result;

                    Logger.Debug(Messages.CommitPersisted, attempt.CommitId, attempt.BucketId);
                    SaveStreamHead(attempt.ToDocumentStreamHead());

                    return doc.ToCommit(this.Serializer);
                }));
            }
            catch (Microsoft.Azure.Documents.DocumentClientException) // TODO: verify actual exception
            {
                DocumentCommit savedCommit = LoadSavedCommit(attempt);

                if (savedCommit.CommitId == attempt.CommitId)
                {
                    throw new DuplicateCommitException();
                }

                Logger.Debug(Messages.ConcurrentWriteDetected);
                throw new ConcurrencyException();
            }
        }
        public static Task <ICommit> CommitNextAsync(
            this IPersistStreams persistence, CommitAttempt previous, CancellationToken cancellationToken)
        {
            var nextAttempt = previous.BuildNextAttempt();

            return(persistence.CommitAsync(nextAttempt, cancellationToken));
        }
Ejemplo n.º 6
0
        public virtual ICommit Commit(CommitAttempt attempt)
        {
            Logger.Debug(Messages.AttemptingToCommit, attempt.Events.Count, attempt.StreamId, attempt.CommitSequence);

            return(TryMongo(() =>
            {
                BsonDocument commitDoc = attempt.ToMongoCommit(_getNextCheckpointNumber, _serializer);
                try
                {
                    // for concurrency / duplicate commit detection safe mode is required
                    PersistedCommits.Insert(commitDoc, WriteConcern.Acknowledged);
                    UpdateStreamHeadAsync(attempt.BucketId, attempt.StreamId, attempt.StreamRevision, attempt.Events.Count);
                    Logger.Debug(Messages.CommitPersisted, attempt.CommitId);
                }
                catch (MongoException e)
                {
                    if (!e.Message.Contains(ConcurrencyException))
                    {
                        throw;
                    }
                    ICommit savedCommit = PersistedCommits.FindOne(attempt.ToMongoCommitIdQuery()).ToCommit(_serializer);
                    if (savedCommit.CommitId == attempt.CommitId)
                    {
                        throw new DuplicateCommitException();
                    }
                    Logger.Debug(Messages.ConcurrentWriteDetected);
                    throw new ConcurrencyException();
                }
                return commitDoc.ToCommit(_serializer);
            }));
        }
        public static BsonDocument ToMongoCommit(this CommitAttempt commit, Int64 checkpoint, IDocumentSerializer serializer)
        {
            int streamRevision      = commit.StreamRevision - (commit.Events.Count - 1);
            int streamRevisionStart = streamRevision;

            IEnumerable <BsonDocument> events = commit
                                                .Events
                                                .Select(e =>
                                                        new BsonDocument
            {
                { MongoCommitFields.StreamRevision, streamRevision++ },
                { MongoCommitFields.Payload, BsonDocumentWrapper.Create(typeof(EventMessage), serializer.Serialize(e)) }
            });

            var mc = new MongoCommit
            {
                CheckpointNumber   = checkpoint,
                CommitId           = commit.CommitId,
                CommitStamp        = commit.CommitStamp,
                Headers            = commit.Headers,
                Events             = new BsonArray(events),
                StreamRevisionFrom = streamRevisionStart,
                StreamRevisionTo   = streamRevision - 1,
                BucketId           = commit.BucketId,
                StreamId           = commit.StreamId,
                CommitSequence     = commit.CommitSequence
            };

            return(mc.ToBsonDocument());
        }
 public IdentityForDuplicationDetection(CommitAttempt commitAttempt)
 {
     bucketId       = commitAttempt.BucketId;
     streamId       = commitAttempt.StreamId;
     commitId       = commitAttempt.CommitId;
     commitSequence = commitAttempt.CommitSequence;
 }
        private ICommit PersistCommit(CommitAttempt attempt)
        {
            if (Logger.IsDebugEnabled)
            {
                Logger.Debug(Messages.AttemptingToCommit, attempt.Events.Count, attempt.StreamId, attempt.CommitSequence, attempt.BucketId);
            }
            string streamId = _streamIdHasher.GetHash(attempt.StreamId);

            return(ExecuteCommand((connection, cmd) =>
            {
                cmd.AddParameter(_dialect.BucketId, attempt.BucketId, DbType.AnsiString);
                cmd.AddParameter(_dialect.StreamId, streamId, DbType.AnsiString);
                cmd.AddParameter(_dialect.StreamIdOriginal, attempt.StreamId);
                cmd.AddParameter(_dialect.StreamRevision, attempt.StreamRevision);
                cmd.AddParameter(_dialect.Items, attempt.Events.Count);
                cmd.AddParameter(_dialect.CommitId, attempt.CommitId);
                cmd.AddParameter(_dialect.CommitSequence, attempt.CommitSequence);
                cmd.AddParameter(_dialect.CommitStamp, attempt.CommitStamp);
                cmd.AddParameter(_dialect.Headers, _serializer.Serialize(attempt.Headers));
                _dialect.AddPayloadParamater(_connectionFactory, connection, cmd, _serializer.Serialize(attempt.Events.ToList()));
                OnPersistCommit(cmd, attempt);
                var checkpointNumber = cmd.ExecuteScalar(_dialect.PersistCommit).ToLong();
                return new Commit(
                    attempt.BucketId,
                    attempt.StreamId,
                    attempt.StreamRevision,
                    attempt.CommitId,
                    attempt.CommitSequence,
                    attempt.CommitStamp,
                    checkpointNumber,
                    attempt.Headers,
                    attempt.Events);
            }));
        }
Ejemplo n.º 10
0
        protected override void Context()
        {
            _streamId = Guid.NewGuid().ToString();
            var commit = Persistence.Commit(_attempt = _streamId.BuildAttempt());

            _bucketId = commit.BucketId;
        }
        public static BsonDocument ToEmptyCommit(this CommitAttempt commit, Int64 checkpoint, String systemBucketName)
        {
            if (commit == null)
            {
                throw new ArgumentNullException(nameof(commit));
            }
            if (String.IsNullOrWhiteSpace(systemBucketName))
            {
                throw new ArgumentNullException(nameof(systemBucketName));
            }
            int streamRevisionStart = commit.StreamRevision - (commit.Events.Count - 1);

            var mc = new MongoCommit
            {
                CheckpointNumber   = checkpoint,
                CommitId           = commit.CommitId,
                CommitStamp        = commit.CommitStamp,
                Headers            = new Dictionary <String, Object>(),
                Events             = new BsonArray(Array.Empty <object>()),
                StreamRevisionFrom = 0,
                StreamRevisionTo   = 0,
                BucketId           = systemBucketName,
                StreamId           = systemBucketName + ".empty." + checkpoint,
                CommitSequence     = 1
            };

            return(mc.ToBsonDocument());
        }
 private void DetectDuplicate(CommitAttempt attempt)
 {
     if (_potentialDuplicates.Contains(new IdentityForDuplicationDetection(attempt)))
     {
         throw new DuplicateCommitException();
     }
 }
Ejemplo n.º 13
0
        protected override void Because()
        {
            _thrown = Catch.Exception(() =>
            {
                _streamId   = Guid.NewGuid().ToString();
                var attempt = new CommitAttempt(_streamId,
                                                2,
                                                Guid.NewGuid(),
                                                1,
                                                DateTime.Now,
                                                new Dictionary <string, object> {
                    { "key.1", "value" }
                },
                                                new List <EventMessage> {
                    new EventMessage {
                        Body = new NEventStore.Persistence.AcceptanceTests.ExtensionMethods.SomeDomainEvent {
                            SomeProperty = "Test"
                        }
                    }
                });
                Persistence.Commit(attempt);
            });

            // _persisted = Persistence.GetFrom(_streamId, 0, int.MaxValue).First();
        }
 public ICommit Commit(CommitAttempt attempt, ICheckpoint checkpoint)
 {
     lock (_commits)
     {
         DetectDuplicate(attempt);
         var commit = new InMemoryCommit(attempt.BucketId,
                                         attempt.StreamId,
                                         attempt.StreamRevision,
                                         attempt.CommitId,
                                         attempt.CommitSequence,
                                         attempt.CommitStamp,
                                         checkpoint.Value,
                                         attempt.Headers,
                                         attempt.Events,
                                         checkpoint);
         if (_commits.Any(c => c.StreamId == commit.StreamId && c.CommitSequence == commit.CommitSequence))
         {
             throw new ConcurrencyException();
         }
         _stamps[commit.CommitId] = commit.CommitStamp;
         _commits.Add(commit);
         _undispatched.Add(commit);
         IStreamHead head = _heads.FirstOrDefault(x => x.StreamId == commit.StreamId);
         _heads.Remove(head);
         Logger.Debug(Resources.UpdatingStreamHead, commit.StreamId);
         int snapshotRevision = head == null ? 0 : head.SnapshotRevision;
         _heads.Add(new StreamHead(commit.BucketId, commit.StreamId, commit.StreamRevision, snapshotRevision));
         return(commit);
     }
 }
Ejemplo n.º 15
0
        protected override void Context()
        {
            string streamId = Guid.NewGuid().ToString();

            _attempt1 = streamId.BuildAttempt();
            _attempt2 = new CommitAttempt(
                _attempt1.BucketId,         // <--- Same bucket
                _attempt1.StreamId,         // <--- Same stream it
                _attempt1.StreamRevision + 10,
                Guid.NewGuid(),
                _attempt1.CommitSequence,   // <--- Same commit seq
                DateTime.UtcNow,
                _attempt1.Headers,
                new[]
            {
                new EventMessage()
                {
                    Body = new ExtensionMethods.SomeDomainEvent {
                        SomeProperty = "Test 3"
                    }
                }
            }
                );

            Persistence.Commit(_attempt1);
        }
Ejemplo n.º 16
0
        public virtual ICommit Commit(CommitAttempt attempt)
        {
            ICommit commit;

            try
            {
                commit = PersistCommit(attempt);
                Logger.LogDebug(Messages.CommitPersisted, attempt.CommitId);
            }
            catch (Exception e)
            {
                if (!(e is UniqueKeyViolationException))
                {
                    throw;
                }

                if (DetectDuplicate(attempt))
                {
                    var msg = String.Format(Messages.DuplicateCommit, attempt.CommitId, attempt.BucketId, attempt.StreamId, attempt.CommitSequence);
                    Logger.LogInformation(msg);
                    throw new DuplicateCommitException($"{msg} inner exception: {e.Message}", e);
                }

                Logger.LogInformation(Messages.ConcurrentWriteDetected);
                throw new ConcurrencyException(e.Message, e);
            }
            return(commit);
        }
Ejemplo n.º 17
0
        public void should_persist_all_aggregate_events()
        {
            var commitId = A.RandomGuid();
            var streamId = A.RandomStreamId();
            var personAggregate =
                Person.CreateNew(A.RandomGuid()).ChangeAge(A.RandomNumber()).ChangeName(A.RandomShortString());

            var events = personAggregate.ConvertUncommitedMessagesToEventMessages();
            // commit sequence??
            var commitAttempt = new CommitAttempt(streamId, commitId, events);

            var fixture = new CommitFixture();

            var act = fixture.Commit(commitAttempt);
            act();

            var eventsFromDb = fixture.GetEvents();
            eventsFromDb.Should().HaveCount(events.Count());

            foreach (var eventLogRecord in eventsFromDb)
            {
                events.Should()
                    .Contain(
                        x =>
                            x.BodyType == eventLogRecord.EventType
                            && ReflectionHelper.PublicInstancePropertiesEqual(
                                x.BodyType,
                                x.Body,
                                eventLogRecord.DomainEvent));
            }
        }
Ejemplo n.º 18
0
        public static BsonDocument ToMongoCommit(this CommitAttempt commit, Func <int> getNextCheckpointNumber, IDocumentSerializer serializer)
        {
            int streamRevision = commit.StreamRevision - (commit.Events.Count - 1);
            IEnumerable <BsonDocument> events = commit
                                                .Events
                                                .Select(e =>
                                                        new BsonDocument
            {
                { "StreamRevision", streamRevision++ },
                { "Payload", new BsonDocumentWrapper(typeof(EventMessage), serializer.Serialize(e)) }
            });

            return(new BsonDocument
            {
                { MongoFields.Id, new BsonDocument
                  {
                      { MongoFields.BucketId, commit.BucketId },
                      { MongoFields.StreamId, commit.StreamId },
                      { MongoFields.CommitSequence, commit.CommitSequence }
                  } },
                { MongoFields.CommitId, commit.CommitId },
                { MongoFields.CommitStamp, commit.CommitStamp },
                { MongoFields.CheckpointNumber, getNextCheckpointNumber() },
                { MongoFields.Headers, BsonDocumentWrapper.Create(commit.Headers) },
                { MongoFields.Events, new BsonArray(events) },
                { MongoFields.Dispatched, false }
            });
        }
Ejemplo n.º 19
0
        public static BsonDocument ToMongoCommit(this CommitAttempt commit, LongCheckpoint checkpoint, IDocumentSerializer serializer)
        {
            int streamRevision                = commit.StreamRevision - (commit.Events.Count - 1);
            int streamRevisionStart           = streamRevision;
            IEnumerable <BsonDocument> events = commit
                                                .Events
                                                .Select(e =>
                                                        new BsonDocument
            {
                { MongoCommitFields.StreamRevision, streamRevision++ },
                { MongoCommitFields.Payload, new BsonDocumentWrapper(typeof(EventMessage), serializer.Serialize(e)) }
            });

            return(new BsonDocument
            {
                { MongoCommitFields.CheckpointNumber, checkpoint.LongValue },
                { MongoCommitFields.CommitId, commit.CommitId },
                { MongoCommitFields.CommitStamp, commit.CommitStamp },
                { MongoCommitFields.Headers, BsonDocumentWrapper.Create(commit.Headers) },
                { MongoCommitFields.Events, new BsonArray(events) },
                { MongoCommitFields.Dispatched, false },
                { MongoCommitFields.StreamRevisionFrom, streamRevisionStart },
                { MongoCommitFields.StreamRevisionTo, streamRevision - 1 },
                { MongoCommitFields.BucketId, commit.BucketId },
                { MongoCommitFields.StreamId, commit.StreamId },
                { MongoCommitFields.CommitSequence, commit.CommitSequence }
            });
        }
        public static BsonDocument ToMongoCommit_original(this CommitAttempt commit, Int64 checkpoint, IDocumentSerializer serializer)
        {
            int streamRevision                = commit.StreamRevision - (commit.Events.Count - 1);
            int streamRevisionStart           = streamRevision;
            IEnumerable <BsonDocument> events = commit
                                                .Events
                                                .Select(e =>
                                                        new BsonDocument
            {
                { MongoCommitFields.StreamRevision, streamRevision++ },
                { MongoCommitFields.Payload, BsonDocumentWrapper.Create(typeof(EventMessage), serializer.Serialize(e)) }
            });

            //var dictionarySerialize = new DictionaryInterfaceImplementerSerializer<Dictionary<string, object>>(DictionaryRepresentation.ArrayOfArrays);
            //var dicSer = BsonSerializer.LookupSerializer<Dictionary<string, object>>();

            return(new BsonDocument
            {
                { MongoCommitFields.CheckpointNumber, checkpoint },
                { MongoCommitFields.CommitId, commit.CommitId },
                { MongoCommitFields.CommitStamp, commit.CommitStamp },
                { MongoCommitFields.Headers, BsonDocumentWrapper.Create(commit.Headers) },
                { MongoCommitFields.Events, new BsonArray(events) },
                { MongoCommitFields.StreamRevisionFrom, streamRevisionStart },
                { MongoCommitFields.StreamRevisionTo, streamRevision - 1 },
                { MongoCommitFields.BucketId, commit.BucketId },
                { MongoCommitFields.StreamId, commit.StreamId },
                { MongoCommitFields.CommitSequence, commit.CommitSequence }
            });
        }
Ejemplo n.º 21
0
        /// <summary>
        /// When persisting a commit (The Database should not exists or be empty)
        /// </summary>
        protected override void Because()
        {
            var streamId = Guid.NewGuid().ToString();

            expectedAttempt = streamId.BuildAttempt();
            Persistence.Commit(expectedAttempt);
        }
        public static CommitAttempt BuildNextAttempt(this CommitAttempt commit)
        {
            var messages = new List <EventMessage>
            {
                new EventMessage {
                    Body = new SomeDomainEvent {
                        SomeProperty = "Another test"
                    }
                },
                new EventMessage {
                    Body = new SomeDomainEvent {
                        SomeProperty = "Another test2"
                    }
                },
            };

            return(new CommitAttempt(commit.BucketId,
                                     commit.StreamId,
                                     commit.StreamRevision + 2,
                                     Guid.NewGuid(),
                                     commit.CommitSequence + 1,
                                     commit.CommitStamp.AddSeconds(1),
                                     new Dictionary <string, object>(),
                                     messages));
        }
Ejemplo n.º 23
0
        public virtual ICommit Commit(CommitAttempt attempt)
        {
            ICommit commit;

            try
            {
                commit = PersistCommit(attempt);
                Logger.Debug(Messages.CommitPersisted, attempt.CommitId);
            }
            catch (Exception e)
            {
                if (!(e is UniqueKeyViolationException))
                {
                    throw;
                }

                if (DetectDuplicate(attempt))
                {
                    Logger.Info(Messages.DuplicateCommit);
                    throw new DuplicateCommitException(e.Message, e);
                }

                Logger.Info(Messages.ConcurrentWriteDetected);
                throw new ConcurrencyException(e.Message, e);
            }
            return(commit);
        }
Ejemplo n.º 24
0
        public static Task <ICommit> CommitSingle(this IPersistStreams persistence, string streamId = null, DateTime?now = null)
        {
            CommitAttempt commitAttempt = (streamId ?? Guid.NewGuid().ToString())
                                          .BuildAttempt(now: now);

            return(persistence.Commit(commitAttempt));
        }
 public virtual ICommit Commit(CommitAttempt attempt)
 {
     Logger.Debug(Messages.AttemptingToCommit, attempt.Events.Count, attempt.StreamId, attempt.CommitSequence, attempt.BucketId);
     try
     {
         return(TryRaven(() =>
         {
             var doc = attempt.ToRavenCommit(_serializer);
             using (TransactionScope scope = OpenCommandScope())
                 using (IDocumentSession session = _store.OpenSession())
                 {
                     session.Advanced.UseOptimisticConcurrency = true;
                     session.Store(doc);
                     session.SaveChanges();
                     scope.Complete();
                 }
             Logger.Debug(Messages.CommitPersisted, attempt.CommitId, attempt.BucketId);
             SaveStreamHead(attempt.ToRavenStreamHead());
             return doc.ToCommit(_serializer);
         }));
     }
     catch (Raven.Abstractions.Exceptions.ConcurrencyException)
     {
         RavenCommit savedCommit = LoadSavedCommit(attempt);
         if (savedCommit.CommitId == attempt.CommitId)
         {
             throw new DuplicateCommitException();
         }
         Logger.Debug(Messages.ConcurrentWriteDetected);
         throw new ConcurrencyException();
     }
 }
Ejemplo n.º 26
0
 public static IMongoQuery ToMongoCommitIdQuery(this CommitAttempt commit)
 {
     return(Query.And(
                Query.EQ(MongoCommitFields.BucketId, commit.BucketId),
                Query.EQ(MongoCommitFields.StreamId, commit.StreamId),
                Query.EQ(MongoCommitFields.CommitSequence, commit.CommitSequence)
                ));
 }
        public virtual ICommit Commit(CommitAttempt attempt)
        {
            Logger.Debug(Messages.AttemptingToCommit, attempt.Events.Count, attempt.StreamId, attempt.CommitSequence);

            return(_options.ServerSideOptimisticLoop ?
                   PersistWithServerSideOptimisticLoop(attempt) :
                   PersistWithClientSideOptimisticLoop(attempt));
        }
 public ICommit Commit(CommitAttempt attempt)
 {
     Stopwatch clock = Stopwatch.StartNew();
     ICommit commit = _persistence.Commit(attempt);
     clock.Stop();
     _counters.CountCommit(attempt.Events.Count, clock.ElapsedMilliseconds);
     return commit;
 }
Ejemplo n.º 29
0
        public virtual void Write(CommitAttempt attempt)
        {
            if (!attempt.IsValid() || !attempt.IsEmpty())
                return;

            this.ThrowOnDuplicateOrConcurrentWrites(attempt);
            this.PersistAndDispatch(attempt);
        }
Ejemplo n.º 30
0
        protected override async Task Context()
        {
            _now = SystemTimeProvider.UtcNow.AddYears(1);
            _streamId = Guid.NewGuid().ToString();
            _attempt = _streamId.BuildAttempt(_now);

            await Persistence.Commit(_attempt);
        }
Ejemplo n.º 31
0
        protected override void Context()
        {
            _now      = SystemTime.UtcNow.AddYears(1);
            _streamId = Guid.NewGuid().ToString();
            _attempt  = _streamId.BuildAttempt(_now);

            Persistence.Commit(_attempt);
        }
Ejemplo n.º 32
0
        protected override void Context()
        {
            string        streamId          = Guid.NewGuid().ToString();
            CommitAttempt successfulAttempt = streamId.BuildAttempt();

            Persistence.Commit(successfulAttempt);
            _failedAttempt = streamId.BuildAttempt();
        }
Ejemplo n.º 33
0
        protected override async Task Context()
        {
            _now      = SystemTimeProvider.UtcNow.AddYears(1);
            _streamId = Guid.NewGuid().ToString();
            _attempt  = _streamId.BuildAttempt(_now);

            await Persistence.Commit(_attempt);
        }
Ejemplo n.º 34
0
        protected override void Context()
        {
            _streamId = Guid.NewGuid().ToString();
            DateTime now = SystemTime.UtcNow;

            Persistence.Commit(_streamId.BuildAttempt(now, _bucketAId));
            _attemptACommitStamp = Persistence.GetFrom(_bucketAId, _streamId, 0, int.MaxValue).First().CommitStamp;
            _attemptForBucketB   = _streamId.BuildAttempt(now.Subtract(TimeSpan.FromDays(1)), _bucketBId);
        }
Ejemplo n.º 35
0
        private void PersistAndDispatch(CommitAttempt attempt)
        {
            this.persistence.Persist(attempt);

            var commit = attempt.ToCommit();
            this.dispatcher.Dispatch(commit);

            this.commitIdentifiers.Add(commit.CommitId);
            this.streamHeads[commit.StreamId] = commit;
        }
Ejemplo n.º 36
0
 protected override Task Context()
 {
     _streamId = Guid.NewGuid().ToString();
     var attempt = new CommitAttempt(_streamId,
         2,
         Guid.NewGuid(),
         1,
         DateTime.Now,
         new Dictionary<string, object> { { "key.1", "value" } },
         new List<EventMessage> { new EventMessage { Body = new ExtensionMethods.SomeDomainEvent { SomeProperty = "Test" } } });
     return Persistence.Commit(attempt);
 }
Ejemplo n.º 37
0
 public void Store(AggregateRoot root, Guid commandId)
 {
     var commitAttempt = new CommitAttempt
                             {
                                 CommitId = commandId,
                                 PreviousCommitSequence = (int)root.InitialVersion,
                                 StreamRevision = (int)root.Version,
                                 StreamId = root.EventSourceId
                             };
     commitAttempt.Events.AddRange(root.GetUncommittedEvents().Select(x => new EventMessage
                                                                               {
                                                                                   Body = x
                                                                               }));
     _eventStore.Write(commitAttempt);
 }
        public ICommit Commit(CommitAttempt attempt)
        {
            using (var transaction = this._db.BeginTransaction())
            {
                this.CreateNewAggregates(attempt);

                foreach (var eventMessage in attempt.Events)
                {
                    this.InsertEventMessage(attempt, eventMessage);
                }

                this.UpdateAggregatesVersion(attempt);

                transaction.Commit();
            }

            return null;
        }
Ejemplo n.º 39
0
        public void if_aggregate_dont_exist_should_create_aggregate_record()
        {
            var commitId = A.RandomGuid();
            var streamId = A.RandomStreamId();
            var aggregateId = A.RandomGuid();
            var personAggregate =
                Person.CreateNew(aggregateId).ChangeAge(A.RandomNumber()).ChangeName(A.RandomShortString());

            var events = personAggregate.ConvertUncommitedMessagesToEventMessages();

            var commitAttempt = new CommitAttempt(streamId, commitId, events);

            var fixture = new CommitFixture();

            var act = fixture.Commit(commitAttempt);
            act();

            var aggregateFromDb = fixture.GetAggregateRecord(aggregateId);
            aggregateFromDb.Should().NotBeNull();
        }
Ejemplo n.º 40
0
        public void aggregates_should_have_updated_version()
        {
            var commitId = A.RandomGuid();
            var streamId = A.RandomStreamId();
            var aggregateId = A.RandomGuid();
            var personAggregate =
                Person.CreateNew(aggregateId).ChangeAge(A.RandomNumber()).ChangeName(A.RandomShortString());

            var events = personAggregate.ConvertUncommitedMessagesToEventMessages();

            var commitAttempt = new CommitAttempt(streamId, commitId, events);

            var fixture = new CommitFixture();

            var act = fixture.Commit(commitAttempt);
            act();

            var aggregateFromDb = fixture.GetAggregateRecord(aggregateId);
            aggregateFromDb.Version.Should().Be(personAggregate.Version);
        }
Ejemplo n.º 41
0
        protected override async Task Context()
        {
            _now = UtcNow.AddYears(1);

            var commitToBucketA = Guid.NewGuid().ToString().BuildAttempt(_now.AddSeconds(1), _bucketAId);

            await Persistence.Commit(commitToBucketA);
			await Persistence.Commit(commitToBucketA = commitToBucketA.BuildNextAttempt());
			await Persistence.Commit(commitToBucketA = commitToBucketA.BuildNextAttempt());
			await Persistence.Commit(commitToBucketA.BuildNextAttempt());

            _commitToBucketB = Guid.NewGuid().ToString().BuildAttempt(_now.AddSeconds(1), _bucketBId);

			await Persistence.Commit(_commitToBucketB);
        }
Ejemplo n.º 42
0
        private void ThrowOnDuplicateOrConcurrentWrites(CommitAttempt attempt)
        {
            if (this.commitIdentifiers.Contains(attempt.CommitId))
                throw new DuplicateCommitException();

            Commit previousCommitForStream;
            if (!this.streamHeads.TryGetValue(attempt.StreamId, out previousCommitForStream))
                return;

            if (previousCommitForStream.CommitSequence > attempt.PreviousCommitSequence)
                throw new ConcurrencyException();

            if (previousCommitForStream.StreamRevision > attempt.PreviousStreamRevision)
                throw new ConcurrencyException();

            if (previousCommitForStream.CommitSequence < attempt.PreviousCommitSequence)
                throw new PersistenceException();

            if (previousCommitForStream.StreamRevision < attempt.PreviousStreamRevision)
                throw new PersistenceException();
        }
Ejemplo n.º 43
0
        public async Task can_commit()
        {
            const int bodyLength = 100000;
            var attempt = new CommitAttempt(
                Bucket.Default,
                Guid.NewGuid().ToString(),
                1,
                Guid.NewGuid(),
                1,
                DateTime.UtcNow,
                new Dictionary<string, object>(),
                new List<EventMessage> { new EventMessage { Body = new string('a', bodyLength) } });
            await Persistence.Commit(attempt);

            ICommit commits = await (Persistence.GetFrom()).Single();
            commits.Events.Single().Body.ToString().Length.Should().Be(bodyLength);
        }
Ejemplo n.º 44
0
        protected override async Task Context()
        {
            string streamId = Guid.NewGuid().ToString();
            _attempt1 = streamId.BuildAttempt();
            _attempt2 = new CommitAttempt(
                _attempt1.BucketId,         // <--- Same bucket
                _attempt1.StreamId,         // <--- Same stream it
                _attempt1.StreamRevision +10,
                Guid.NewGuid(),
                _attempt1.CommitSequence,   // <--- Same commit seq
                DateTime.UtcNow,
                _attempt1.Headers,
                new[]
                {
                    new EventMessage(){ Body = new ExtensionMethods.SomeDomainEvent {SomeProperty = "Test 3"}}
                }
            );

            await Persistence.Commit(_attempt1);
        }
Ejemplo n.º 45
0
 protected override async Task Context()
 {
     string streamId = Guid.NewGuid().ToString();
     CommitAttempt successfulAttempt = streamId.BuildAttempt();
     await Persistence.Commit(successfulAttempt);
     _failedAttempt = streamId.BuildAttempt();
 }
 public ICommit Commit(CommitAttempt attempt)
 {
     return _original.Commit(attempt);
 }
 public ICommit Commit(CommitAttempt attempt)
 {
     return underlying.Commit(EmulateSerializationDeserialization(attempt));
 }
 private CommitAttempt EmulateSerializationDeserialization(CommitAttempt attempt)
 {
     // serialization
     var headersPayload = serializer.Serialize(attempt.Headers);
     var eventsPayload = serializer.Serialize(attempt.Events.ToList());
     // deserialization
     var headers = serializer.Deserialize<Dictionary<string, object>>(headersPayload);
     var events = serializer.Deserialize<List<EventMessage>>(eventsPayload);
     return new CommitAttempt(
         attempt.BucketId,
         attempt.StreamId,
         attempt.StreamRevision,
         attempt.CommitId,
         attempt.CommitSequence,
         attempt.CommitStamp,
         headers,
         events);
 }
 public override bool PreCommit(CommitAttempt attempt)
 {
     // Can easily do logging or other such activities here
     return true; // true == allow commit to continue, false = stop.
 }
Ejemplo n.º 50
0
 protected override async Task Context()
 {
     _streamId = Guid.NewGuid().ToString();
     DateTime now = UtcNow;
     await Persistence.Commit(_streamId.BuildAttempt(now, _bucketAId));
     _attemptACommitStamp = (await Persistence.GetFrom(_bucketAId, _streamId, 0, int.MaxValue).First()).CommitStamp;
     _attemptForBucketB = _streamId.BuildAttempt(now.Subtract(TimeSpan.FromDays(1)), _bucketBId);
 }
Ejemplo n.º 51
0
        protected override async Task Context()
        {
            _streamId = Guid.NewGuid().ToString();

            _now = UtcNow.AddYears(1);
            _first = _streamId.BuildAttempt(now:_now.AddSeconds(1));
            await Persistence.Commit(_first);

            _second = await Persistence.CommitNext(_first);
            _third = await Persistence.CommitNext(_second);
            await Persistence.CommitNext(_third);
        }
Ejemplo n.º 52
0
 public RavenCommit(CommitAttempt attempt)
     : this(attempt.ToCommit())
 {
 }
Ejemplo n.º 53
0
 protected override async Task Context()
 {
     var commit = await Persistence.CommitSingle();
     _attemptTwice = new CommitAttempt(
         commit.BucketId,
         commit.StreamId,
         commit.StreamRevision,
         commit.CommitId,
         commit.CommitSequence,
         commit.CommitStamp,
         commit.Headers,
         commit.Events);
 }
 public IdentityForDuplicationDetection(CommitAttempt commitAttempt)
 {
     bucketId = commitAttempt.BucketId;
     streamId = commitAttempt.StreamId;
     commitId = commitAttempt.CommitId;
     commitSequence = commitAttempt.CommitSequence;
 }
 public ICommit Commit(CommitAttempt attempt, ICheckpoint checkpoint)
 {
     lock (_commits)
     {
         DetectDuplicate(attempt);
         var commit = new InMemoryCommit(attempt.BucketId,
             attempt.StreamId,
             attempt.StreamRevision,
             attempt.CommitId,
             attempt.CommitSequence,
             attempt.CommitStamp,
             checkpoint.Value,
             attempt.Headers,
             attempt.Events,
             checkpoint);
         if (_potentialConflicts.Contains(new IdentityForConcurrencyConflictDetection(commit)))
         {
             throw new ConcurrencyException();
         }
         _stamps[commit.CommitId] = commit.CommitStamp;
         _commits.Add(commit);
         _potentialDuplicates.Add(new IdentityForDuplicationDetection(commit));
         _potentialConflicts.Add(new IdentityForConcurrencyConflictDetection(commit));
         _undispatched.Add(commit);
         IStreamHead head = _heads.FirstOrDefault(x => x.StreamId == commit.StreamId);
         _heads.Remove(head);
         Logger.Debug(Resources.UpdatingStreamHead, commit.StreamId);
         int snapshotRevision = head == null ? 0 : head.SnapshotRevision;
         _heads.Add(new StreamHead(commit.BucketId, commit.StreamId, commit.StreamRevision, snapshotRevision));
         return commit;
     }
 }
 private void DetectDuplicate(CommitAttempt attempt)
 {
     if (_potentialDuplicates.Contains(new IdentityForDuplicationDetection(attempt)))
     {
         throw new DuplicateCommitException();
     }
 }
Ejemplo n.º 57
0
 protected override async Task Context()
 {
     ICommit commit = await Persistence.CommitSingle();
     _attemptWithSameRevision = commit.StreamId.BuildAttempt();
 }
 public ICommit Commit(CommitAttempt attempt)
 {
     ThrowWhenDisposed();
     Logger.Debug(Resources.AttemptingToCommit, attempt.CommitId, attempt.StreamId, attempt.CommitSequence);
     return this[attempt.BucketId].Commit(attempt, new LongCheckpoint(Interlocked.Increment(ref _checkpoint)));
 }
 protected override void OnPersistCommit(IDbStatement cmd, CommitAttempt attempt)
 {
     _raisedCommand = cmd;
     _raisedCommitAttempt = attempt;
 }
 public override Task<bool> PreCommit(CommitAttempt attempt)
 {
     // Can easily do logging or other such activities here
     return Task.FromResult(true); // true == allow commit to continue, false = stop.
 }