Example #1
0
        private void EventLoop()
        {
            var task = _proxy.ExecuteRequestAsync(new Request
            {
                Uri     = EventsUri,
                Method  = HttpMethod.Get,
                Timeout = Timeout.Infinite
            });

            task.Wait();

            var response = task.Result;

            if (response?.StatusCode == HttpStatusCode.OK)
            {
                var evt = response?.Data?.FromBytes <Event>();
                if (evt != null)
                {
                    EventsUri = new Uri(evt.Links?.Resync?.Href ?? evt.Links.Next.Href, UriKind.Relative);
                    if (evt.Links?.Resync == null)
                    {
                        OnEventReceived?.Invoke(this, new EventReceivedEventArgs
                        {
                            Resource = evt
                        });
                    }
                }
            }
            else if (response?.StatusCode == HttpStatusCode.Conflict)
            {
                _error = response?.Data?.FromBytes <Error>();
                Stop();
            }
        }
Example #2
0
        /// <summary>
        /// Вызывает нужный метод-обработчик на основе типа события из БД
        /// </summary>
        private void HandleDbNotification(object sender, NpgsqlNotificationEventArgs?e)
        {
            _logger.LogTrace($"Получено новое событие от БД {GetDbLogName()}: " +
                             $"PID = {e?.PID}, " +
                             $"Channel = \"{e?.Channel}\", " +
                             $"Payload = \"{e?.Payload}\"");

            if (!String.IsNullOrEmpty(e?.Channel) && _eventsToSubscribe.Contains(e.Channel))
            {
                try
                {
                    _logger.LogTrace($"Вызов обработчика для события от БД {GetDbLogName()} с PID = {e.PID} (channel = \"{e.Channel}\")...");
                    OnEventReceived?.Invoke(this, new DbEvent(_dbOptions, e.Channel, e.Payload));
                    _logger.LogTrace($"Вызов обработчика для события от БД {GetDbLogName()} с PID = {e.PID} (channel = \"{e.Channel}\") завершен");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"Необработанное исключение при вызове обработка события от БД {GetDbLogName()} с PID = {e.PID} (channel = \"{e.Channel}\")");
                }
            }
            else
            {
                _logger.LogTrace($"Нет обработчиков для события из БД {GetDbLogName()} c PID = {e?.PID} (channel = \"{e?.Channel}\")");
            }
        }
        private async Task Consumer_Received(object sender, BasicDeliverEventArgs eventArgs)
        {
            var eventName = eventArgs.RoutingKey;
            var message   = Encoding.UTF8.GetString(eventArgs.Body);

            var integrationEventReceivedArgs = new IntegrationEventReceivedArgs()
            {
                EventName = eventName,
                Message   = message
            };

            try
            {
                await OnEventReceived?.Invoke(this, integrationEventReceivedArgs);
            }

            catch (Exception ex)
            {
                _logger.LogWarning(ex, "----- ERROR Processing message \"{Message}\"", message);
            }

            // Even on exception we take the message off the queue.
            // in a REAL WORLD app this should be handled with a Dead Letter Exchange (DLX).
            // For more information see: https://www.rabbitmq.com/dlx.html
            _consumerChannel.BasicAck(eventArgs.DeliveryTag, multiple: false);
        }
        public void NotifyEventReceived(IntegrationEvent integrationEvent)
        {
            Events.Add(integrationEvent);
            var eventArgs = new EventReceivedNotifierEventArgs()
            {
                Event = integrationEvent
            };

            OnEventReceived?.Invoke(this, eventArgs);
        }
Example #5
0
        protected void Event <TEventData>(Expression <Func <Event <TEventData> > > propertyExpression, string fieldName)
        {
            var machineEvent = propertyExpression.Compile().Invoke();

            _messagesToEventsMap[typeof(TEventData)] = machineEvent;
            _acceptedMessageMap.Add(new MessageBind(typeof(TEventData), fieldName));

            base.Event(propertyExpression);

            DuringAny(
                When(machineEvent).Then(
                    ctx =>
                    OnEventReceived.Invoke(this,
                                           new EventReceivedData <TEventData, TSagaData>(ctx.Event, ctx.Data, ctx.Instance))));
        }
Example #6
0
        private void ClientOnOnMessageReceived(RpcClient rpcClient1, RPCMessage rpcMessage)
        {
            switch (rpcMessage)
            {
            case RPCResponseMessage responseMessage:
                if (!_messageResponsesHandlers.TryRemove(responseMessage.RequestMessageId, out var value))
                {
                    return;
                }
                value.Message = responseMessage;
                value.Event.Set();
                break;

            case RPCEventMessage eventMessage:
                if (!_previousMessages.TryGetValue(eventMessage.MessageId, out _))
                {
                    _previousMessages.TryAdd(eventMessage.MessageId, null);
                    var edea = EventDataEventArgs.Retrieve(eventMessage.ServiceName, eventMessage.EventName, eventMessage.EventArgs);
                    OnEventReceived?.Invoke(this, edea);
                    EventDataEventArgs.Store(edea);
                }
                break;

            case RPCPushMessage pushMessage:
                if (!_previousMessages.TryGetValue(pushMessage.MessageId, out _))
                {
                    _previousMessages.TryAdd(pushMessage.MessageId, null);
                    var evArgs = ReferencePool <EventArgs <RPCPushMessage> > .Shared.New();

                    evArgs.Item1 = pushMessage;
                    OnPushMessageReceived?.Invoke(this, evArgs);
                    evArgs.Item1 = null;
                    ReferencePool <EventArgs <RPCPushMessage> > .Shared.Store(evArgs);
                }
                break;

            case RPCError errorMessage:
                var respMsg = RPCResponseMessage.Retrieve(errorMessage);
                foreach (var mHandler in _messageResponsesHandlers.ToArray())
                {
                    mHandler.Value.Message = respMsg;
                    mHandler.Value.Event.Set();
                    _messageResponsesHandlers.TryRemove(mHandler.Key, out _);
                }
                break;
            }
        }
Example #7
0
        public LANClient(ILogger <LANClient> logger)
        {
            var selfAddresses = NetworkInterface.GetAllNetworkInterfaces().SelectMany(ni => ni.GetIPProperties().UnicastAddresses.Select(ua => ua.Address.ToString()));

            _logger = logger;
            try
            {
                receiveUdpClient = new UdpClient(DefaultUdpPort)
                {
                    EnableBroadcast = true
                };
            }
            catch (Exception ex)
            {
                _logger.LogDebug(ex, "Exception");
                throw;
            }
            Task.Run(async() =>
            {
                try
                {
                    while (true)
                    {
                        var receivedResults = await receiveUdpClient.ReceiveAsync();
                        if (selfAddresses.Contains(receivedResults.RemoteEndPoint.Address.ToString()))
                        {
                            //ブロードキャストを自分で受信(無視)
                            continue;
                        }
                        _logger.LogDebug($"UDP受信:{receivedResults.RemoteEndPoint.Address.ToString()} {BytesConvert.ToHexString(receivedResults.Buffer)}");
                        OnEventReceived?.Invoke(this, (receivedResults.RemoteEndPoint.Address.ToString(), receivedResults.Buffer));
                    }
                }
                catch (System.ObjectDisposedException)
                {
                    //握りつぶす
                }
                catch (Exception ex)
                {
                    _logger.LogDebug(ex, "Exception");
                }
            });
        }
 private void RegisterSubscriptionClientMessageHandler()
 {
     _subscriptionClient.RegisterMessageHandler(
         async(message, token) =>
     {
         var eventName   = $"{message.Label}";
         var messageData = Encoding.UTF8.GetString(message.Body);
         var integrationEventReceivedArgs = new IntegrationEventReceivedArgs()
         {
             EventName = eventName,
             Message   = messageData
         };
         await Task.Run(async() => await(OnEventReceived?.Invoke(this, integrationEventReceivedArgs) ?? Task.CompletedTask));
         await _subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
     },
         new MessageHandlerOptions(ExceptionReceivedHandler)
     {
         MaxConcurrentCalls = 10, AutoComplete = false
     });
 }
Example #9
0
 public InMemoryEventSubscriber(BlockingCollection <IntegrationEvent> events)
 {
     _events = events;
     Task.Run(async() =>
     {
         foreach (var integrationEvent in _events.GetConsumingEnumerable())
         {
             string eventName = integrationEvent.GetType().Name;
             if (subscriptions.Contains(eventName))
             {
                 var eventArgs = new IntegrationEventReceivedArgs()
                 {
                     EventName = eventName,
                     Message   = JsonConvert.SerializeObject(integrationEvent)
                 };
                 if (OnEventReceived != null)
                 {
                     await OnEventReceived.Invoke(this, eventArgs);
                 }
             }
         }
     });
 }
Example #10
0
        private void Consume(object sender, BasicDeliverEventArgs @event)
        {
            _logger.LogInformation($"received message at {DateTime.UtcNow}, routing key: {@event.RoutingKey}");

            _deliveryTag = @event.DeliveryTag;

            var content = Encoding.UTF8.GetString(@event.Body);

            _logger.LogInformation($"raw content is {content}");

            var baseJsonContent = JsonConvert.DeserializeObject <Dictionary <string, object> >(content);

            var id = GetId(baseJsonContent);

            if (!id.HasValue)
            {
                throw new ArgumentNullException(nameof(id));
            }

            var received = new Received(id.Value, @event.RoutingKey, content, @event.BasicProperties.ReplyTo, @event.BasicProperties.CorrelationId);


            OnEventReceived?.Invoke(sender, received);
        }
Example #11
0
 private static void FireEvent(int pid, EventType eventType, int[] args)
 {
     OnEventReceived?.Invoke(pid, eventType, args);
 }
Example #12
0
 //
 private static void FireEvent(string pid, GameEvents gameevent, int[] args)
 {
     OnEventReceived?.Invoke(pid, gameevent, args);
 }
Example #13
0
 private void Connector_OnEventReceived(object sender, RPCEventArgs e)
 {
     OnEventReceived?.Invoke(this, e);
 }