Пример #1
0
        protected override async Task Terminate(ISubscribeContext context)
        {
            var eventType = context.EventType;

            var publisherAddresses = subscriptionRouter.GetAddressesForEventType(eventType)
                                     .EnsureNonEmpty(() => $"No publisher address could be found for message type {eventType}. Ensure the configured publisher endpoint has at least one known instance.");

            var subscribeTasks = new List <Task>();

            foreach (var publisherAddress in publisherAddresses)
            {
                Logger.Debug($"Subscribing to {eventType.AssemblyQualifiedName} at publisher queue {publisherAddress}");

                var subscriptionMessage = ControlMessageFactory.Create(MessageIntentEnum.Subscribe);

                subscriptionMessage.Headers[Headers.SubscriptionMessageType]    = eventType.AssemblyQualifiedName;
                subscriptionMessage.Headers[Headers.ReplyToAddress]             = subscriberAddress;
                subscriptionMessage.Headers[Headers.SubscriberTransportAddress] = subscriberAddress;
                subscriptionMessage.Headers[Headers.SubscriberEndpoint]         = subscriberEndpoint;
                subscriptionMessage.Headers[Headers.TimeSent]           = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
                subscriptionMessage.Headers[Headers.NServiceBusVersion] = GitFlowVersion.MajorMinorPatch;

                subscribeTasks.Add(SendSubscribeMessageWithRetries(publisherAddress, subscriptionMessage, eventType.AssemblyQualifiedName, context.Extensions));
            }
            await Task.WhenAll(subscribeTasks.ToArray()).ConfigureAwait(false);
        }
Пример #2
0
    public override async Task Invoke(ISubscribeContext context, Func <Task> next)
    {
        var eventType = context.EventType;

        if (publisherTable.TryGetValue(eventType, out var publisherEndpoint))
        {
            Logger.Debug($"Sending subscribe request for {eventType.AssemblyQualifiedName} to router queue {routerAddress} to be forwarded to {publisherEndpoint}");

            var subscriptionMessage = ControlMessageFactory.Create(MessageIntentEnum.Subscribe);

            subscriptionMessage.Headers[Headers.SubscriptionMessageType]          = eventType.AssemblyQualifiedName;
            subscriptionMessage.Headers[Headers.ReplyToAddress]                   = subscriberAddress;
            subscriptionMessage.Headers[Headers.SubscriberTransportAddress]       = subscriberAddress;
            subscriptionMessage.Headers[Headers.SubscriberEndpoint]               = subscriberEndpoint;
            subscriptionMessage.Headers["NServiceBus.Bridge.DestinationEndpoint"] = publisherEndpoint;
            subscriptionMessage.Headers[Headers.TimeSent]           = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
            subscriptionMessage.Headers[Headers.NServiceBusVersion] = "6.3.1"; //The code has been copied from 6.3.1

            var transportOperation   = new TransportOperation(subscriptionMessage, new UnicastAddressTag(routerAddress));
            var transportTransaction = context.Extensions.GetOrCreate <TransportTransaction>();
            await dispatcher.Dispatch(new TransportOperations(transportOperation), transportTransaction, context.Extensions).ConfigureAwait(false);

            if (nativePubSub)
            {
                await next().ConfigureAwait(false);
            }
        }
        else
        {
            await next().ConfigureAwait(false);
        }
    }
Пример #3
0
    public override Task Invoke(IUnsubscribeContext context, Func <Task> next)
    {
        var    eventType = context.EventType;
        string publisherEndpoint;

        if (!publisherTable.TryGetValue(eventType, out publisherEndpoint))
        {
            return(next()); //Invoke the terminator
        }

        Logger.Debug($"Sending unsubscribe request for {eventType.AssemblyQualifiedName} to bridge queue {bridgeAddress} to be forwarded to {publisherEndpoint}");

        var subscriptionMessage = ControlMessageFactory.Create(MessageIntentEnum.Unsubscribe);

        subscriptionMessage.Headers[Headers.SubscriptionMessageType]          = eventType.AssemblyQualifiedName;
        subscriptionMessage.Headers[Headers.ReplyToAddress]                   = subscriberAddress;
        subscriptionMessage.Headers[Headers.SubscriberTransportAddress]       = subscriberAddress;
        subscriptionMessage.Headers[Headers.SubscriberEndpoint]               = subscriberEndpoint;
        subscriptionMessage.Headers["NServiceBus.Bridge.DestinationEndpoint"] = publisherEndpoint;
        subscriptionMessage.Headers[Headers.TimeSent]           = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
        subscriptionMessage.Headers[Headers.NServiceBusVersion] = "6.3.1"; //The code has been copied from 6.3.1

        var transportOperation   = new TransportOperation(subscriptionMessage, new UnicastAddressTag(bridgeAddress));
        var transportTransaction = context.Extensions.GetOrCreate <TransportTransaction>();

        return(dispatcher.Dispatch(new TransportOperations(transportOperation), transportTransaction, context.Extensions));
    }
        protected override Task Terminate(IUnsubscribeContext context)
        {
            var eventType = context.EventType;

            var publisherAddresses = subscriptionRouter.GetAddressesForEventType(eventType);

            if (publisherAddresses.Count == 0)
            {
                throw new Exception($"No publisher address could be found for message type {eventType}. Ensure the configured publisher endpoint has at least one known instance.");
            }

            var unsubscribeTasks = new List <Task>(publisherAddresses.Count);

            foreach (var publisherAddress in publisherAddresses)
            {
                Logger.Debug("Unsubscribing to " + eventType.AssemblyQualifiedName + " at publisher queue " + publisherAddress);

                var unsubscribeMessage = ControlMessageFactory.Create(MessageIntentEnum.Unsubscribe);

                unsubscribeMessage.Headers[Headers.SubscriptionMessageType]    = eventType.AssemblyQualifiedName;
                unsubscribeMessage.Headers[Headers.ReplyToAddress]             = replyToAddress;
                unsubscribeMessage.Headers[Headers.SubscriberTransportAddress] = replyToAddress;
                unsubscribeMessage.Headers[Headers.SubscriberEndpoint]         = endpoint;
                unsubscribeMessage.Headers[Headers.TimeSent]           = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
                unsubscribeMessage.Headers[Headers.NServiceBusVersion] = GitFlowVersion.MajorMinorPatch;

                unsubscribeTasks.Add(SendUnsubscribeMessageWithRetries(publisherAddress, unsubscribeMessage, eventType.AssemblyQualifiedName, context.Extensions));
            }
            return(Task.WhenAll(unsubscribeTasks));
        }
    async Task Send(Subscriber subscriber, string publisherEndpoint, string messageType, MessageIntentEnum intent, IRawEndpoint dispatcher)
    {
        var publisherInstances = endpointInstances.FindInstances(publisherEndpoint);
        var publisherAddresses = publisherInstances.Select(i => dispatcher.ToTransportAddress(LogicalAddress.CreateRemoteAddress(i))).ToArray();

        foreach (var publisherAddress in publisherAddresses)
        {
            Logger.Debug(
                $"Sending {intent} request for {messageType} to {publisherAddress} on behalf of {subscriber.TransportAddress}.");

            var subscriptionMessage = ControlMessageFactory.Create(intent);

            subscriptionMessage.Headers[Headers.SubscriptionMessageType]          = messageType;
            subscriptionMessage.Headers[Headers.ReplyToAddress]                   = dispatcher.TransportAddress;
            subscriptionMessage.Headers[Headers.SubscriberTransportAddress]       = dispatcher.TransportAddress;
            subscriptionMessage.Headers[Headers.SubscriberEndpoint]               = dispatcher.EndpointName;
            subscriptionMessage.Headers["NServiceBus.Bridge.DestinationEndpoint"] = publisherEndpoint;
            subscriptionMessage.Headers[Headers.TimeSent]           = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
            subscriptionMessage.Headers[Headers.NServiceBusVersion] = "6.3.1"; //The code has been copied from 6.3.1

            var transportOperation = new TransportOperation(subscriptionMessage, new UnicastAddressTag(publisherAddress));
            await dispatcher.Dispatch(new TransportOperations(transportOperation), new TransportTransaction(),
                                      new ContextBag()).ConfigureAwait(false);
        }
    }
Пример #6
0
        protected override async Task Terminate(IUnsubscribeContext context)
        {
            var eventType     = context.EventType;
            var eventMetadata = messageMetadataRegistry.GetMessageMetadata(eventType);

            await subscriptionManager.Unsubscribe(eventMetadata, context.Extensions, context.CancellationToken).ConfigureAwait(false);


            var publisherAddresses = subscriptionRouter.GetAddressesForEventType(eventType);

            if (publisherAddresses.Count == 0)
            {
                return;
            }

            var unsubscribeTasks = new List <Task>(publisherAddresses.Count);

            foreach (var publisherAddress in publisherAddresses)
            {
                Logger.Debug("Unsubscribing to " + eventType.AssemblyQualifiedName + " at publisher queue " + publisherAddress);

                var unsubscribeMessage = ControlMessageFactory.Create(MessageIntentEnum.Unsubscribe);

                unsubscribeMessage.Headers[Headers.SubscriptionMessageType]    = eventType.AssemblyQualifiedName;
                unsubscribeMessage.Headers[Headers.ReplyToAddress]             = replyToAddress;
                unsubscribeMessage.Headers[Headers.SubscriberTransportAddress] = replyToAddress;
                unsubscribeMessage.Headers[Headers.SubscriberEndpoint]         = endpoint;
                unsubscribeMessage.Headers[Headers.TimeSent]           = DateTimeOffsetHelper.ToWireFormattedString(DateTimeOffset.UtcNow);
                unsubscribeMessage.Headers[Headers.NServiceBusVersion] = GitVersionInformation.MajorMinorPatch;

                unsubscribeTasks.Add(SendUnsubscribeMessageWithRetries(publisherAddress, unsubscribeMessage, eventType.AssemblyQualifiedName, context.Extensions, 0, context.CancellationToken));
            }

            await Task.WhenAll(unsubscribeTasks).ConfigureAwait(false);
        }
        protected override async Task Terminate(ISubscribeContext context)
        {
            var eventType = context.EventType;

            await subscriptionManager.Subscribe(eventType, context.Extensions).ConfigureAwait(false);

            var publisherAddresses = subscriptionRouter.GetAddressesForEventType(eventType);

            if (publisherAddresses.Count == 0)
            {
                return;
            }

            var subscribeTasks = new List <Task>(publisherAddresses.Count);

            foreach (var publisherAddress in publisherAddresses)
            {
                Logger.Debug($"Subscribing to {eventType.AssemblyQualifiedName} at publisher queue {publisherAddress}");

                var subscriptionMessage = ControlMessageFactory.Create(MessageIntentEnum.Subscribe);

                subscriptionMessage.Headers[Headers.SubscriptionMessageType]    = eventType.AssemblyQualifiedName;
                subscriptionMessage.Headers[Headers.ReplyToAddress]             = subscriberAddress;
                subscriptionMessage.Headers[Headers.SubscriberTransportAddress] = subscriberAddress;
                subscriptionMessage.Headers[Headers.SubscriberEndpoint]         = subscriberEndpoint;
                subscriptionMessage.Headers[Headers.TimeSent]           = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
                subscriptionMessage.Headers[Headers.NServiceBusVersion] = GitVersionInformation.MajorMinorPatch;

                subscribeTasks.Add(SendSubscribeMessageWithRetries(publisherAddress, subscriptionMessage, eventType.AssemblyQualifiedName, context.Extensions));
            }

            await Task.WhenAll(subscribeTasks).ConfigureAwait(false);
        }
        protected override Task Terminate(ISubscribeContext context)
        {
            var eventType = context.EventType;

            var publisherAddresses = subscriptionRouter.GetAddressesForEventType(eventType);

            if (publisherAddresses.Count == 0)
            {
                throw new Exception($"No publisher address could be found for message type '{eventType}'. Ensure that a publisher has been configured for the event type and that the configured publisher endpoint has at least one known instance.");
            }

            var subscribeTasks = new List <Task>(publisherAddresses.Count);

            foreach (var publisherAddress in publisherAddresses)
            {
                Logger.Debug($"Subscribing to {eventType.AssemblyQualifiedName} at publisher queue {publisherAddress}");

                var subscriptionMessage = ControlMessageFactory.Create(MessageIntentEnum.Subscribe);

                subscriptionMessage.Headers[Headers.SubscriptionMessageType]    = eventType.AssemblyQualifiedName;
                subscriptionMessage.Headers[Headers.ReplyToAddress]             = subscriberAddress;
                subscriptionMessage.Headers[Headers.SubscriberTransportAddress] = subscriberAddress;
                subscriptionMessage.Headers[Headers.SubscriberEndpoint]         = subscriberEndpoint;
                subscriptionMessage.Headers[Headers.TimeSent]           = DateTimeOffsetHelper.ToWireFormattedString(DateTimeOffset.UtcNow);
                subscriptionMessage.Headers[Headers.NServiceBusVersion] = GitVersionInformation.MajorMinorPatch;

                subscribeTasks.Add(SendSubscribeMessageWithRetries(publisherAddress, subscriptionMessage, eventType.AssemblyQualifiedName, context.Extensions));
            }
            return(Task.WhenAll(subscribeTasks));
        }
Пример #9
0
    static async Task Main()
    {
        Console.Title = "Case00041163.OccasionalSubscriber";

        var endpointConfiguration = RawEndpointConfiguration.Create(Console.Title, (context, messages) => Task.CompletedTask, "error");

        endpointConfiguration.UseTransport <MsmqTransport>();

        var endpointInstance = await RawEndpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        var subscriptionMessage = ControlMessageFactory.Create(MessageIntentEnum.Subscribe);

        subscriptionMessage.Headers[Headers.SubscriptionMessageType]    = typeof(MyEvent).AssemblyQualifiedName;
        subscriptionMessage.Headers[Headers.ReplyToAddress]             = "Case00041163.OccasionalSubscriber@FAKEPC";
        subscriptionMessage.Headers[Headers.SubscriberTransportAddress] = "Case00041163.OccasionalSubscriber@FAKEPC";
        subscriptionMessage.Headers[Headers.SubscriberEndpoint]         = "Case00041163.OccasionalSubscriber";
        subscriptionMessage.Headers[Headers.TimeSent]           = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
        subscriptionMessage.Headers[Headers.NServiceBusVersion] = "5.6.4";

        var operation = new TransportOperation(subscriptionMessage, new UnicastAddressTag("Case00041163.Publisher"));

        await endpointInstance.Dispatch(new TransportOperations(operation), new TransportTransaction(), new ContextBag()).ConfigureAwait(false);

        await endpointInstance.Stop().ConfigureAwait(false);
    }
Пример #10
0
    async Task Send(Subscriber subscriber, string publisherEndpoint, string messageType, MessageIntentEnum intent, IRawEndpoint dispatcher, InterBridgeRoutingSettings forwarding)
    {
        var typeFullName = messageType.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).First();

        if (!forwarding.PublisherTable.TryGetValue(typeFullName, out var nextHopEndpoint))
        {
            return;
        }

        var subscriptionMessage = ControlMessageFactory.Create(intent);

        if (publisherEndpoint != null)
        {
            subscriptionMessage.Headers["NServiceBus.Bridge.DestinationEndpoint"] = publisherEndpoint;
        }
        subscriptionMessage.Headers[Headers.SubscriptionMessageType]    = messageType;
        subscriptionMessage.Headers[Headers.ReplyToAddress]             = dispatcher.TransportAddress;
        subscriptionMessage.Headers[Headers.SubscriberTransportAddress] = dispatcher.TransportAddress;
        subscriptionMessage.Headers[Headers.SubscriberEndpoint]         = dispatcher.EndpointName;
        subscriptionMessage.Headers[Headers.TimeSent]           = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
        subscriptionMessage.Headers[Headers.NServiceBusVersion] = "6.3.1"; //The code has been copied from 6.3.1

        var publisherInstances = endpointInstances.FindInstances(nextHopEndpoint);
        var publisherAddresses = publisherInstances.Select(i => dispatcher.ToTransportAddress(LogicalAddress.CreateRemoteAddress(i))).ToArray();

        foreach (var publisherAddress in publisherAddresses)
        {
            Logger.Debug(
                $"Sending {intent} request for {messageType} to {publisherAddress} on behalf of {subscriber.TransportAddress}.");

            var transportOperation = new TransportOperation(subscriptionMessage, new UnicastAddressTag(publisherAddress));
            await dispatcher.Dispatch(new TransportOperations(transportOperation), new TransportTransaction(),
                                      new ContextBag()).ConfigureAwait(false);
        }
    }
Пример #11
0
 /// <summary>
 /// Deserializes a ControlMessage from a NGRIDControllerMessage.
 /// </summary>
 /// <param name="controllerMessage">NGRIDControllerMessage that includes ControlMessage</param>
 /// <returns>Deserialized ControlMessage object.</returns>
 private static ControlMessage DeserializeControlMessage(NGRIDControllerMessage controllerMessage)
 {
     return(NGRIDSerializationHelper.DeserializeFromByteArray(
                () =>
                ControlMessageFactory.CreateMessageByTypeId(controllerMessage.ControllerMessageTypeId),
                controllerMessage.MessageData));
 }
        protected override async Task Terminate(ISubscribeContext context)
        {
            var subscribeTasks = new List <Task>();

            foreach (var eventType in context.EventTypes)
            {
                try
                {
                    var publisherAddresses = subscriptionRouter.GetAddressesForEventType(eventType);
                    if (publisherAddresses.Count == 0)
                    {
                        throw new Exception($"No publisher address could be found for message type '{eventType}'. Ensure that a publisher has been configured for the event type and that the configured publisher endpoint has at least one known instance.");
                    }

                    foreach (var publisherAddress in publisherAddresses)
                    {
                        Logger.Debug($"Subscribing to {eventType.AssemblyQualifiedName} at publisher queue {publisherAddress}");

                        var subscriptionMessage = ControlMessageFactory.Create(MessageIntentEnum.Subscribe);

                        subscriptionMessage.Headers[Headers.SubscriptionMessageType]    = eventType.AssemblyQualifiedName;
                        subscriptionMessage.Headers[Headers.ReplyToAddress]             = subscriberAddress;
                        subscriptionMessage.Headers[Headers.SubscriberTransportAddress] = subscriberAddress;
                        subscriptionMessage.Headers[Headers.SubscriberEndpoint]         = subscriberEndpoint;
                        subscriptionMessage.Headers[Headers.TimeSent]           = DateTimeOffsetHelper.ToWireFormattedString(DateTimeOffset.UtcNow);
                        subscriptionMessage.Headers[Headers.NServiceBusVersion] = GitVersionInformation.MajorMinorPatch;

                        subscribeTasks.Add(SendSubscribeMessageWithRetries(publisherAddress, subscriptionMessage, eventType.AssemblyQualifiedName, context.Extensions, 0, context.CancellationToken));
                    }
                }
#pragma warning disable PS0019 // Do not catch Exception without considering OperationCanceledException - Tasks are not observed until below
                catch (Exception e)
#pragma warning restore PS0019 // Do not catch Exception without considering OperationCanceledException
                {
                    subscribeTasks.Add(Task.FromException(e));
                }
            }

            var t = Task.WhenAll(subscribeTasks);
            try
            {
                await t.ConfigureAwait(false);
            }
            catch (Exception)
            {
                // if subscribing via SubscribeAll, throw an AggregateException
                if (context.Extensions.TryGet <bool>(MessageSession.SubscribeAllFlagKey, out var flag) && flag)
                {
                    throw t.Exception;
                }

                // otherwise throw the first exception to not change exception behavior when calling subscribe.
                throw;
            }
        }
Пример #13
0
        public Task CancelDeferredMessages(string messageKey, IBehaviorContext context)
        {
            var controlMessage = ControlMessageFactory.Create(MessageIntentEnum.Send);

            controlMessage.Headers[Headers.SagaId] = messageKey;
            controlMessage.Headers[TimeoutManagerHeaders.ClearTimeouts] = bool.TrueString;

            var dispatchContext = new RoutingContext(controlMessage, new UnicastRoutingStrategy(timeoutManagerAddress), context);

            return(dispatchContext.InvokePipeline <IRoutingContext>());
        }
Пример #14
0
        internal async Task SpinOnce(CancellationToken cancellationToken)
        {
            if (NextRetrieval > currentTimeProvider() || cancellationToken.IsCancellationRequested)
            {
                return;
            }

            Logger.DebugFormat("Polling for timeouts at {0}.", currentTimeProvider());
            var timeoutChunk = await timeoutsFetcher.GetNextChunk(startSlice).ConfigureAwait(false);

            foreach (var timeoutData in timeoutChunk.DueTimeouts)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }

                var dispatchRequest = ControlMessageFactory.Create(MessageIntentEnum.Send);

                dispatchRequest.Headers["Timeout.Id"] = timeoutData.Id;

                var transportOperation = new TransportOperation(dispatchRequest, new UnicastAddressTag(dispatcherAddress));
                await dispatcher.Dispatch(new TransportOperations(transportOperation), new TransportTransaction(), new ContextBag()).ConfigureAwait(false);

                if (startSlice < timeoutData.DueTime)
                {
                    startSlice = timeoutData.DueTime;
                }
            }

            lock (lockObject)
            {
                var nextTimeToQuery = timeoutChunk.NextTimeToQuery;

                // we cap the next retrieval to max 1 minute this will make sure that we trip the circuit breaker if we
                // loose connectivity to our storage. This will also make sure that timeouts added (during migration) direct to storage
                // will be picked up after at most 1 minute
                var maxNextRetrieval = currentTimeProvider() + MaxNextRetrievalDelay;

                NextRetrieval = nextTimeToQuery > maxNextRetrieval ? maxNextRetrieval : nextTimeToQuery;

                Logger.DebugFormat("Polling next retrieval is at {0}.", NextRetrieval.ToLocalTime());
            }

            circuitBreaker.Success();
        }
Пример #15
0
        Task SendReadyMessage(int capacity, bool isStarting)
        {
            //we use the actual address to make sure that the worker inside the master node will check in correctly
            var readyMessage = ControlMessageFactory.Create(MessageIntentEnum.Send);

            readyMessage.Headers.Add(LegacyDistributorHeaders.WorkerCapacityAvailable, capacity.ToString());
            readyMessage.Headers.Add(LegacyDistributorHeaders.WorkerSessionId, workerSessionId);
            readyMessage.Headers.Add(Headers.ReplyToAddress, receiveAddress);

            if (isStarting)
            {
                readyMessage.Headers.Add(LegacyDistributorHeaders.WorkerStarting, bool.TrueString);
            }

            var transportOperation = new TransportOperation(readyMessage, new UnicastAddressTag(distributorControlAddress));

            return(dispatcher.Dispatch(new TransportOperations(transportOperation), new TransportTransaction(), new ContextBag()));
        }
Пример #16
0
    async Task SendSubscribeMessage(ISubscribeContext context, Type eventType, string publisherEndpoint, string router)
    {
        var subscriptionMessage = ControlMessageFactory.Create(MessageIntentEnum.Subscribe);

        subscriptionMessage.Headers[Headers.SubscriptionMessageType]    = eventType.AssemblyQualifiedName;
        subscriptionMessage.Headers[Headers.ReplyToAddress]             = subscriberAddress;
        subscriptionMessage.Headers[Headers.SubscriberTransportAddress] = subscriberAddress;
        subscriptionMessage.Headers[Headers.SubscriberEndpoint]         = subscriberEndpoint;
        subscriptionMessage.Headers[Headers.TimeSent]           = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
        subscriptionMessage.Headers[Headers.NServiceBusVersion] = "6.3.1"; //The code has been copied from 6.3.1

        if (publisherEndpoint != null)
        {
            subscriptionMessage.Headers["NServiceBus.Bridge.DestinationEndpoint"] = publisherEndpoint;
        }

        var transportOperation   = new TransportOperation(subscriptionMessage, new UnicastAddressTag(router));
        var transportTransaction = context.Extensions.GetOrCreate <TransportTransaction>();
        await dispatcher.Dispatch(new TransportOperations(transportOperation), transportTransaction, context.Extensions).ConfigureAwait(false);
    }
Пример #17
0
        /// <summary>
        /// Handles MessageReceived event.
        /// All messages received from all controllers comes to this method.
        /// </summary>
        /// <param name="sender">Sender object</param>
        /// <param name="e">Event arguments</param>
        private void MDSController_MessageReceived(object sender, MessageReceivedFromRemoteApplicationEventArgs e)
        {
            try
            {
                //Response to Ping messages
                if ((e.Message.MessageTypeId == MDSMessageFactory.MessageTypeIdMDSPingMessage) && string.IsNullOrEmpty(e.Message.RepliedMessageId))
                {
                    //Reply ping message
                    SendMessage(new MDSPingMessage {
                        RepliedMessageId = e.Message.MessageId
                    }, e.Communicator);
                    return;
                }

                //Do not process messages other than MDSControllerMessage
                if (e.Message.MessageTypeId != MDSMessageFactory.MessageTypeIdMDSControllerMessage)
                {
                    return;
                }

                //Cast message to MDSControllerMessage
                var controllerMessage = e.Message as MDSControllerMessage;
                if (controllerMessage == null)
                {
                    return;
                }

                //Create (deserialize) ControlMessage from MessageData of controllerMessage object
                var controlMessage = MDSSerializationHelper.DeserializeFromByteArray(
                    () =>
                    ControlMessageFactory.CreateMessageByTypeId(controllerMessage.ControllerMessageTypeId),
                    controllerMessage.MessageData);

                //Process message
                ProcessControllerMessage(e.Communicator, controllerMessage, controlMessage);
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.Message, ex);
            }
        }
Пример #18
0
    public static OutgoingMessage CreateMessage(string ultimateDestination, string messageType, string localAddress, string localEndpoint, MessageIntentEnum intent)
    {
        var subscriptionMessage = ControlMessageFactory.Create(intent);

        subscriptionMessage.Headers[Headers.SubscriptionMessageType] = messageType;
        subscriptionMessage.Headers[Headers.ReplyToAddress]          = localAddress;
        if (localAddress != null)
        {
            subscriptionMessage.Headers[Headers.SubscriberTransportAddress] = localAddress;
        }
        subscriptionMessage.Headers[Headers.SubscriberEndpoint] = localEndpoint;
        subscriptionMessage.Headers[Headers.TimeSent]           = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
        subscriptionMessage.Headers[Headers.NServiceBusVersion] = "6.3.1"; //The code has been copied from 6.3.1

        if (ultimateDestination != null)
        {
            subscriptionMessage.Headers["NServiceBus.Bridge.DestinationEndpoint"] = ultimateDestination;
        }

        return(subscriptionMessage);
    }
        public async Task VerifyIfServiceControlQueueExists()
        {
            try
            {
                // In order to verify if the queue exists, we are sending a control message to SC.
                // If we are unable to send a message because the queue doesn't exist, then we can fail fast.
                // We currently don't have a way to check if Queue exists in a transport agnostic way,
                // hence the send.
                var outgoingMessage = ControlMessageFactory.Create(MessageIntentEnum.Send);
                outgoingMessage.Headers[Headers.ReplyToAddress] = settings.LocalAddress();
                var operation = new TransportOperation(outgoingMessage, new UnicastAddressTag(serviceControlBackendAddress));
                await messageSender.Dispatch(new TransportOperations(operation), new TransportTransaction(), new ContextBag()).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                const string errMsg = @"You have ServiceControl plugins installed in your endpoint, however, this endpoint is unable to contact the ServiceControl Backend to report endpoint information.
Please ensure that the Particular ServiceControl queue specified is correct.";

                throw new Exception(errMsg, ex);
            }
        }
        public async Task Start(IMessageDispatcher dispatcher, CancellationToken cancellationToken = default)
        {
            messageSender = dispatcher;
            try
            {
                // In order to verify if the queue exists, we are sending a control message to SC.
                // If we are unable to send a message because the queue doesn't exist, then we can fail fast.
                // We currently don't have a way to check if Queue exists in a transport agnostic way,
                // hence the send.
                var outgoingMessage = ControlMessageFactory.Create(MessageIntentEnum.Send);
                outgoingMessage.Headers[Headers.ReplyToAddress] = localAddress;
                var operation = new TransportOperation(outgoingMessage, new UnicastAddressTag(destinationQueue));
                await messageSender.Dispatch(new TransportOperations(operation), new TransportTransaction(), cancellationToken).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                const string errMsg = @"You have enabled saga state change auditing in your endpoint, however, this endpoint is unable to contact the ServiceControl to report endpoint information.
Please ensure that the specified queue is correct.";

                throw new Exception(errMsg, ex);
            }
        }
        protected override async Task Terminate(ISubscribeContext context)
        {
            var eventMetadata = new MessageMetadata[context.EventTypes.Length];

            for (int i = 0; i < context.EventTypes.Length; i++)
            {
                eventMetadata[i] = messageMetadataRegistry.GetMessageMetadata(context.EventTypes[i]);
            }
            try
            {
                await subscriptionManager.SubscribeAll(eventMetadata, context.Extensions, context.CancellationToken).ConfigureAwait(false);
            }
            catch (AggregateException e)
            {
                if (context.Extensions.TryGet <bool>(MessageSession.SubscribeAllFlagKey, out var flag) && flag)
                {
                    throw;
                }

                // if this is called from Subscribe, rethrow the expected single exception
                throw e.InnerException ?? e;
            }

            var subscribeTasks = new List <Task>();

            foreach (var eventType in context.EventTypes)
            {
                try
                {
                    var publisherAddresses = subscriptionRouter.GetAddressesForEventType(eventType);
                    if (publisherAddresses.Count == 0)
                    {
                        continue;
                    }

                    foreach (var publisherAddress in publisherAddresses)
                    {
                        Logger.Debug($"Subscribing to {eventType.AssemblyQualifiedName} at publisher queue {publisherAddress}");

                        var subscriptionMessage = ControlMessageFactory.Create(MessageIntentEnum.Subscribe);

                        subscriptionMessage.Headers[Headers.SubscriptionMessageType]    = eventType.AssemblyQualifiedName;
                        subscriptionMessage.Headers[Headers.ReplyToAddress]             = subscriberAddress;
                        subscriptionMessage.Headers[Headers.SubscriberTransportAddress] = subscriberAddress;
                        subscriptionMessage.Headers[Headers.SubscriberEndpoint]         = subscriberEndpoint;
                        subscriptionMessage.Headers[Headers.TimeSent]           = DateTimeOffsetHelper.ToWireFormattedString(DateTimeOffset.UtcNow);
                        subscriptionMessage.Headers[Headers.NServiceBusVersion] = GitVersionInformation.MajorMinorPatch;

                        subscribeTasks.Add(SendSubscribeMessageWithRetries(publisherAddress, subscriptionMessage, eventType.AssemblyQualifiedName, context.Extensions, 0, context.CancellationToken));
                    }
                }
#pragma warning disable PS0019 // Do not catch Exception without considering OperationCanceledException - Tasks are not observed until below
                catch (Exception e)
#pragma warning restore PS0019 // Do not catch Exception without considering OperationCanceledException
                {
                    subscribeTasks.Add(Task.FromException(e));
                }
            }

            var t = Task.WhenAll(subscribeTasks);
            try
            {
                await t.ConfigureAwait(false);
            }
            catch (Exception)
            {
                // if subscribing via SubscribeAll, throw an AggregateException
                if (context.Extensions.TryGet <bool>(MessageSession.SubscribeAllFlagKey, out var flag) && flag)
                {
                    throw t.Exception;
                }

                // otherwise throw the first exception to not change exception behavior when calling subscribe.
                throw;
            }
        }