Esempio n. 1
0
        /// <summary>
        /// Reads update messages from network stream and processes them in a loop until the connection terminates
        /// or until an action (such as a protocol violation) that leads to termination of the connection occurs.
        /// </summary>
        public async Task ReceiveMessageLoopAsync()
        {
            log.Info("()");

            try
            {
                while (!shutdownSignaling.IsShutdown)
                {
                    LocProtocolMessage message = await ReceiveMessageAsync(shutdownSignaling.ShutdownCancellationTokenSource.Token, true);

                    if (message == null)
                    {
                        break;
                    }
                    bool disconnect = !await messageProcessor.ProcessMessageAsync(this, message);

                    if (disconnect)
                    {
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }

            log.Info("(-)");
        }
Esempio n. 2
0
        private async Task ProcessRequestInternal(AspNetWebSocketContext context)
        {
            var socket = context.WebSocket;

            var userId = Guid.NewGuid();

            var tableIdInput = GetTableInput(context);

            var tableId = _tables.AddUserToTable(tableIdInput, userId, socket);

            var clientConnected = true;

            while (true)
            {
                if (socket.State == WebSocketState.Open)
                {
                    if (clientConnected)
                    {
                        await ProcessConnectedClientAsync(socket, tableId, userId);

                        clientConnected = false;
                    }
                    var message = await _messageExchanger.ReceiveMessageAsync(socket);

                    await _messageProcessor.ProcessMessageAsync(message, userId, tableId);
                }
                else
                {
                    await ProcessDisconnectedClientAsync(tableId, userId);

                    break;
                }
            }
        }
        /// <summary>
        /// Reads messages from the client stream and processes them in a loop until the client disconnects
        /// or until an action (such as a protocol violation) that leads to disconnecting of the client occurs.
        /// </summary>
        public async Task ReceiveMessageLoop()
        {
            log.Trace("()");

            try
            {
                if (UseTls)
                {
                    SslStream  sslStream = (SslStream)Stream;
                    ConfigBase config    = (ConfigBase)Base.ComponentDictionary[ConfigBase.ComponentName];
                    await sslStream.AuthenticateAsServerAsync((X509Certificate)config.Settings["TcpServerTlsCertificate"], false, SslProtocols.Tls12, false);
                }

                RawMessageReader messageReader = new RawMessageReader(Stream);
                while (!shutdownSignaling.IsShutdown)
                {
                    RawMessageResult rawMessage = await messageReader.ReceiveMessageAsync(shutdownSignaling.ShutdownCancellationTokenSource.Token);

                    bool disconnect        = rawMessage.Data == null;
                    bool protocolViolation = rawMessage.ProtocolViolation;
                    if (rawMessage.Data != null)
                    {
                        IProtocolMessage message = CreateMessageFromRawData(rawMessage.Data);
                        if (message != null)
                        {
                            disconnect = !await messageProcessor.ProcessMessageAsync(this, message);
                        }
                        else
                        {
                            protocolViolation = true;
                        }
                    }

                    if (protocolViolation)
                    {
                        await messageProcessor.SendProtocolViolation(this);

                        break;
                    }

                    if (disconnect)
                    {
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }

            log.Trace("(-)");
        }
Esempio n. 4
0
        public async Task ProcessMessageContextAsync_Failed_CannotHandle_Test()
        {
            //Arrange
            var message = CreateMessage();
            var context = new TestMessageContext(message, _messageReceiver, _messageSender);

            _failurePolicy.CanHandle(Arg.Any <Exception>()).Returns(false);
            _messageProcessor.ProcessMessageAsync(Arg.Any <Message>(), Arg.Any <CancellationToken>())
            .Throws(new Exception());

            //Act
            await _sut.ProcessMessageContextAsync(context, CancellationToken.None).ConfigureAwait(false);

            //Assert
            await _messageProcessor.Received().ProcessMessageAsync(Arg.Is(message), Arg.Is(CancellationToken.None))
            .ConfigureAwait(false);

            await _messageReceiver.DidNotReceiveWithAnyArgs().CompleteAsync(null).ConfigureAwait(false);

            await _messageReceiver.Received().AbandonAsync(Arg.Is(message.SystemProperties.LockToken)).ConfigureAwait(false);
        }
Esempio n. 5
0
 public async Task ProcessDataAsync(SentMessage thisData) //done.
 {
     if (IsEnabled == false)
     {
         lock (_synLock)
         {
             _messages.Enqueue(thisData);
         }
         return;
     }
     IsEnabled = false;
     await _thisMessage.ProcessMessageAsync(thisData);
 }
Esempio n. 6
0
        public async Task <IActionResult> Post([FromBody] Update update)
        {
            _logger.Debug("update received for chat {chatId}",
                          update?.Message?.Chat?.Id ?? update?.EditedMessage?.Chat?.Id ?? update?.CallbackQuery?.Message?.Chat?.Id);

            IMessageProcessor messageProcessor = await _messageProcessorFactory.GetMessageProcessorAsync(update);

            if (messageProcessor != null)
            {
                await messageProcessor.ProcessMessageAsync(update);
            }

            return(Ok());
        }
Esempio n. 7
0
        private async Task HandleMessage(Message message, CancellationToken ct)
        {
            var sw        = Stopwatch.StartNew();
            var timestamp = DateTimeOffset.UtcNow;

            var processingResult = await _processor.ProcessMessageAsync(message, _endpointHandlingConfig, ct).ConfigureAwait(false);

            var isSuccessful = await HandleMessageOutcome(message, processingResult).ConfigureAwait(false);

            _instrumentor.TrackRequest(
                LogEventIds.ListenerHandlerFinished,
                sw.ElapsedMilliseconds,
                timestamp,
                _name,
                isSuccessful: isSuccessful,
                customProperties: processingResult.AdditionalProperties);
        }
Esempio n. 8
0
        private EventingBasicConsumer InitConsumer()
        {
            _Logger.LogInformation("InitConsumer started");

            if (Channel.IsOpen)
            {
                Channel.Close();
            }

            EnsureChanel();
            var consumer = new EventingBasicConsumer(Channel);

            consumer.Received += (chanel, ea) =>
            {
                Task.Run(async() => await _MessageProcessor.ProcessMessageAsync(ea));
            };

            _Logger.LogInformation("Consumer initiated");
            return(consumer);
        }
        /// <summary>
        /// This is the main entry point for your service instance.
        /// </summary>
        /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service instance.</param>
        //protected override async Task RunAsync(CancellationToken cancellationToken)
        //{
        //    // TODO: Replace the following sample code with your own logic
        //    //       or remove this RunAsync override if it's not needed in your service.

        //    long iterations = 0;

        //    while (true)
        //    {
        //        cancellationToken.ThrowIfCancellationRequested();

        //        ServiceEventSource.Current.ServiceMessage(this.Context, "Working-{0}", ++iterations);

        //        await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
        //    }
        //}



        private async Task ProcessMessageAsync(Message message, CancellationToken token)
        {
            ServiceEventSource.Current.ServiceMessage(this.Context, "MESSAGE RECIEVED!!!", message);
            var model = JsonSerializer.Deserialize <MessageModel>(message.Body);

            IMessageProcessor actor = ActorProxy.Create <IMessageProcessor>(ActorId.CreateRandom(), new Uri("fabric:/ServiceFabricTestApp/MessageProcessorActorService"));
            var result = await actor.ProcessMessageAsync(model);


            if (result)
            {
                ServiceEventSource.Current.ServiceMessage(this.Context, $"Message {model.Title} has been processed successfully", message);
                await _serviceBusService.CompleteAsync(message);
            }
            else
            {
                ServiceEventSource.Current.ServiceMessage(this.Context, $"An error ocurred while processing the message with Id: {message.MessageId} and will be deadlettered", message);
                await _serviceBusService.DeadLetterAsync(message, "result was false");
            }
        }
Esempio n. 10
0
        public async Task ProcessMessageContextAsync(MessageContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                await CheckForDeferredMessageAsync(context).ConfigureAwait(false);

                await _messageProcessor.ProcessMessageAsync(context.Message, cancellationToken).ConfigureAwait(false);

                await context.MessageReceiver.CompleteAsync(context.Message.SystemProperties.LockToken)
                .ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                if (await TryCompleteOnExceptionAsync(context, exception) || await TryAbandonOnExceptionAsync(context, exception))
                {
                    return;
                }

                await _failurePolicy.HandleFailureAsync(context, cancellationToken).ConfigureAwait(false);
            }
        }
Esempio n. 11
0
        public async Task ProcessDataAsync(SentMessage thisData) //done.
        {
            if (IsEnabled == false)                              //no more bypass.
            {
                lock (_synLock)
                    _messages.Enqueue(thisData);
                return;
            }
            IsEnabled = false;
            if (thisData.Status == "Connection Error")
            {
                await _thisMessage.ProcessErrorAsync(thisData.Body);

                return;
            }
            if (thisData.Status == "hosting")
            {
                var open = _resolver.Resolve <IOpeningMessenger>();
                await open.HostConnectedAsync(this);

                return;
            }
            if (thisData.Status == "clienthost")
            {
                var open = _resolver.Resolve <IOpeningMessenger>();
                if (thisData.Body != "")
                {
                    await open.ConnectedToHostAsync(this, thisData.Body);

                    return;
                }
                await open.HostNotFoundAsync(this);

                return;
            }
            await _thisMessage.ProcessMessageAsync(thisData);
        }
        public Task Publish <T>(T message)
        {
            var randomMessage = _messageProcessor.ProcessMessageAsync(message.ToString()).Result;

            return(Task.Factory.StartNew(() => SendMessage(randomMessage)));
        }
        private async Task <int> ProcessBufferAsync(
            byte[] buffer,
            int filledCount,
            bool isBlobCompressed,
            CloudAppendBlob blob)
        {
            var delimiterEndIndexes = new List <int> {
                -1
            };

            while (true)
            {
                int newDelimiterEndIndex = await GetNextDelimiterEndIndexAsync(
                    buffer,
                    filledCount,
                    delimiterEndIndexes.Last(),
                    blob);

                if (newDelimiterEndIndex == -1)
                {
                    break;
                }

                bool foundCorrectChunk = false;
                for (int j = 0; j < delimiterEndIndexes.Count; ++j)
                {
                    int delimiterEndIndex = delimiterEndIndexes[j];
                    int chunkSize         = newDelimiterEndIndex - delimiterEndIndex - _delimiterBytes.Length;
                    if (chunkSize == 0)
                    {
                        continue;
                    }

                    int chunkStart = delimiterEndIndex + 1;
                    if (_isNewFormat.HasValue && _isNewFormat.Value)
                    {
                        chunkSize  -= 8;
                        chunkStart += 4;
                    }
                    var chunk = new byte[chunkSize];
                    Array.Copy(buffer, chunkStart, chunk, 0, chunkSize);
                    if (isBlobCompressed)
                    {
                        chunk = UnpackMessage(chunk);
                        if (chunk == null)
                        {
                            continue;
                        }
                    }

                    foundCorrectChunk = TryDeserialize(chunk, out var obj);
                    if (foundCorrectChunk)
                    {
                        int skippedBytesCount = delimiterEndIndex - delimiterEndIndexes[0];
                        if (j > 1 || j == 1 && skippedBytesCount > _maxAllowedSkippedBytesCount)
                        {
                            if (_skipCorrupted)
                            {
                                _log.WriteWarning(nameof(ProcessBufferAsync), null, $"Skipped {skippedBytesCount} bytes with {j} delimiters.");
                            }
                            else
                            {
                                throw new InvalidOperationException(
                                          $"Couldn't process message(s). Found corrupted chunk - {skippedBytesCount} bytes with {j} delimiters.");
                            }
                        }
                        await _messageProcessor.ProcessMessageAsync(obj);

                        break;
                    }
                }

                if (foundCorrectChunk)
                {
                    delimiterEndIndexes.Clear();
                }
                delimiterEndIndexes.Add(newDelimiterEndIndex);
                if (delimiterEndIndexes.Count >= _maxUnprocessedPatternsCount)
                {
                    throw new InvalidOperationException($"Couldn't properly process blob - {delimiterEndIndexes.Count} unprocessed patterns.");
                }
            }

            return(delimiterEndIndexes[0]);
        }