public async Task <TResponse> Handle(CommandEnvelope <TCommand, TResponse> request, RequestHandlerDelegate <TResponse> next) { await Task.Delay(_options.Delay); return(await next()); }
public void PipeOrderIsPreserved() { Module .RevealFor <object>() .Pipe(next => (e, ct) => { Assert.Equal(1, GetStep(e.Metadata)); return(next(e.SetMetadata(SetStep(e.Metadata, 2)), ct)); }) .Pipe(next => (e, ct) => { Assert.Equal(2, GetStep(e.Metadata)); return(next(e.SetMetadata(SetStep(e.Metadata, 3)), ct)); }) .Handle( (e, ct) => { Assert.Equal(3, GetStep(e.Metadata)); return(Task.CompletedTask); }); var envelope = new CommandEnvelope() .SetCommand(new object()) .SetMetadata(Metadata.None.With(new Metadatum("step", "1"))); new CommandHandlerInvoker(Module).Invoke(envelope); }
public static void OnCreateOrderCommand( [ServiceBusTrigger("commands")] CommandEnvelope <CreateOrder> envelope, TextWriter log) { var command = envelope.Command as CreateOrder; var repository = Container.Resolve <IRepository <CommandingOrder, Guid> >(); var client = Container.Resolve <ICommandHandler>(); var order = repository.GetById(command.CommandId); var events = new List <EventEnvelope <OrderCreated> >(); order.Event += (s, e) => { if (e is OrderCreated) { events.Add(new EventEnvelope <OrderCreated> { Event = (OrderCreated)e , Timestamp = DateTime.UtcNow , Username = envelope.Username }); } }; order.Apply(command); repository.Set(order); client.Handle(events.ToArray()); }
public async Task <Unit> Handle(CommandEnvelope <JoinRoomCommand, Unit> message) { var context = message.Context; var command = message.Command; await context.User.JoinRoom(command.RoomId, context.Connection.Id); return(Unit.Value); }
public async Task <IRoomData> Handle(CommandEnvelope <GetRoomStateCommand, IRoomData> message) { var context = message.Context; var command = message.Command; var player = await context.User.JoinRoom(command.RoomId, context.Connection.Id); return(await player.GetState()); }
public void CanSerializeToBson() { var aggregateId = Guid.Parse("61296B2F-F040-472D-95DF-B1C3A32A7C7E"); var envelope = new CommandEnvelope(aggregateId, new FakeCommand("My Command")); var bson = WriteBson(envelope); Validate(bson, "vQAAAAVhABAAAAAEL2spYUDwLUeV37HDoyp8fgNjAJ0AAAACJHR5cGUAdAAAAFRlc3QuU3BhcmsuU2VyaWFsaXphdGlvbi5Db252ZXJ0ZXJzLlVzaW5nQ29tbWFuZEVudmVsb3BlQ29udmVydGVyLkZha2VDb21tYW5kLCBTcGFyay5TZXJpYWxpemF0aW9uLk5ld3RvbnNvZnQuVGVzdHMAAlByb3BlcnR5AAsAAABNeSBDb21tYW5kAAAA"); }
public Task PostScheduled(CommandEnvelope envelope, IObserver<LogEntry> log) { var req = CreatePostCommandRequest(envelope); return _client.PostScheduled(req) .ContinueWith(x => { var resp = x.Result; var id = resp.Id; Action<string> traceStatus = m => log.OnNext(new LogEntry { Message = m, Severity = LogEntrySeverity.Trace, Timestamp = DateTime.Now }); traceStatus("Start waiting for execution command " + id); var token = DateTime.MinValue; while (true) { var resp2 = _client.GetScheduled(id, token); // Write user log var serverLog = resp2.Log.OrEmpty().ToList(); foreach (var entry in serverLog) { log.OnNext(entry); } // Take maximum available timestamp token = serverLog.Select(xx => xx.Timestamp).Union(new[] { token }).Max(); switch (resp2.Status) { case ScheduledCommandStatus.Pending: traceStatus("Command(" + id + ") is still pending."); break; case ScheduledCommandStatus.InProgress: traceStatus("Command(" + id + ") is in progress."); break; case ScheduledCommandStatus.Success: traceStatus("Command(" + id + ") completed success."); return; case ScheduledCommandStatus.Failure: traceStatus("Command(" + id + ") failed."); return; } Thread.Sleep(300); } }); }
public async Task <Unit> Handle(CommandEnvelope <LaunchFleetCommand, Unit> message) { var context = message.Context; var command = message.Command; var player = await context.User.JoinRoom(command.RoomId, context.Connection.Id); await player.LaunchFleet(command.Fleet); return(Unit.Value); }
public async Task <Unit> Handle(CommandEnvelope <UpdateGameOptionsCommand, Unit> message) { var context = message.Context; var command = message.Command; var player = await context.User.JoinRoom(command.RoomId, context.Connection.Id); await player.UpdateGameOptions(command.Options); return(Unit.Value); }
public async Task <Unit> Handle(CommandEnvelope <CancelFleetCommand, Unit> message) { var command = message.Command; var context = message.Context; var player = await context.User.JoinRoom(command.RoomId, context.Connection.Id); var cancelation = _mapper.Map <CancelFleetCommand, FleetCancelationData>(command); await player.CancelFleet(cancelation); return(Unit.Value); }
public void NewReturnsExpectedInstance() { var sut = new CommandEnvelope(); Assert.Null(sut.Command); Assert.Equal(Guid.Empty, sut.CommandId); Assert.Equal(Guid.Empty, sut.CorrelationId); Assert.Null(sut.SourceId); Assert.Null(sut.Principal); Assert.Same(ReactiveDomain.Metadata.None, sut.Metadata); }
public async Task <Unit> Handle(CommandEnvelope <SendMessageCommand, Unit> message) { var context = message.Context; var command = message.Command; var player = await context.User.JoinRoom(command.RoomId, context.Connection.Id); var textMessage = _mapper.Map <SendMessageCommand, TextMessageData>(command); await player.SendMessage(textMessage); return(Unit.Value); }
public Task ContinueWith(CommandEnvelope command) { var commandType = command.GetType(); var useCase = _useCases.FirstOrDefault(uc => uc.CanTell(command.Payload)); if (null == useCase) { throw new NoStoryException(command.Payload.GetType().Name); } return(useCase.Tell(command)); }
public void SetMetadataReturnsExpectedInstance() { var sut = new CommandEnvelope().SetMetadata(Metadata); Assert.Same(Metadata, sut.Metadata); Assert.Null(sut.Command); Assert.Equal(Guid.Empty, sut.CommandId); Assert.Equal(Guid.Empty, sut.CorrelationId); Assert.Null(sut.Principal); Assert.Null(sut.SourceId); }
void PublishToQueue(CommandEnvelope commandEnvelope, string queuePath) { if (!Directory.Exists(queuePath)) { Directory.CreateDirectory(queuePath); } File.WriteAllText( Path.Combine(queuePath, Guid.NewGuid().ToString()), commandEnvelope.SerializeToJson() ); }
public async Task <LoginCommandResponse> Handle(CommandEnvelope <LoginCommand, LoginCommandResponse> message) { var context = message.Context; var command = message.Command; var result = await context.Connection.Login(command.AccessToken); var response = new LoginCommandResponse { AccessToken = result.AccessToken }; return(response); }
public void TypedAsThrowsIfCommandIsNotAssignableToType() { var sut = new CommandEnvelope() .SetCommand(Command) .SetCommandId(CommandId) .SetCorrelationId(CorrelationId) .SetSourceId(SourceId) .SetMetadata(Metadata) .SetPrincipal(Principal); Assert.Throws <InvalidCastException>(() => sut.TypedAs <Message>()); }
public Task<string> PostAsync(CommandEnvelope envelope) { var req = CreatePostCommandRequest(envelope); return _client.Post(req) .ContinueWith(x => { if (!x.Result.IsSuccessStatusCode) throw new ZazTransportException("An error occurred while sending request.", x.Result); var log = x.Result.Content.ReadAsStringAsync().Result; return log; }); }
public void DoNotSaveAggregateOnSuccessIfNoEventsRaised() { var aggregate = new FakeAggregate(); var envelope = new CommandEnvelope(GuidStrategy.NewGuid(), new FakeCommand()); var commandHandler = new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => { }); AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate); using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope)) commandHandler.Handle(context); AggregateStore.Verify(mock => mock.Save(aggregate, It.IsAny <CommandContext>()), Times.Never); }
public Task Post(CommandEnvelope envelope) { var req = CreatePostCommandRequest(envelope); return _client.Post(req) .ContinueWith(x => { if (!x.Result.IsSuccessStatusCode) { throw new InvalidOperationException("Command was not successfully posted. Server response: " + x.Result.ReasonPhrase); } return; }); }
public void RetrieveCommandHandlerBasedOnCommandType() { var command = new FakeCommand(); var aggregate = new FakeAggregate(); var envelope = new CommandEnvelope(GuidStrategy.NewGuid(), command); var message = Message.Create(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope); HandlerRegistry.Setup(mock => mock.GetHandlerFor(command)).Returns(new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => { })); AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate); Processor.Process(message); HandlerRegistry.Verify(mock => mock.GetHandlerFor(command), Times.Once()); }
public void CanSerializeToJson() { var aggregateId = Guid.Parse("a6c45a28-c572-4d5b-ac18-7b0ec2d723fb"); var envelope = new CommandEnvelope(aggregateId, new FakeCommand("My Command")); var json = WriteJson(envelope); Validate(json, @" { ""a"": ""a6c45a28-c572-4d5b-ac18-7b0ec2d723fb"", ""c"": { ""$type"": ""Test.Spark.Serialization.Converters.UsingCommandEnvelopeConverter.FakeCommand, Spark.Serialization.Newtonsoft.Tests"", ""Property"": ""My Command"" } }"); }
public void VerifyInitializedIfExplictCreateRequired() { var aggregate = new FakeAggregate(explicitCreateRequired: true, version: 0); var envelope = new CommandEnvelope(GuidStrategy.NewGuid(), new FakeCommand()); var commandHandler = new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => ((FakeAggregate)a).Handle((FakeCommand)c)); AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate); using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope)) { var ex = Assert.Throws <InvalidOperationException>(() => commandHandler.Handle(context)); Assert.Equal(Exceptions.AggregateNotInitialized.FormatWith(typeof(FakeAggregate), Guid.Empty), ex.Message); } }
public void DoNotVerifyInitializedIfImplicitCreateAllowed() { var aggregate = new FakeAggregate(explicitCreateRequired: false, version: 0); var envelope = new CommandEnvelope(GuidStrategy.NewGuid(), new FakeCommand()); var commandHandler = new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => ((FakeAggregate)a).Handle((FakeCommand)c)); AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate); using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope)) { commandHandler.Handle(context); Assert.True(aggregate.Handled); } }
public async Task <TResponse> Handle(CommandEnvelope <TCommand, TResponse> message, RequestHandlerDelegate <TResponse> next) { var context = message.Context; if (_skipAuthentication) { return(await next.Invoke()); } var loginResult = await context.Connection.Authenticate(context.Metadata.AccessToken); context.UserId = loginResult.UserId; context.User = loginResult.User; return(await next.Invoke()); }
public static async Task <long?> Handle <S, C>(CommandEnvelope <C> commandEnvelope, IAggregate <S> aggregate, IEventStore eventStore, CancellationToken cancel = default) where C : class where S : class { if (commandEnvelope.AggregateId == null || commandEnvelope.Command == null) { throw new Exception(); } var streamName = aggregate.GetStreamName(commandEnvelope.AggregateId); var(version, state) = await Load(streamName, aggregate, eventStore, cancel); var events = aggregate.Handle(state, commandEnvelope.Command) .Select((e, i) => e.CreateEventEnvelope(commandEnvelope.AggregateId, version + i + 1)) .ToArray(); return(await eventStore.Save(streamName, cancel, events)); }
public void WillTimeoutEventuallyIfCannotSave() { var command = new FakeCommand(); var aggregate = new FakeAggregate(); var envelope = new CommandEnvelope(GuidStrategy.NewGuid(), command); var message = Message.Create(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope); var processor = new CommandProcessor(HandlerRegistry.Object, TransientErrorRegistry.Object, new CommandProcessorSettings { RetryTimeout = TimeSpan.FromMilliseconds(20) }); SystemTime.ClearOverride(); AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate); AggregateStore.Setup(mock => mock.Save(aggregate, It.IsAny <CommandContext>())).Callback(() => { throw new ConcurrencyException(); }); HandlerRegistry.Setup(mock => mock.GetHandlerFor(command)).Returns(new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => ((FakeAggregate)a).Handle((FakeCommand)c))); Assert.Throws <TimeoutException>(() => processor.Process(message)); }
private BasketModel CommitCommand(CommandEnvelope <Command> cmd) { var list = new List <CommandEnvelope <Command> > { cmd }; var res = CommandHandler.handler.Invoke(cmd); if (res.IsOk) { return(GetBasketAggregate(cmd.AggregateId.Item)); } var f = (res as Result <FSharpList <EventEnvelope <Event> >, IError> .Bad).Item; var reasons = f.Select(x => x.ToString()).ToArray(); var reason = string.Join("; ", reasons); throw new Exception(reason); }
private void QueueCommand(CommandEnvelope <Command> cmd) { var list = new List <Tuple <QueueName, CommandEnvelope <Command> > > { Tuple.Create(QueueName.NewQueueName("Order"), cmd) }; var res = PinetreeCQRS.Persistence.SqlServer.Commands.queueCommands(ListModule.OfSeq(list)); if (res.IsOk) { return; } var f = (res as Result <FSharpList <CommandEnvelope <Command> >, IError> .Bad).Item; var reasons = f.Select(x => x.ToString()).ToArray(); var reason = string.Join("; ", reasons); throw new Exception(reason); }
public async Task <TResponse> Handle(CommandEnvelope <TCommand, TResponse> message, RequestHandlerDelegate <TResponse> next) { var context = message.Context; try { return(await next.Invoke()); } catch (Exception ex) { _counter.Increment(); var level = ex is UserException ? LogEventLevel.Warning : LogEventLevel.Error; _logger.Write(level, ex, "[{TraceId}-{UserId}] {Message}", context.Metadata.TraceId, context.UserId == null ? "Anonymous" : context.UserId.ToString(), ex.Message); throw; } }
private async Task TellAndSaveWithoutLoading <TCommand>( CommandEnvelope command, Func <TCommand, AggregateState <TState> .Transition> update) { // _log.Debug("Processing command {command}", command); var transition = update((TCommand)command.Payload); var uow = UnitOfWork <TState> .For(command.ChainInfo.MessageId , command.ChainInfo.CorrelationId , command.ChainInfo.CausationId , InitializeState(transition.State.Id)); // var state = uow.State; var transaction = uow.Track(transition.Events, transition.State); var finalVersion = transition.State.Version; var originlVersion = finalVersion - transition.Events.Count(); var expectedVersion = originlVersion; await _repository.Save(transaction, expectedVersion); }
public void TypedAsDoesNotThrowIfCommandIsAssignableToType() { var message = new Message(); var sut = new CommandEnvelope() .SetCommand(message) .SetCommandId(CommandId) .SetCorrelationId(CorrelationId) .SetSourceId(SourceId) .SetMetadata(Metadata) .SetPrincipal(Principal); var result = sut.TypedAs <object>(); Assert.IsType <CommandEnvelope <object> >(result); Assert.Same(message, result.Command); Assert.Equal(CommandId, result.CommandId); Assert.Equal(CorrelationId, result.CorrelationId); Assert.Equal(SourceId, result.SourceId); Assert.Same(Metadata, result.Metadata); Assert.Same(Principal, result.Principal); }
public void TypedAsReturnsExpectedInstance() { var message = new Message(); var sut = new CommandEnvelope() .SetCommand(message) .SetCommandId(CommandId) .SetCorrelationId(CorrelationId) .SetSourceId(SourceId) .SetMetadata(Metadata) .SetPrincipal(Principal); var result = sut.TypedAs <Message>(); Assert.IsType <CommandEnvelope <Message> >(result); Assert.Same(message, result.Command); Assert.Equal(CommandId, result.CommandId); Assert.Equal(CorrelationId, result.CorrelationId); Assert.Equal(SourceId, result.SourceId); Assert.Same(Metadata, result.Metadata); Assert.Same(Principal, result.Principal); }
public void ReloadAggregateOnConcurrencyException() { var save = 0; var command = new FakeCommand(); var aggregate = new FakeAggregate(); var envelope = new CommandEnvelope(GuidStrategy.NewGuid(), command); var message = Message.Create(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope); var ex = new ConcurrencyException(); HandlerRegistry.Setup(mock => mock.GetHandlerFor(command)).Returns(new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => ((FakeAggregate)a).Handle((FakeCommand)c))); AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate); AggregateStore.Setup(mock => mock.Save(aggregate, It.IsAny<CommandContext>())).Callback(() => { if (++save == 1) throw ex; }); Processor.Process(message); AggregateStore.Verify(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId), Times.Exactly(2)); }
public Task PostScheduled(CommandEnvelope envelope) { var req = CreatePostCommandRequest(envelope); return _client.PostScheduled(req) .ContinueWith(x => { var resp = x.Result; var id = resp.Id; WriteTrace("Start waiting for execution command " + id); while (true) { Thread.Sleep(300); var resp2 = _client.GetScheduled(id); switch (resp2.Status) { case ScheduledCommandStatus.Pending: WriteTrace("Command(" + id + ") is still pending."); break; case ScheduledCommandStatus.InProgress: WriteTrace("Command(" + id + ") is in progress."); break; case ScheduledCommandStatus.Success: WriteTrace("Command(" + id + ") completed success."); return; case ScheduledCommandStatus.Failure: WriteTrace("Command(" + id + ") failed."); return; } } }); }
public void DoNotSaveAggregateOnSuccessIfNoEventsRaised() { var aggregate = new FakeAggregate(); var envelope = new CommandEnvelope(GuidStrategy.NewGuid(), new FakeCommand()); var commandHandler = new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => { }); AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate); using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope)) commandHandler.Handle(context); AggregateStore.Verify(mock => mock.Save(aggregate, It.IsAny<CommandContext>()), Times.Never); }
public static TranslationResult Ok(CommandEnvelope command) { return new TranslationResult(command, TranslationResultType.Ok, null); }
public void WillTimeoutEventuallyIfCannotSave() { var command = new FakeCommand(); var aggregate = new FakeAggregate(); var envelope = new CommandEnvelope(GuidStrategy.NewGuid(), command); var message = Message.Create(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope); var processor = new CommandProcessor(HandlerRegistry.Object, TransientErrorRegistry.Object, new CommandProcessorSettings { RetryTimeout = TimeSpan.FromMilliseconds(20) }); SystemTime.ClearOverride(); AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate); AggregateStore.Setup(mock => mock.Save(aggregate, It.IsAny<CommandContext>())).Callback(() => { throw new ConcurrencyException(); }); HandlerRegistry.Setup(mock => mock.GetHandlerFor(command)).Returns(new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => ((FakeAggregate)a).Handle((FakeCommand)c))); Assert.Throws<TimeoutException>(() => processor.Process(message)); }
private TranslationResult(CommandEnvelope commandEnvelope, TranslationResultType type, string suggestedVersion) { Type = type; CommandEnvelope = commandEnvelope; SuggestedVersion = suggestedVersion; }
private static PostCommandRequest CreatePostCommandRequest(CommandEnvelope envelope) { return new PostCommandRequest { Command = envelope.Command, Key = envelope.Key, Tags = envelope.Tags }; }
public static TranslationResult NewVersionSuggested(CommandEnvelope command, string suggestedVersion) { return new TranslationResult(command, TranslationResultType.NewVersionSuggested, suggestedVersion); }
public void VerifyInitializedIfExplictCreateRequired() { var aggregate = new FakeAggregate(explicitCreateRequired: true, version: 0); var envelope = new CommandEnvelope(GuidStrategy.NewGuid(), new FakeCommand()); var commandHandler = new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => ((FakeAggregate)a).Handle((FakeCommand)c)); AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate); using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope)) { var ex = Assert.Throws<InvalidOperationException>(() => commandHandler.Handle(context)); Assert.Equal(Exceptions.AggregateNotInitialized.FormatWith(typeof(FakeAggregate), Guid.Empty), ex.Message); } }