private MessagingEnvelope <TMessage> PrepareMessageEnvelope <TMessage>(TMessage message, Action <MessagingEnvelope> customizer = null) { var outgoingEnvelope = new MessagingEnvelope <TMessage>(new Dictionary <string, string> { [MessagingHeaders.MessageId] = Guid.NewGuid().ToString(), [MessagingHeaders.PublishTime] = DateTime.Now.ToString(CultureInfo.InvariantCulture) }, message); if (message is IKeyProvider messageKeyProvider) { outgoingEnvelope.Headers[MessagingHeaders.StreamId] = messageKeyProvider.Key; } var sourceId = GetSourceId(); if (!string.IsNullOrWhiteSpace(sourceId)) { outgoingEnvelope.Headers[MessagingHeaders.Source] = sourceId; } customizer?.Invoke(outgoingEnvelope); outgoingEnvelope.SetHeader(MessagingHeaders.CorrelationId, Guid.NewGuid().ToString()); return(outgoingEnvelope); }
public void Should_deserialize_messages_using_header_type_info() { //Arrange var sut = new NewtonsoftJsonMessageSerDes( Mock.Of <IMessageTypeRegistry>(x => x.ResolveType(It.IsAny <string>(), It.IsAny <IEnumerable <Assembly> >()) == typeof(TestMessage) && x.GetTypeId(It.IsAny <Type>()) == "TestMessage")); var @event = new TestMessage(11232, 1122312, "something"); var envelope = new MessagingEnvelope(new Dictionary <string, string> { [MessagingHeaders.MessageType] = "TestMessage" }, @event); var json = sut.SerializeMessageEnvelope(envelope); //Act var deserialized = sut.DeserializeMessageEnvelope(json, new MessageSerDesOptions() { DeserializationType = DeserializationType.Dynamic, DynamicDeserializationScannedAssemblies = new[] { Assembly.GetExecutingAssembly() } }); //Assert deserialized.Should().NotBeNull(); deserialized.Payload.Should().NotBeNull(); deserialized.Payload.GetType().Should().Be(typeof(TestMessage)); }
async Task HandleMessage(string msg) { MessagingEnvelope <TMessage> deserializedMessage = null; try { deserializedMessage = _messageSerDes.DeserializeMessageEnvelope <TMessage>(msg, _subscriberOptions?.SerDes); } catch (Exception ex) { _logger.LogError( "MessageBusSubscriber encountered an error when deserializing a message from topic {TopicName}.\n {Error}", _topicName, ex); //TODO: push to DLQ } if (deserializedMessage != null) { foreach (var handler in _handlers.ToList()) { await handler(deserializedMessage); } } }
public static Guid?GetCorrelationId(this MessagingEnvelope envelope) { return(envelope.Headers.TryGetValue(MessagingHeaders.CorrelationId, out var value) ? Guid.TryParse(value, out var guidValue) ? guidValue : default(Guid?) : default(Guid?)); }
public TenantIdHeaderMessagingTokenResolverTests() { _mockMessagingContextAccessor = new MessagingContextAccessor(); _headers = new Dictionary <string, string>(); var mockMessagingEnvelope = new MessagingEnvelope(_headers, new object()); var mockMessagingContext = new MessagingContext(mockMessagingEnvelope); _mockMessagingContextAccessor.MessagingContext = mockMessagingContext; }
private async Task Handle(MessagingEnvelope <TMessage> message, CancellationToken cancellationToken) { using (var scope = _serviceProvider.CreateScope()) { var pipeline = scope.ServiceProvider.GetService <PipelineDelegate <MessagingEnvelope> >(); _messagingContextAccessor.MessagingContext = new MessagingContext(message); await pipeline(message, cancellationToken); } }
public static void SetHeader(this MessagingEnvelope envelope, string header, string value, bool overwrite = false) { if (!overwrite && envelope.Headers.ContainsKey(header) && !string.IsNullOrEmpty(envelope.Headers[header])) { return; } envelope.Headers[header] = value; }
public static void TransferHeaderTo(this MessagingEnvelope envelope, MessagingEnvelope destinationEnvelope, string header, bool overwrite = false) { if (!envelope.Headers.ContainsKey(header)) { return; } destinationEnvelope.SetHeader(header, envelope.Headers[header], overwrite); }
private async Task Handle(MessagingEnvelope <TMessage> message, string topicName, PipelineDelegate <MessagingContext> pipeline, CancellationToken cancellationToken) { using var scope = _serviceProvider.CreateScope(); var context = new MessagingContext(message, topicName, scope.ServiceProvider); _messagingContextAccessor.MessagingContext = context; await pipeline(context, cancellationToken); }
public static void TransferCustomHeadersTo(this MessagingEnvelope envelope, MessagingEnvelope destinationEnvelope, bool overwrite = false) { foreach (KeyValuePair <string, string> header in envelope.Headers) { if (header.Key.StartsWith("nbb-")) { continue; } envelope.TransferHeaderTo(destinationEnvelope, header.Key, overwrite); } }
public async void Should_logSuccessMessage() { //Arrange var mockedLogger = Mock.Of <ILogger <ExceptionHandlingMiddleware> >(); var correlationMiddleWare = new ExceptionHandlingMiddleware(mockedLogger); var sentMessage = new { Field = "value" }; var envelope = new MessagingEnvelope(new System.Collections.Generic.Dictionary <string, string>(), sentMessage); Task next() => Task.CompletedTask; //Act await correlationMiddleWare.Invoke(new MessagingContext(envelope, string.Empty, null), default, next);
public async void Should_publishEventsToMediatR() { //Arrange var mockedMediator = Mock.Of <IMediator>(); var mediatRMiddleware = new MediatRMiddleware(mockedMediator); var sentMessage = Mock.Of <IMockingEventMessage>(); var envelope = new MessagingEnvelope <IMockingEventMessage>(new System.Collections.Generic.Dictionary <string, string>(), sentMessage); Task Next() => Task.CompletedTask; //Act await mediatRMiddleware.Invoke(envelope, default, Next);
public string SerializeMessageEnvelope(MessagingEnvelope message, MessageSerDesOptions options = null) { var messageTypeId = _messageTypeRegistry.GetTypeId(message.Payload.GetType()); message.SetHeader(MessagingHeaders.MessageType, messageTypeId, true); var json = JsonConvert.SerializeObject(message, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); return(json); }
public async Task Should_execute_pipeline_on_message_received() { //Arrange var message = new TestMessage(); var envelope = new MessagingEnvelope <TestMessage>(new Dictionary <string, string>(), message); var pipeline = Mock.Of <PipelineDelegate <MessagingEnvelope> >(); Func <string, Task> messageBusSubscriberCallback = null; var cancellationToken = new CancellationToken(); var mockedMessageBusSubscriber = Mock.Of <IMessagingTopicSubscriber>(); Mock.Get(mockedMessageBusSubscriber) .Setup(x => x.SubscribeAsync(It.IsAny <string>(), It.IsAny <Func <string, Task> >(), It.IsAny <CancellationToken>(), It.IsAny <MessagingSubscriberOptions>())) .Callback((string topic, Func <string, Task> handler, CancellationToken token, MessagingSubscriberOptions options) => { messageBusSubscriberCallback = handler; cancellationToken = token; }) .Returns(Task.CompletedTask); var mockedServiceProvider = Mock.Of <IServiceProvider>(sp => sp.GetService(typeof(IServiceScopeFactory)) == Mock.Of <IServiceScopeFactory>(ssf => ssf.CreateScope() == Mock.Of <IServiceScope>(ss => ss.ServiceProvider == Mock.Of <IServiceProvider>(ssp => (PipelineDelegate <MessagingEnvelope>)ssp.GetService(typeof(PipelineDelegate <MessagingEnvelope>)) == pipeline)))); var mockedSerDes = Mock.Of <IMessageSerDes>(x => x.DeserializeMessageEnvelope(It.IsAny <string>(), It.IsAny <MessageSerDesOptions>()) == envelope); var messageBusSubscriberService = new MessagingTopicSubscriberService( "topicName", mockedSerDes, mockedMessageBusSubscriber, mockedServiceProvider, Mock.Of <MessagingContextAccessor>(), Mock.Of <ITopicRegistry>(), Mock.Of <ILogger <MessagingTopicSubscriberService> >(), new MessagingSubscriberOptions() ); //Act await messageBusSubscriberService.StartAsync(cancellationToken); await messageBusSubscriberCallback("serializedEnvelope"); await messageBusSubscriberService.StopAsync(cancellationToken); //Assert Mock.Get(pipeline).Verify(x => x(envelope, cancellationToken)); }
public async void Should_setNewCorrelationId() { //Arrange var correlationMiddleWare = new CorrelationMiddleware(); var sentMessage = new { Field = "value" }; Guid?correlationId = null; var envelope = new MessagingEnvelope(new System.Collections.Generic.Dictionary <string, string>(), sentMessage); Task Next() { correlationId = CorrelationManager.GetCorrelationId(); return(Task.CompletedTask); } //Act await correlationMiddleWare.Invoke(new MessagingContext(envelope, string.Empty, null), default, Next);
public void Should_not_deserialize_messages_using_wrong_interface() { //Arrange var sut = new NewtonsoftJsonMessageSerDes(Mock.Of <IMessageTypeRegistry>(x => x.ResolveType(It.IsAny <string>(), It.IsAny <IEnumerable <Assembly> >()) == typeof(TestMessage))); var @event = new TestMessage(11232, 1122312, "something"); var envelope = new MessagingEnvelope(new Dictionary <string, string> { [MessagingHeaders.MessageType] = typeof(TestMessage).AssemblyQualifiedName }, @event); var json = sut.SerializeMessageEnvelope(envelope); //Act void Action() => sut.DeserializeMessageEnvelope <ICommand>(json); //Assert ((Action)Action).Should().Throw <Exception>(); }
public async Task Should_execute_pipeline_on_message_received() { //Arrange var message = new TestMessage(); var envelope = new MessagingEnvelope <TestMessage>(new Dictionary <string, string>(), message); var pipeline = Mock.Of <PipelineDelegate <MessagingContext> >(); Func <MessagingEnvelope <TestMessage>, Task> messageBusSubscriberCallback = null; var cancellationToken = new CancellationToken(); var mockedMessageBusSubscriber = Mock.Of <IMessageBus>(); Mock.Get(mockedMessageBusSubscriber) .Setup(x => x.SubscribeAsync(It.IsAny <Func <MessagingEnvelope <TestMessage>, Task> >(), It.IsAny <MessagingSubscriberOptions>(), It.IsAny <CancellationToken>())) .Callback((Func <MessagingEnvelope <TestMessage>, Task> handler, MessagingSubscriberOptions _, CancellationToken token) => { messageBusSubscriberCallback = handler; cancellationToken = token; }) .Returns(Task.FromResult(Mock.Of <IDisposable>())); var mockedServiceProvider = Mock.Of <IServiceProvider>(sp => sp.GetService(typeof(IServiceScopeFactory)) == Mock.Of <IServiceScopeFactory>(ssf => ssf.CreateScope() == Mock.Of <IServiceScope>())); var messageBusSubscriberService = new HostedSubscriber <TestMessage>( mockedMessageBusSubscriber, mockedServiceProvider, Mock.Of <MessagingContextAccessor>(), new MockLogger(), Mock.Of <ITopicRegistry>(), new ExecutionMonitor() ); //Act using var _ = await messageBusSubscriberService.SubscribeAsync(pipeline, new MessagingSubscriberOptions (), cancellationToken); await messageBusSubscriberCallback(envelope); //Assert Mock.Get(pipeline).Verify(x => x(It.Is <MessagingContext>(ctx => ctx.MessagingEnvelope == envelope), cancellationToken)); }
public async void Should_callNextPipelineMiddleware() { //Arrange var dummyPolicy = Policy.Handle <Exception>().RetryAsync(0); var resiliencyMiddleware = new DefaultResiliencyMiddleware( Mock.Of <ILogger <DefaultResiliencyMiddleware> >()); var sentMessage = new { Field = "value" }; var isNextMiddlewareCalled = false; var envelope = new MessagingEnvelope(new System.Collections.Generic.Dictionary <string, string>(), sentMessage); Task Next() { isNextMiddlewareCalled = true; return(Task.CompletedTask); } //Act await resiliencyMiddleware.Invoke(new MessagingContext(envelope, string.Empty, null), default, Next);
public void Should_throw_when_untyped_deserialization_with_incompatible_options() { //Arrange var sut = new NewtonsoftJsonMessageSerDes(Mock.Of <IMessageTypeRegistry>(x => x.ResolveType(It.IsAny <string>(), It.IsAny <IEnumerable <Assembly> >()) == typeof(TestMessage))); var @event = new TestMessage(11232, 1122312, "something"); var envelope = new MessagingEnvelope(new Dictionary <string, string> { [MessagingHeaders.MessageType] = @event.GetType().Name }, @event); var json = sut.SerializeMessageEnvelope(envelope); //Act void Action() => sut.DeserializeMessageEnvelope(json, new MessageSerDesOptions { DeserializationType = DeserializationType.TypeSafe }); //Assert ((Action)Action).Should().Throw <Exception>().WithMessage("*TypeSafe*"); }
private async Task Handle(string message, CancellationToken cancellationToken = default) { MessagingEnvelope messageEnvelope = null; try { messageEnvelope = _messageSerDes.DeserializeMessageEnvelope(message, _subscriberOptions?.SerDes); } catch (Exception ex) { _logger.LogError( "MessagingTopicSubscriberService encountered an error when deserializing a message from topic {TopicName}.\n {Error}", _topic, ex); } using (var scope = _serviceProvider.CreateScope()) { var pipeline = scope.ServiceProvider.GetService <PipelineDelegate <MessagingEnvelope> >(); _messagingContextAccessor.MessagingContext = new MessagingContext(messageEnvelope); await pipeline(messageEnvelope, cancellationToken); } }
public async void Should_callNextPipelineMiddleware() { //Arrange var dummyPolicy = Policy.Handle <Exception>().RetryAsync(0); var resiliencyMiddleware = new DefaultResiliencyMiddleware( Mock.Of <IResiliencyPolicyProvider>(x => x.GetConcurencyExceptionPolicy(It.IsAny <Action <Exception> >()) == dummyPolicy && x.GetOutOfOrderPolicy(It.IsAny <Action <int> >()) == dummyPolicy), Mock.Of <ILogger <DefaultResiliencyMiddleware> >()); var sentMessage = Mock.Of <IMessage>(); var isNextMiddlewareCalled = false; var envelope = new MessagingEnvelope <IMessage>(new System.Collections.Generic.Dictionary <string, string>(), sentMessage); Task Next() { isNextMiddlewareCalled = true; return(Task.CompletedTask); } //Act await resiliencyMiddleware.Invoke(envelope, default, Next);
public void Should_deserialize_with_json_payload() { //Arrange var sut = new NewtonsoftJsonMessageSerDes(Mock.Of <IMessageTypeRegistry>(x => x.ResolveType(It.IsAny <string>(), It.IsAny <IEnumerable <Assembly> >()) == typeof(TestMessage))); var @event = new TestMessage(11232, 1122312, "something"); var envelope = new MessagingEnvelope(new Dictionary <string, string> { [MessagingHeaders.MessageType] = @event.GetType().Name }, @event); var json = sut.SerializeMessageEnvelope(envelope); //Act var deserialized = sut.DeserializeMessageEnvelope(json, new MessageSerDesOptions { DeserializationType = DeserializationType.HeadersOnly }); //Assert deserialized.Should().NotBeNull(); deserialized.Payload.GetType().Should().Be(typeof(string)); (deserialized.Payload as string).Should().ContainAll(@event.ContractId.ToString(), @event.PartnerId.ToString(), @event.Details); }
public MessagingContext(MessagingEnvelope receivedMessageEnvelope) { ReceivedMessageEnvelope = receivedMessageEnvelope; }
public static string GetMessageTypeId(this MessagingEnvelope envelope) { return(envelope.Headers.TryGetValue(MessagingHeaders.MessageType, out var value) ? value : null); }