async Task SendMessage <T>(T message, IPipe <SendContext <T> > pipe, CancellationToken cancellationToken) where T : class { LogContext.SetCurrentIfNull(_logContext); SendContext <T> context = new MessageSendContext <T>(message, cancellationToken); await pipe.Send(context).ConfigureAwait(false); var receiveContext = new MediatorReceiveContext <T>(context, this, this, _publishTopology, _receiveObservers, cancellationToken); try { if (_sendObservers.Count > 0) { await _sendObservers.PreSend(context).ConfigureAwait(false); } await _dispatcher.Dispatch(receiveContext).ConfigureAwait(false); if (_sendObservers.Count > 0) { await _sendObservers.PostSend(context).ConfigureAwait(false); } } catch (Exception ex) { if (_sendObservers.Count > 0) { await _sendObservers.SendFault(context, ex).ConfigureAwait(false); } throw; } }
public void Just_how_fast_are_you() { var message = new SerializationTestMessage { DecimalValue = 123.45m, LongValue = 098123213, BoolValue = true, ByteValue = 127, IntValue = 123, DateTimeValue = new DateTime(2008, 9, 8, 7, 6, 5, 4), TimeSpanValue = TimeSpan.FromSeconds(30), GuidValue = Guid.NewGuid(), StringValue = "Chris's Sample Code", DoubleValue = 1823.172 }; var sendContext = new MessageSendContext <SerializationTestMessage>(message); ReceiveContext receiveContext = null; //warm it up for (var i = 0; i < 10; i++) { byte[] data = Serialize(sendContext); var transportMessage = new InMemoryTransportMessage(Guid.NewGuid(), data, Serializer.ContentType.MediaType, TypeMetadataCache <SerializationTestMessage> .ShortName); receiveContext = new InMemoryReceiveContext(transportMessage, TestConsumeContext.GetContext()); Deserialize <SerializationTestMessage>(receiveContext); } var timer = Stopwatch.StartNew(); const int iterations = 50000; for (var i = 0; i < iterations; i++) { Serialize(sendContext); } timer.Stop(); var perSecond = iterations * 1000 / timer.ElapsedMilliseconds; Console.WriteLine("Serialize: {0}ms, Rate: {1} m/s", timer.ElapsedMilliseconds, perSecond); timer = Stopwatch.StartNew(); for (var i = 0; i < 50000; i++) { Deserialize <SerializationTestMessage>(receiveContext); } timer.Stop(); perSecond = iterations * 1000 / timer.ElapsedMilliseconds; Console.WriteLine("Deserialize: {0}ms, Rate: {1} m/s", timer.ElapsedMilliseconds, perSecond); }
public async Task Should_properly_use_the_original_specification_plus_more() { var specification = new SendPipeSpecification(); specification.GetMessageSpecification <MyMessage>() .UseExecute(context => Console.WriteLine("Hello, World.")); specification.GetMessageSpecification <IMyMessage>() .UseExecute(context => { }); var endpointSpecification = new SendPipeSpecification(); endpointSpecification.ConnectSendPipeSpecificationObserver(new ParentSendPipeSpecificationObserver(specification)); endpointSpecification.GetMessageSpecification <IMyMessage>() .UseConcurrencyLimit(1); endpointSpecification.GetMessageSpecification <ITraceableMessage>() .UsePartitioner(8, x => NewId.NextGuid()); IPipe <SendContext <MyMessage> > pipe = endpointSpecification.GetMessageSpecification <MyMessage>().BuildMessagePipe(); var sendContext = new MessageSendContext <MyMessage>(new MyMessage()); await pipe.Send(sendContext).ConfigureAwait(false); }
async Task ISendTransport.Send <T>(T message, IPipe <SendContext <T> > pipe, CancellationToken cancellationToken) { LogContext.SetCurrentIfNull(_context.LogContext); var context = new MessageSendContext <T>(message, cancellationToken); await pipe.Send(context).ConfigureAwait(false); StartedActivity?activity = LogContext.IfEnabled(OperationName.Transport.Send)?.StartSendActivity(context); try { if (_context.SendObservers.Count > 0) { await _context.SendObservers.PreSend(context).ConfigureAwait(false); } var messageId = context.MessageId ?? NewId.NextGuid(); var transportMessage = new InMemoryTransportMessage(messageId, context.Body, context.ContentType.MediaType, TypeMetadataCache <T> .ShortName) { Delay = context.Delay }; SetHeaders(transportMessage.Headers, context.Headers); await _context.Exchange.Send(transportMessage, cancellationToken).ConfigureAwait(false); context.LogSent(); activity.AddSendContextHeadersPostSend(context); if (_context.SendObservers.Count > 0) { await _context.SendObservers.PostSend(context).ConfigureAwait(false); } } catch (Exception ex) { context.LogFaulted(ex); if (_context.SendObservers.Count > 0) { await _context.SendObservers.SendFault(context, ex).ConfigureAwait(false); } throw; } finally { activity?.Stop(); } }
public async Task Should_properly_delegate_the_specifications() { var specification = new SendPipeSpecification(); specification.GetMessageSpecification <MyMessage>() .UseExecute(context => Console.WriteLine("Hello, World.")); specification.GetMessageSpecification <IMyMessage>() .UseExecute(context => { }); IPipe <SendContext <MyMessage> > pipe = specification.GetMessageSpecification <MyMessage>().BuildMessagePipe(); var sendContext = new MessageSendContext <MyMessage>(new MyMessage()); await pipe.Send(sendContext).ConfigureAwait(false); }
protected byte[] Serialize <T>(T obj) where T : class { using (var output = new MemoryStream()) { var sendContext = new MessageSendContext <T>(obj); sendContext.SourceAddress = _sourceAddress; sendContext.DestinationAddress = _destinationAddress; sendContext.FaultAddress = _faultAddress; sendContext.ResponseAddress = _responseAddress; sendContext.RequestId = _requestId; Serializer.Serialize(output, sendContext); byte[] serializedMessageData = output.ToArray(); Trace.WriteLine(Encoding.UTF8.GetString(serializedMessageData)); return(serializedMessageData); } }
static (byte[], Dictionary <string, object>) Serialize <T>(T obj) where T : class { var serializer = new RawJsonMessageSerializer(); using var output = new MemoryStream(); var sendContext = new MessageSendContext <T>(obj); serializer.Serialize(output, sendContext); var bytes = output.ToArray(); var headers = new Dictionary <string, object> { { MessageHeaders.ContentType, RawJsonMessageSerializer.ContentTypeHeaderValue }, { MessageHeaders.MessageId, sendContext.MessageId } }; headers.Set(sendContext.Headers); return(bytes, headers); }
public async Task Should_receive_concurrently() { TaskCompletionSource <ConsumeContext <KafkaMessage> > taskCompletionSource = GetTask <ConsumeContext <KafkaMessage> >(); var services = new ServiceCollection(); services.AddSingleton(taskCompletionSource); services.TryAddSingleton <ILoggerFactory>(LoggerFactory); services.TryAddSingleton(typeof(ILogger <>), typeof(Logger <>)); services.AddMassTransit(x => { x.UsingInMemory((context, cfg) => cfg.ConfigureEndpoints(context)); x.AddRider(rider => { rider.AddConsumer <KafkaMessageConsumer>(); rider.UsingKafka((context, k) => { k.Host("localhost:9092"); k.TopicEndpoint <KafkaMessage>(Topic, nameof(Receive_Specs), c => { c.ConfigureConsumer <KafkaMessageConsumer>(context); c.CheckpointMessageCount = 10; c.ConcurrencyLimit = 100; }); }); }); }); var provider = services.BuildServiceProvider(); var busControl = provider.GetRequiredService <IBusControl>(); var observer = GetConsumeObserver(); busControl.ConnectConsumeObserver(observer); await busControl.StartAsync(TestCancellationToken); try { var config = new ProducerConfig { BootstrapServers = "localhost:9092" }; using IProducer <Null, KafkaMessage> p = new ProducerBuilder <Null, KafkaMessage>(config) .SetValueSerializer(new MassTransitJsonSerializer <KafkaMessage>()) .Build(); var kafkaMessage = new KafkaMessageClass("test"); var sendContext = new MessageSendContext <KafkaMessage>(kafkaMessage); var message = new Message <Null, KafkaMessage> { Value = kafkaMessage, Headers = DictionaryHeadersSerialize.Serializer.Serialize(sendContext) }; await Task.WhenAll(Enumerable.Range(0, 100).Select(x => p.ProduceAsync(Topic, message))); ConsumeContext <KafkaMessage> result = await taskCompletionSource.Task; Assert.AreEqual(message.Value.Text, result.Message.Text); Assert.AreEqual(sendContext.MessageId, result.MessageId); Assert.That(result.DestinationAddress, Is.EqualTo(new Uri($"loopback://localhost/{KafkaTopicAddress.PathPrefix}/{Topic}"))); Assert.That(await observer.Messages.Any <KafkaMessage>()); } finally { await busControl.StopAsync(TestCancellationToken); await provider.DisposeAsync(); } }
public async Task Should_receive() { TaskCompletionSource <ConsumeContext <EventHubMessage> > taskCompletionSource = GetTask <ConsumeContext <EventHubMessage> >(); var services = new ServiceCollection(); services.AddSingleton(taskCompletionSource); services.TryAddSingleton <ILoggerFactory>(LoggerFactory); services.TryAddSingleton(typeof(ILogger <>), typeof(Logger <>)); services.AddMassTransit(x => { x.UsingInMemory((context, cfg) => cfg.ConfigureEndpoints(context)); x.AddRider(rider => { rider.AddConsumer <EventHubMessageConsumer>(); rider.UsingEventHub((context, k) => { k.Host(Configuration.EventHubNamespace); k.Storage(Configuration.StorageAccount); k.ReceiveEndpoint(Configuration.EventHubName, c => { c.ConfigureConsumer <EventHubMessageConsumer>(context); }); }); }); }); var provider = services.BuildServiceProvider(); var busControl = provider.GetRequiredService <IBusControl>(); await busControl.StartAsync(TestCancellationToken); try { await using var producer = new EventHubProducerClient(Configuration.EventHubNamespace, Configuration.EventHubName); var serializer = new JsonMessageSerializer(); var message = new EventHubMessageClass("test"); var context = new MessageSendContext <EventHubMessage>(message); await using (var stream = new MemoryStream()) { serializer.Serialize(stream, context); stream.Flush(); var eventData = new EventData(stream.ToArray()); await producer.SendAsync(new[] { eventData }); } ConsumeContext <EventHubMessage> result = await taskCompletionSource.Task; Assert.AreEqual(message.Text, result.Message.Text); } finally { await busControl.StopAsync(TestCancellationToken); await provider.DisposeAsync(); } }
public async Task Should_receive() { TaskCompletionSource <ConsumeContext <KafkaMessage> > taskCompletionSource = GetTask <ConsumeContext <KafkaMessage> >(); TaskCompletionSource <ConsumeContext <BusPing> > pingTaskCompletionSource = GetTask <ConsumeContext <BusPing> >(); var services = new ServiceCollection(); services.AddSingleton(taskCompletionSource); services.AddSingleton(pingTaskCompletionSource); services.TryAddSingleton <ILoggerFactory>(LoggerFactory); services.TryAddSingleton(typeof(ILogger <>), typeof(Logger <>)); services.AddMassTransit(x => { x.AddConsumer <BusPingConsumer>(); x.UsingInMemory((context, cfg) => cfg.ConfigureEndpoints(context)); x.AddRider(rider => { rider.AddConsumer <KafkaMessageConsumer>(); rider.UsingKafka((context, k) => { k.Host("localhost:9092"); k.TopicEndpoint <KafkaMessage>(Topic, nameof(Receive_Specs), c => { c.AutoOffsetReset = AutoOffsetReset.Earliest; c.ConfigureConsumer <KafkaMessageConsumer>(context); }); }); }); }); var provider = services.BuildServiceProvider(); var busControl = provider.GetRequiredService <IBusControl>(); await busControl.StartAsync(TestCancellationToken); try { var config = new ProducerConfig { BootstrapServers = "localhost:9092" }; using IProducer <Null, KafkaMessage> p = new ProducerBuilder <Null, KafkaMessage>(config) .SetValueSerializer(new MassTransitJsonSerializer <KafkaMessage>()) .Build(); var kafkaMessage = new KafkaMessageClass("test"); var sendContext = new MessageSendContext <KafkaMessage>(kafkaMessage); var message = new Message <Null, KafkaMessage> { Value = kafkaMessage, Headers = DictionaryHeadersSerialize.Serializer.Serialize(sendContext) }; await p.ProduceAsync(Topic, message); ConsumeContext <KafkaMessage> result = await taskCompletionSource.Task; ConsumeContext <BusPing> ping = await pingTaskCompletionSource.Task; Assert.AreEqual(result.CorrelationId, ping.InitiatorId); Assert.That(ping.SourceAddress, Is.EqualTo(new Uri($"loopback://localhost/{KafkaTopicAddress.PathPrefix}/{Topic}"))); } finally { await busControl.StopAsync(TestCancellationToken); await provider.DisposeAsync(); } }