protected override void Context()
        {
            _alreadyCommitted = BuildCommitStub(HeadStreamRevision, HeadCommitSequence);
            _beyondEndOfStream = BuildCommitAttemptStub(BeyondEndOfStreamRevision, HeadCommitSequence + 1);

            Hook.PostCommit(_alreadyCommitted);
        }
 public override void PostCommit(ICommit committed)
 {
     if (committed != null)
     {
         _scheduler.ScheduleDispatch(committed);
     }
 }
 public override ICommit Select(ICommit committed)
 {
     bool converted = false;
     var eventMessages = committed
         .Events
         .Select(eventMessage =>
         {
             object convert = Convert(eventMessage.Body);
             if (ReferenceEquals(convert, eventMessage.Body))
             {
                 return eventMessage;
             }
             converted = true;
             return new EventMessage { Headers = eventMessage.Headers, Body = convert };
         })
         .ToList();
     if (!converted)
     {
         return committed;
     }
     return new Commit(committed.BucketId,
         committed.StreamId,
         committed.StreamRevision,
         committed.CommitId,
         committed.CommitSequence,
         committed.CommitStamp,
         committed.CheckpointToken,
         committed.Headers,
         eventMessages);
 }
 public void Dispatch(ICommit commit)
 {
     foreach (var e in commit.Events.Select(x=>x.Body))
     {
         EventPublisher.Publish(e as IEvent);
     }
 }
Example #5
0
        public void Save(ICommit commit) {
            if (commit == null)
                throw new ArgumentNullException("commit");

            var id = Serializer.Serialize(commit.Id);
            var value = Serializer.Serialize(commit);

            using (var connection = DbConnectionFactory.CreateOpenConnection())
            using (var trans = connection.BeginTransaction(IsolationLevel.Serializable))
            using (var command = connection.CreateCommand()) {
                command.Transaction = trans;
                command.CommandText = "INSERT INTO SqlCommits (Id, Value) VALUES (@Id, @Value)";
                command.Parameters.Add(command.CreateParameter());
                command.Parameters[0].ParameterName = "Id";
                command.Parameters[0].Value = id;
                command.Parameters.Add(command.CreateParameter());
                command.Parameters[1].ParameterName = "Value";
                command.Parameters[1].Value = value;

                if (command.ExecuteNonQuery() == 0)
                    throw new InvalidOperationException("Failed to insert a row");

                trans.Commit();
            }
        }
 public static void DispatchCommit(IPublisher bus, ICommit commit)
 {
     foreach (var @event in commit.Events)
     {
         bus.Publish(@event.Body);
     }
 }
            protected override Task Context()
            {
                _alreadyCommitted = BuildCommitStub(HeadStreamRevision, HeadCommitSequence);
                _beyondEndOfStream = BuildCommitAttemptStub(HeadStreamRevision + 1, BeyondEndOfStreamCommitSequence);

                return Hook.PostCommit(_alreadyCommitted);
            }
Example #8
0
 private void ValidateCommitStamp(ICommit commit)
 {
     if (commit.CommitStamp.AddSeconds(-2) > CommitStampProcessed)
     {
         throw new Exception(string.Format("Commit {0} {1} marked with checkpoint can not be found", CommitIdProcessed, CommitStampProcessed));
     }
 }
Example #9
0
        public void Apply(ICommit commit) {
            foreach (var addObject in commit.AddedPocos) {
                Server.MetaStore.AddNew(addObject.Meta);
                Server.IndexManager.NotifyMetaChange(addObject.Meta);
            }

            foreach (var propertySet in commit.UpdatedPocos) {
                var meta = Server.MetaStore.GetWritable(propertySet.Key);
                foreach (var setProperty in propertySet) {
                    meta.Properties[setProperty.Property] = setProperty.Value;
                }

                Server.MetaStore.Update(meta);
            }

            foreach (var addToCollection in commit.CollectionAdditions) {
                var meta = Server.MetaStore.GetWritable(addToCollection.CollectionId);
                meta.Collection.Add(addToCollection.Value);

                Server.MetaStore.Update(meta);
            }

            foreach (var removeFromCollection in commit.CollectionRemovals) {
                var meta = Server.MetaStore.GetWritable(removeFromCollection.CollectionId);
                meta.Collection.Remove(removeFromCollection.Value);

                Server.MetaStore.Update(meta);
            }
        }
 public void Dispatch(ICommit commit)
 {
     foreach (var eventMessage in commit.Events)
     {
         var msg = (IMessage) eventMessage.Body;
         _bus.Publish(msg);
     }
 }
 public override void ScheduleDispatch(ICommit commit)
 {
     if (!Started)
     {
         throw new InvalidOperationException(Messages.SchedulerNotStarted);
     }
     Logger.Info(Resources.SchedulingDelivery, commit.CommitId);
     _queue.Add(commit);
 }
Example #12
0
        public void OnNext(ICommit value)
        {
            foreach (var ev in value.Events)
            {
                var @event = ConvertEventMessageToEvent(ev);

                Send(@event);
            }
        }
 public CommitModel(ICommit commit)
 {
     this.Sequence = commit.CommitSequence;
     this.CheckPoint = commit.CheckpointToken;
     this.Date = commit.CommitStamp;
     this.CommitId = commit.CommitId;
     this.Headers = commit.Headers;
     Events = commit.Events.ToList();
 }
 public virtual void ScheduleDispatch(ICommit commit)
 {
     if (!Started)
     {
         throw new InvalidOperationException(Messages.SchedulerNotStarted);
     }
     DispatchImmediately(commit);
     MarkAsDispatched(commit);
 }
 public override void PostCommit(ICommit committed)
 {
     Logger.DebugFormat(
         "New commit {0} on tenant {1}",
         committed.CheckpointToken,
         TenantAccessor.Current.Id
     );
     Updater.Update();
 }
        protected override async Task Context()
        {
            _process1 = new AcceptanceTestMongoPersistenceFactory().Build();
            await _process1.Initialize();
            _commit1 = await _process1.Commit(Guid.NewGuid().ToString().BuildAttempt());

            _process2 = new AcceptanceTestMongoPersistenceFactory().Build();
            await _process2.Initialize();
        }
 public void Dispatch(ICommit commit)
 {
     foreach (var header in commit.Headers)
     {
         if (header.Key.StartsWith("UndispatchedMessage."))
         {
             _bus.Send(header.Value);
         }
     }
 }
        protected override void Context()
        {
            _commits = new[]
            {
                _firstCommit = CommitHelper.Create(),
                _lastCommit = CommitHelper.Create()
            };

            A.CallTo(() => _persistence.GetUndispatchedCommits()).Returns(_commits);
        }
        public override void PostCommit(ICommit committed)
        {
            if (!committed.Headers.ContainsKey("AggregateType"))
                return;

            var type = (string)committed.Headers["AggregateType"];
            if (type != DocumentTypeName)
                return;

            HandleDocumentCreation(committed);
        }
Example #20
0
        public ICommit Select(ICommit committed)
        {
            var eventConversionRunner = _eventConversionRunnerFactory();

            foreach (var eventMessage in committed.Events)
            {
                eventMessage.Body = eventConversionRunner.Run(eventMessage.Body);
            }

            return committed;
        }
 private void MarkAsDispatched(ICommit commit)
 {
     try
     {
         Logger.Info(Resources.MarkingCommitAsDispatched, commit.CommitId);
         _persistence.MarkCommitAsDispatched(commit);
     }
     catch (ObjectDisposedException)
     {
         Logger.Warn(Resources.UnableToMarkDispatched, commit.CommitId);
     }
 }
Example #22
0
 public void Set(ICommit commit)
 {
     if (commit == null)
     {
         CommitIdProcessed = null;
         CommitStampProcessed = null;
     }
     else
     {
         CommitIdProcessed = commit.CommitId;
         CommitStampProcessed = commit.CommitStamp;
     }
 }
 private void DispatchImmediately(ICommit commit)
 {
     try
     {
         Logger.Info(Resources.SchedulingDispatch, commit.CommitId);
         _dispatcher.Dispatch(commit);
     }
     catch
     {
         Logger.Error(Resources.UnableToDispatch, _dispatcher.GetType(), commit.CommitId);
         throw;
     }
 }
        public void Dispatch(ICommit commit)
        {
            foreach (var @event in commit.Events.Where(x => x.Body is IDomainEvent))
            {
                var tmp = @event;

                this.Info(() => string.Format("Attempting to dispatch event: {0}", tmp));

                _bus.Publish(@event.Body);

                this.Info(() => string.Format("Successfully dispatched event: {0}", tmp));                
            }
        }
        protected override void Context()
        {
            _date = DateTime.Now;
            _commit = new Commit(Bucket.Default, streamId, 1, Guid.NewGuid(), 1, DateTime.Now, new LongCheckpoint(0).Value, null, null);

            _hook1 = A.Fake<IPipelineHook>();
            A.CallTo(() => _hook1.Select(_commit)).Returns(_commit);
            pipelineHooks.Add(_hook1);

            _hook2 = A.Fake<IPipelineHook>();
            A.CallTo(() => _hook2.Select(_commit)).Returns(_commit);
            pipelineHooks.Add(_hook2);

            A.CallTo(() => persistence.GetFrom(Bucket.Default, _date)).Returns(new List<ICommit> { _commit });
        }
Example #26
0
 private static void DispatchCommit(ICommit commit)
 {
     // This is where we'd hook into our messaging infrastructure, such as NServiceBus,
     // MassTransit, WCF, or some other communications infrastructure.
     // This can be a class as well--just implement IDispatchCommits.
     try
     {
         foreach (var @event in commit.Events)
             Console.WriteLine(Resources.MessagesDispatched + ((SomeDomainEvent)@event.Body).Value);
     }
     catch (Exception)
     {
         Console.WriteLine(Resources.UnableToDispatch);
     }
 }
        void HandleDocumentCreation(ICommit committed)
        {
            var docCreated = committed.Events
                .Where(x => x.Body is DocumentDescriptorInitialized)
                .Select(x => (DocumentDescriptorInitialized) x.Body)
                .FirstOrDefault();

            if (docCreated != null)
            {
                _handleWriter.Promise(
                    docCreated.HandleInfo.Handle,
                    committed.CheckpointToken
                );
            }
        }
 public void SetDispatched(ICommit commit)
 {
     try
     {
         if (_messageTracker.Dispatched(commit.CommitId, DateTime.UtcNow))
         {
             if (commit.Headers.ContainsKey("reply-to"))
             {
                 //_bus.Publish(new CommitProjected(
                 //    commit.Headers["reply-to"].ToString(),
                 //    commit.CommitId,
                 //    "readmodel"
                 //    ));
             }
         }
     }
     catch (Exception ex)
     {
         Logger.Error("Commit status update failed", ex);
     }
 }
            protected override Task Context()
            {
                _date = DateTime.Now;
                _commit = new Commit(Bucket.Default, streamId, 1, Guid.NewGuid(), 1, DateTime.Now, new LongCheckpoint(0).Value, null, null);

                //_hook1 = A.Fake<IPipelineHook>();
                //A.CallTo(() => _hook1.Select(_commit)).Returns(_commit);
                _hook1 = Substitute.For<IPipelineHook>();
                _hook1.Select(_commit).Returns(_commit);
                pipelineHooks.Add(_hook1);

                //_hook2 = A.Fake<IPipelineHook>();
                //A.CallTo(() => _hook2.Select(_commit)).Returns(_commit);
                _hook2 = Substitute.For<IPipelineHook>();
                _hook2.Select(_commit).Returns(_commit);
                pipelineHooks.Add(_hook2);

                //A.CallTo(() => persistence.GetFrom(Bucket.Default, _date)).Returns(new List<ICommit> {_commit}.AsAsyncEnumerable());
                persistence.GetFrom(Bucket.Default, _date).Returns(new List<ICommit> { _commit }.AsAsyncEnumerable());
                return Task.FromResult(true);
            }
        public void Dispatch(ICommit commit)
        {
            lock (lockObject)
            {
                if (commit.Headers.Keys.Any(s => s == "SagaType"))
                {
                    var commands = commit.Headers.Where(x => x.Key.StartsWith("UndispatchedMessage.")).Select(x => x.Value).ToList();

                    foreach (var cmd in commands.Cast<ICommand>())
                        try
                        {
                            commandBusPublish.Call(cmd);
                        }
                        catch (Exception ex)
                        {
                            logger.Error(ex, cmd);
                            eventBus.Publish(new CommandDispatchFailedEvent
                            {
                                Id = new Guid(commit.StreamId),
                                CommandType = cmd.GetType().ToString(),
                                Command = JsonConvert.SerializeObject(cmd),
                                ErrorType = ex.GetType().ToString(),
                                ErrorMessage = ex.Message
                            });
                        }
                }
                else
                {
                    foreach (var evt in commit.Events.Select(e => e.Body))
                    {
                        eventBusPublish.Call(evt);
                    }

                    SetCheckpoint(commit);
                }
            }
        }
Example #31
0
 public VersionTaggedCommit(ICommit commit, SemanticVersion semVer, string tag)
 {
     this.Tag    = tag;
     this.Commit = commit;
     this.SemVer = semVer;
 }
 private static bool TryParse(ICommit mergeCommit, GitVersionContext context, out MergeMessage mergeMessage)
 {
     mergeMessage = Inner(mergeCommit, context);
     return(mergeMessage != null);
 }
 public override ICommit Select(ICommit committed)
 {
     // return null if the user isn't authorized to see this commit
     return(committed);
 }
Example #34
0
            public void should_find_tracked_streams()
            {
                ICommit stillTracked = BuildCommit(_trackedCommitAttempts.Last().StreamId, _trackedCommitAttempts.Last().CommitId);

                _hook.Contains(stillTracked).Should().BeTrue();
            }
Example #35
0
 private static bool AlreadyTracked(ICommit head)
 {
     return(head != null);
 }
Example #36
0
 public MergeBaseData(IBranchHead branch, IBranchHead otherBranch, IRepository repository, ICommit mergeBase)
 {
     Branch      = branch;
     OtherBranch = otherBranch;
     Repository  = repository;
     MergeBase   = mergeBase;
 }
Example #37
0
 protected override void Context()
 {
     _commit = Persistence.Commit(Guid.NewGuid().ToString().BuildAttempt());
 }
 public void MarkCommitAsDispatched(ICommit commit)
 {
     underlying.MarkCommitAsDispatched(commit);
 }
 protected override void Context()
 {
     _commit = CreateCommit(new EventMessage {
         Body = new ConvertingEvent(_id)
     });
 }
Example #40
0
        public override bool PreCommit(CommitAttempt attempt)
        {
            Logger.LogTrace(Resources.OptimisticConcurrencyCheck, attempt.StreamId);

            ICommit head = GetStreamHead(GetHeadKey(attempt));

            if (head == null)
            {
                return(true);
            }

            if (head.CommitSequence >= attempt.CommitSequence)
            {
                throw new ConcurrencyException(String.Format(
                                                   Messages.ConcurrencyExceptionCommitSequence,
                                                   head.CommitSequence,
                                                   attempt.CommitSequence,
                                                   attempt.StreamId,
                                                   attempt.StreamRevision,
                                                   attempt.Events.Count
                                                   ));
            }

            if (head.StreamRevision >= attempt.StreamRevision)
            {
                throw new ConcurrencyException(String.Format(
                                                   Messages.ConcurrencyExceptionStreamRevision,
                                                   head.StreamRevision,
                                                   attempt.StreamRevision,
                                                   attempt.StreamId,
                                                   attempt.StreamRevision,
                                                   attempt.Events.Count
                                                   ));
            }

            if (head.CommitSequence < attempt.CommitSequence - 1)
            {
                throw new StorageException(String.Format(
                                               Messages.StorageExceptionCommitSequence,
                                               head.CommitSequence,
                                               attempt.CommitSequence,
                                               attempt.StreamId,
                                               attempt.StreamRevision,
                                               attempt.Events.Count
                                               )); // beyond the end of the stream
            }

            if (head.StreamRevision < attempt.StreamRevision - attempt.Events.Count)
            {
                throw new StorageException(String.Format(
                                               Messages.StorageExceptionEndOfStream,
                                               head.StreamRevision,
                                               attempt.StreamRevision,
                                               attempt.Events.Count,
                                               attempt.StreamId,
                                               attempt.StreamRevision
                                               )); // beyond the end of the stream
            }

            Logger.LogTrace(Resources.NoConflicts, attempt.StreamId);
            return(true);
        }
Example #41
0
 public override ICommit Select(ICommit committed)
 {
     Track(committed);
     return(committed);
 }
Example #42
0
 private static HeadKey GetHeadKey(ICommit commit)
 {
     return(new HeadKey(commit.BucketId, commit.StreamId));
 }
 protected override void Because()
 {
     _converted = EventUpconverter.Select(_commit);
 }
 protected override void Context()
 {
     _trackedCommit = BuildCommit(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid());
     _hook          = new OptimisticPipelineHook();
     _hook.Track(_trackedCommit);
 }
Example #45
0
 protected override void Because()
 {
     _commit2 = _process2.Commit(Guid.NewGuid().ToString().BuildAttempt());
 }
 public override void PostCommit(ICommit committed)
 {
     // anything to do after the commit has been persisted.
 }
 public void Dispatch(ICommit commit)
 {
     _taskCompletionSource.SetResult(Unit.Default);
 }
Example #48
0
 public override void Project(ICommit commit)
 {
     _conventionProjector.Project(commit);
 }
Example #49
0
 public override void PostCommit(ICommit committed)
 {
     Track(committed);
 }
Example #50
0
 public void MarkCommitAsDispatched(ICommit commit)
 {
     _original.MarkCommitAsDispatched(commit);
 }
 private static bool TryParse(ICommit mergeCommit, IVersionContext context, out SemanticVersion semanticVersion)
 {
     semanticVersion = Inner(mergeCommit, context);
     return(semanticVersion != null);
 }
 protected override void Context()
 {
     _commit = Persistence.CommitSingle(Guid.NewGuid().ToString());
     Persistence.AddSnapshot(new Snapshot(_commit.BucketId, _commit.StreamId, _commit.StreamRevision, "SnapshotData"));
 }
 private static string FormatType(ICommit commit)
 {
     return($"Merge message '{commit.CommitMessage?.Trim()}'");
 }
        protected override void Context()
        {
            ICommit commit = Persistence.CommitSingle();

            _attemptWithSameRevision = commit.StreamId.BuildAttempt();
        }
Example #55
0
 protected override async Task Because()
 {
     _persisted = await(Persistence.GetFrom(_streamId, 0, int.MaxValue)).First();
 }
 protected override void Context()
 {
     _commit = Persistence.CommitSingle();
 }
 protected override void Because()
 {
     _persisted = Persistence.GetFrom(_streamId, 0, int.MaxValue).First();
 }
Example #58
0
            public void should_only_contain_streams_explicitly_tracked()
            {
                ICommit untracked = BuildCommit(Guid.Empty, _trackedCommitAttempts[0].CommitId);

                _hook.Contains(untracked).Should().BeFalse();
            }
Example #59
0
 public bool Contains(ICommit attempt)
 {
     return(GetStreamHead(GetHeadKey(attempt)) != null);
 }
Example #60
0
 private void OnEntrySelfAssessmentAdded(IDbTransaction tx, ICommit commit, EntrySelfAssessmentAdded @event)
 {
     InsertEntrySelfAssessment(tx, @event.SelfAssessment);
 }