Пример #1
0
        private SendResponse SendDirectNotify(NotifyRequest request, ISenderChannel channel)
        {
            var recipient = request.Recipient as IDirectRecipient;

            if (recipient == null)
            {
                throw new ArgumentException("request.Recipient not IDirectRecipient", "request");
            }

            request.CurrentSender = channel.SenderName;

            NoticeMessage noticeMessage;
            var           oops = CreateNoticeMessageFromNotifyRequest(request, channel.SenderName, out noticeMessage);

            if (oops != null)
            {
                return(oops);
            }

            request.CurrentMessage = noticeMessage;
            var preventresponse = CheckPreventInterceptors(request, InterceptorPlace.MessageSend, channel.SenderName);

            if (preventresponse != null)
            {
                return(preventresponse);
            }

            channel.SendAsync(noticeMessage);

            return(new SendResponse(noticeMessage, channel.SenderName, SendResult.Inprogress));
        }
Пример #2
0
 public DispatchRequest(INoticeMessage message, ISenderChannel senderChannel, Action <INoticeMessage, SendResponse> callback)
 {
     Interlocked.Increment(ref DispatchNum);
     NoticeMessage    = message;
     SenderChannel    = senderChannel;
     DispatchCallback = callback;
 }
Пример #3
0
        /// <summary>
        /// Метод подписки на события журнала.
        /// </summary>
        /// <param name="filter">Фильтр событий.</param>
        /// <param name="channel">Канал передачи событий.</param>
        /// <param name="cookie">Идентификатор подписки.</param>
        void ISrvcBlackboard.Subscribe(IEventFilter filter, ChannelDescription channel, Guid cookie)
        {
            Logger.Debug("ISrvcBlackboard.Subscribe: подписался {0}", cookie);
            // создаем канал
            ISenderChannel ch = channel != null?UnitySingleton.Resolve <ITransport>().CreateSenderChannel(channel) : null;

            _subsribeTask.Run(() => (this as IBlackboard).Subscribe(filter, ch, cookie));
        }
Пример #4
0
 /// <summary>
 /// Метод подписки на события журнала.
 /// </summary>
 /// <param name="filter">Фильтр событий.</param>
 /// <param name="channel">Канал передачи событий.</param>
 /// <param name="cookie">Идентификатор подписки.</param>
 void IBlackboard.Subscribe(IEventFilter filter, ISenderChannel channel, Guid cookie)
 {
     // локальный подписчик
     if (filter.Host == UnitySingleton.Resolve <ITransport>().HostID)
     {
         // добавляем нового подписчика в карту
         _localEventsSubscribers.Add(cookie, filter, channel);
     }
 }
Пример #5
0
        public void UngeristerSender(ISenderChannel sender)
        {
            if (sender == null)
            {
                throw new ArgumentNullException("sender");
            }
            if (sender.SenderName == null)
            {
                throw new ArgumentException("sender.SenderName is empty", "sender");
            }

            lock (channels)
            {
                channels.Remove(sender.SenderName);
            }
        }
        public async Task <bool> OnMessageAsync(Message message, ISenderChannel channel, CancellationToken cancellationToken)
        {
            using var _ = _logger.BeginScope(
                      new Dictionary <string, string>
            {
                { "id", message.Id },
                { "from", message.From },
                { "to", message.To },
                { "type", message.Type },
            });

            await InvokeListenersAsync <IMessageListener, Message>(
                message,
                channel,
                cancellationToken);

            return(true);
        }
        public async Task <bool> OnNotificationAsync(Notification notification, ISenderChannel channel, CancellationToken cancellationToken)
        {
            using var _ = _logger.BeginScope(
                      new Dictionary <string, string>
            {
                { "id", notification.Id },
                { "from", notification.From },
                { "to", notification.To },
                { "event", notification.Event.ToString() },
            });

            await InvokeListenersAsync <INotificationListener, Notification>(
                notification,
                channel,
                cancellationToken);

            return(true);
        }
        public async Task <bool> OnCommandAsync(Command command, ISenderChannel channel, CancellationToken cancellationToken)
        {
            using var _ = _logger.BeginScope(
                      new Dictionary <string, string>
            {
                { "Command.Id", command.Id },
                { "Command.From", command.From },
                { "Command.To", command.To },
                { "Command.Method", command.Method.ToString() },
                { "Command.Uri", command.Uri },
                { "Command.Type", command.Type },
            });

            await InvokeListenersAsync <ICommandListener, Command>(
                command,
                channel,
                cancellationToken);

            return(true);
        }
Пример #9
0
        /// <summary>
        /// Метод добавления нового подписчика.
        /// </summary>
        /// <param name="cookie">Идентификатор.</param>
        /// <param name="filter">Фильтр событий.</param>
        /// <param name="channel">Канал передачи событий.</param>
        public void Add(Guid cookie, IEventFilter filter, ISenderChannel channel)
        {
#if LOG_SUBSCRIBERS
            _logger.Debug("LocalEventsSubscribersList.Add cookie: {0}; filter: {1}; channel: {2}", cookie.ToString(), filter.ToString(), channel.ToString());
#endif // LOG_SUBSCRIBERS

            lock (_subscribers)
            {
                if (!_subscribers.ContainsKey(cookie))
                {
                    if (channel == null)
                    {
                        // иногда, в нештатных ситуациях к нам приходит Update (канал null) для удаленного подписчика
                        // это возможно при обрыве связи между хостами или падении сред. Логгирование добавлено для
                        // проверки кто и почему выполняет update.
                        _logger.Error("LocalEventsSubscribersList:Add channel is null!!! cookie: " + cookie);
                        throw new ArgumentNullException("channel");
                    }
                    _subscribers[cookie] = new SubscriberLocalEvents(cookie, filter, channel);

                    var subsriberChannel = _subscribers[cookie].SendChannel as ICommunicationChannel;
                    subsriberChannel.StateChanged += commChannel_StateChanged;
                }
                else // обновляем подписчика
                {
                    _subscribers[cookie].Filter = filter;

                    if (channel != null)
                    {
                        _subscribers[cookie].SendChannel = channel;
                    }
                }
            }

            var commChannel = channel as ICommunicationChannel;
            if (null != commChannel)
            {
                commChannel.StateChanged += commChannel_StateChanged;
            }
        }
        private async Task <int> InvokeListenersAsync <TListener, TEnvelope>(
            TEnvelope envelope,
            ISenderChannel channel,
            CancellationToken cancellationToken)
            where TEnvelope : Envelope, new()
            where TListener : IEnvelopeListener <TEnvelope>
        {
            using var scope = _serviceScopeFactory.CreateScope();

            var channelContext  = new ChannelContext(channel, _channelProvider);
            var contextProvider = scope.ServiceProvider.GetRequiredService <ChannelContextProvider>();

            contextProvider.SetContext(channelContext);

            try
            {
                var listeners = scope
                                .ServiceProvider
                                .GetServices <TListener>()
                                ?.Where(l => l.Filter(envelope))
                                .ToArray();

                if (listeners != null && listeners.Length > 0)
                {
                    await Task.WhenAll(
                        listeners
                        .Select(l =>
                                Task.Run(() => l.OnEnvelopeAsync(envelope, cancellationToken), cancellationToken)));

                    return(listeners.Length);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "{EnvelopeType} processing failed", typeof(TEnvelope).Name);
            }

            return(0);
        }
Пример #11
0
        public void RegisterSender(ISenderChannel sender)
        {
            if (sender == null)
            {
                throw new ArgumentNullException("sender");
            }
            if (sender.SenderName == null)
            {
                throw new ArgumentException("sender.SenderName is empty", "sender");
            }

            lock (channels)
            {
                if (channels.ContainsKey(sender.SenderName))
                {
                    if (channels[sender.SenderName].Equals(sender))
                    {
                        return;
                    }
                    channels.Remove(sender.SenderName);
                }
                channels.Add(sender.SenderName, sender);
            }
        }
Пример #12
0
 /// <summary>
 /// Конструктор класса.
 /// </summary>
 /// <param name="id">Идентификатор.</param>
 /// <param name="filter">Фильтр событий.</param>
 /// <param name="subsChannel">Канал передачи событий.</param>
 public SubscriberLocalEvents(Guid id, IEventFilter filter, ISenderChannel subsChannel)
 {
     ID          = id;
     Filter      = filter;
     SendChannel = subsChannel;
 }
Пример #13
0
        private SendResponse SendDirectNotify(NotifyRequest request, ISenderChannel channel)
        {
            var recipient = request.Recipient as IDirectRecipient;
            if (recipient == null) throw new ArgumentException("request.Recipient not IDirectRecipient", "request");

            request.CurrentSender = channel.SenderName;

            NoticeMessage noticeMessage;
            var oops = CreateNoticeMessageFromNotifyRequest(request, channel.SenderName, out noticeMessage);
            if (oops != null) return oops;

            request.CurrentMessage = noticeMessage;
            var preventresponse = CheckPreventInterceptors(request, InterceptorPlace.MessageSend, channel.SenderName);
            if (preventresponse != null) return preventresponse;

            channel.SendAsync(noticeMessage);

            return new SendResponse(noticeMessage, channel.SenderName, SendResult.Inprogress);
        }
Пример #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SenderEndPoint"/> class.
 /// </summary>
 /// <param name="uri">The URI.</param>
 /// <param name="receiverChannel">The channel.</param>
 public SenderEndPoint(Uri uri, ISenderChannel receiverChannel)
 {
     Uri = uri;
     _receiverChannel = receiverChannel;
 }
Пример #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SenderEndPoint"/> class.
 /// </summary>
 /// <param name="uri">The URI.</param>
 /// <param name="receiverChannel">The channel.</param>
 public SenderEndPoint(Uri uri, ISenderChannel receiverChannel)
 {
     Uri = uri;
     _receiverChannel = receiverChannel;
 }
Пример #16
0
 public ChannelContext(ISenderChannel channel, IChannelProvider channelProvider)
 {
     Channel          = channel;
     _channelProvider = channelProvider;
 }