Ejemplo n.º 1
0
        public override BizContext preHandleRequest(RemotingContext remotingCtx, object request)
        {
            BizContext ctx = new MyBizContext(this, remotingCtx);

            ctx.put("test", "test");
            return(ctx);
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Handle the request(s).
 /// </summary>
 /// <param name="ctx"></param>
 /// <param name="msg"></param>
 private void handle(RemotingContext ctx, object msg)
 {
     try
     {
         if (msg is IList)
         {
             //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
             //ORIGINAL LINE: final Runnable handleTask = new Runnable()
             Runnable handleTask = new TempRunnable(this, ctx, msg);
             if (RpcConfigManager.dispatch_msg_list_in_default_executor())
             {
                 // If msg is list ,then the batch submission to biz threadpool can save io thread.
                 // See decoder.ProtocolDecoder
                 processorManager.DefaultExecutor.execute(handleTask);
             }
             else
             {
                 handleTask.run();
             }
         }
         else
         {
             process(ctx, msg);
         }
     }
     catch (System.Exception t)
     {
         processException(ctx, msg, t);
     }
 }
        public async Task Invoke(HttpContext context, StatelessServiceContext serviceContext)
        {
            using (_logger.BeginScope(new Dictionary <string, object>
            {
                [SharedProperties.TraceId] = context.Request.HttpContext.TraceIdentifier
            }))
            {
                RemotingContext.SetData(HeaderIdentifiers.TraceId, context.Request.HttpContext.TraceIdentifier);

                AddTracingDetailsOnRequest(context, serviceContext);

                var stopwatch = Stopwatch.StartNew();
                var started   = DateTime.Now;
                var success   = false;

                try
                {
                    await _next(context);

                    success = true;
                }
                catch (Exception exception)
                {
                    _logger.LogCritical((int)ServiceFabricEvent.Exception, exception, exception.Message);
                    throw;
                }
                finally
                {
                    stopwatch.Stop();
                    _logger.LogRequest(context, started, stopwatch.Elapsed, success);
                }
            }
        }
 /// <summary>
 /// pre process remoting context, initial some useful infos and pass to biz
 /// </summary>
 /// <param name="ctx"> remoting context </param>
 /// <param name="cmd"> rpc request command </param>
 /// <param name="currentTimestamp"> current timestamp </param>
 private void preProcessRemotingContext(RemotingContext ctx, RpcRequestCommand cmd, long currentTimestamp)
 {
     ctx.ArriveTimestamp = cmd.ArriveTime;
     ctx.Timeout         = cmd.Timeout;
     ctx.RpcCommandType  = cmd.Type;
     ctx.InvokeContext.putIfAbsent(InvokeContext.BOLT_PROCESS_WAIT_TIME, currentTimestamp - cmd.ArriveTime);
 }
Ejemplo n.º 5
0
        /// <seealso cref= AbstractRemotingProcessor#doProcess </seealso>
        public override void doProcess(RemotingContext ctx, RemotingCommand cmd)
        {
            Connection   conn   = ctx.ChannelContext.Channel.GetAttribute(Connection.CONNECTION).Get();
            InvokeFuture future = conn.removeInvokeFuture(cmd.Id);

            try
            {
                if (future != null)
                {
                    future.putResponse(cmd);
                    future.cancelTimeout();
                    try
                    {
                        future.executeInvokeCallback();
                    }
                    catch (System.Exception e)
                    {
                        logger.LogError("Exception caught when executing invoke callback, id={}", cmd.Id, e);
                    }
                }
                else
                {
                    logger.LogWarning("Cannot find InvokeFuture, maybe already timeout, id={}, from={} ", cmd.Id, ctx.ChannelContext.Channel.RemoteAddress.ToString());
                }
            }
            finally
            {
            }
        }
 /// <summary>
 /// print some debug log when receive request
 /// </summary>
 private void debugLog(RemotingContext ctx, RpcRequestCommand cmd, long currentTimestamp)
 {
     if (logger.IsEnabled(LogLevel.Debug))
     {
         logger.LogDebug("Rpc request received! requestId={}, from {}", cmd.Id, ctx.ChannelContext.Channel.RemoteAddress.ToString());
         logger.LogDebug("request id {} currenTimestamp {} - arriveTime {} = server cost {} < timeout {}.", cmd.Id, currentTimestamp, cmd.ArriveTime, currentTimestamp - cmd.ArriveTime, cmd.Timeout);
     }
 }
Ejemplo n.º 7
0
        Task <int> IMyActor.GetCountAsync(CancellationToken cancellationToken)
        {
            var traceId = RemotingContext.GetData(HeaderIdentifiers.TraceId);

            _logger.LogInformation($"Hello from inside {nameof(MyActor)} (traceId {traceId})");

            return(StateManager.GetStateAsync <int>("count", cancellationToken));
        }
 //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
 //ORIGINAL LINE: @Override public void doProcess(final RemotingContext ctx, RemotingCommand msg)
 public override void doProcess(RemotingContext ctx, RemotingCommand msg)
 {
     if (msg is HeartbeatCommand)
     { // process the heartbeat
       //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
       //ORIGINAL LINE: final int id = msg.getId();
         int id = msg.Id;
         if (logger.IsEnabled(LogLevel.Debug))
         {
             logger.LogDebug("Heartbeat received! Id=" + id + ", from " + ctx.ChannelContext.Channel.RemoteAddress.ToString());
         }
         HeartbeatAckCommand ack = new HeartbeatAckCommand();
         ack.Id = id;
         var writeFlushTask = ctx.writeAndFlush(ack);
         writeFlushTask.ContinueWith((task) =>
         {
             if (task.IsCompletedSuccessfully)
             {
                 if (logger.IsEnabled(LogLevel.Debug))
                 {
                     logger.LogDebug("Send heartbeat ack done! Id={}, to remoteAddr={}", id, ctx.ChannelContext.Channel.RemoteAddress.ToString());
                 }
             }
             else
             {
                 logger.LogError("Send heartbeat ack failed! Id={}, to remoteAddr={}", id, ctx.ChannelContext.Channel.RemoteAddress.ToString());
             }
         });
         //.addListener(new ChannelFutureListenerAnonymousInnerClass(this, ctx, id));
     }
     else if (msg is HeartbeatAckCommand)
     {
         Connection   conn   = (Connection)ctx.ChannelContext.Channel.GetAttribute(Connection.CONNECTION).Get();
         InvokeFuture future = conn.removeInvokeFuture(msg.Id);
         if (future != null)
         {
             future.putResponse(msg);
             future.cancelTimeout();
             try
             {
                 future.executeInvokeCallback();
             }
             catch (Exception e)
             {
                 logger.LogError("Exception caught when executing heartbeat invoke callback. From {}", ctx.ChannelContext.Channel.RemoteAddress.ToString(), e);
             }
         }
         else
         {
             logger.LogWarning("Cannot find heartbeat InvokeFuture, maybe already timeout. Id={}, From {}", msg.Id, ctx.ChannelContext.Channel.RemoteAddress.ToString());
         }
     }
     else
     {
         //JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
         throw new Exception("Cannot process command: " + msg.GetType().FullName);
     }
 }
        /// <summary>
        /// Send response using remoting context if necessary.<br>
        /// If request type is oneway, no need to send any response nor exception.
        /// </summary>
        /// <param name="ctx"> remoting context </param>
        /// <param name="type"> type code </param>
        /// <param name="response"> remoting command </param>
        //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
        //ORIGINAL LINE: public void sendResponseIfNecessary(final RemotingContext ctx, byte type, final RemotingCommand response)
        public virtual void sendResponseIfNecessary(RemotingContext ctx, byte type, RemotingCommand response)
        {
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final int id = response.getId();
            int id = response.Id;

            if (type != RpcCommandType.REQUEST_ONEWAY)
            {
                RemotingCommand serializedResponse = response;
                try
                {
                    response.serialize();
                }
                catch (SerializationException e)
                {
                    string errMsg = "SerializationException occurred when sendResponseIfNecessary in RpcRequestProcessor, id=" + id;
                    logger.LogError(errMsg, e);
                    serializedResponse = CommandFactory.createExceptionResponse(id, ResponseStatus.SERVER_SERIAL_EXCEPTION, e);
                    try
                    {
                        serializedResponse.serialize(); // serialize again for exception response
                    }
                    catch (SerializationException)
                    {
                        // should not happen
                        logger.LogError("serialize SerializationException response failed!");
                    }
                }
                catch (System.Exception t)
                {
                    string errMsg = "Serialize RpcResponseCommand failed when sendResponseIfNecessary in RpcRequestProcessor, id=" + id;
                    logger.LogError(errMsg, t);
                    serializedResponse = CommandFactory.createExceptionResponse(id, t, errMsg);
                }

                var writeFlushTask = ctx.writeAndFlush(serializedResponse);
                writeFlushTask.ContinueWith((task) =>
                {
                    if (logger.IsEnabled(LogLevel.Debug))
                    {
                        logger.LogDebug("Rpc response sent! requestId=" + id + ". The address is " + ctx.ChannelContext.Channel.RemoteAddress.ToString());
                    }
                    if (!task.IsCompletedSuccessfully)
                    {
                        logger.LogError("Rpc response send failed! id=" + id + ". The address is " + ctx.ChannelContext.Channel.RemoteAddress.ToString(), task.Exception);
                    }
                });
                //.addListener(new ChannelFutureListenerAnonymousInnerClass(this, ctx, id));
            }
            else
            {
                if (logger.IsEnabled(LogLevel.Debug))
                {
                    logger.LogDebug("Oneway rpc request received, do not send response, id=" + id + ", the address is " + ctx.ChannelContext.Channel.RemoteAddress.ToString());
                }
            }
        }
        Task <string> IDemoActor.GetGreetingResponseAsync(CancellationToken cancellationToken)
        {
            // Read the data from the custom header
            var remotingContext =
                string.Join(", ", RemotingContext.Keys.Select(k => $"{k}: {RemotingContext.GetData(k)}"));

            ActorEventSource.Current.ActorMessage(this, $"GetGreetingResponseAsync got context: {remotingContext}");

            return(Task.FromResult($"Hello From Actor (with context '{remotingContext}')"));
        }
        public async Task <int> CalculateSumAsync(int a, int b)
        {
            var traceId = RemotingContext.GetData(HeaderIdentifiers.TraceId);

            _logger.LogTrace($"Hello from inside {nameof(MyStateless)} (traceId {traceId})");

            await new HttpClient().GetAsync("http://www.nu.nl");

            return(a + b);
        }
Ejemplo n.º 12
0
        public Startup(IWebHostEnvironment env)
        {
            Environment = env;
            var dom = new ConfigurationBuilder()
                      .SetBasePath(env.ContentRootPath)
                      .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                      .AddEnvironmentVariables()
                      .Build();

            Configuration = dom;
            RemotingContext.Set(Environment, Configuration);
            ASP_DBEntities.ConnectionString = Configuration["ASP_DBEntities"];  // globally
        }
        /// <summary>
        /// dispatch request command to user processor
        /// </summary>
        /// <param name="ctx"> remoting context </param>
        /// <param name="cmd"> rpc request command </param>
        private void dispatchToUserProcessor(RemotingContext ctx, RpcRequestCommand cmd)
        {
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final int id = cmd.getId();
            int id = cmd.Id;
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final byte type = cmd.getType();
            byte type = cmd.Type;
            // processor here must not be null, for it have been checked before
            UserProcessor processor = ctx.getUserProcessor(cmd.RequestClass);

            if (processor is AsyncUserProcessor)
            {
                try
                {
                    processor.handleRequest(processor.preHandleRequest(ctx, cmd.RequestObject), new RpcAsyncContext(ctx, cmd, this), cmd.RequestObject);
                }
                catch (RejectedExecutionException)
                {
                    logger.LogWarning("RejectedExecutionException occurred when do ASYNC process in RpcRequestProcessor");
                    sendResponseIfNecessary(ctx, type, CommandFactory.createExceptionResponse(id, ResponseStatus.SERVER_THREADPOOL_BUSY));
                }
                catch (System.Exception t)
                {
                    string errMsg = "AYSNC process rpc request failed in RpcRequestProcessor, id=" + id;
                    logger.LogError(errMsg, t);
                    sendResponseIfNecessary(ctx, type, CommandFactory.createExceptionResponse(id, t, errMsg));
                }
            }
            else
            {
                try
                {
                    object responseObject = processor.handleRequest(processor.preHandleRequest(ctx, cmd.RequestObject), cmd.RequestObject);

                    sendResponseIfNecessary(ctx, type, CommandFactory.createResponse(responseObject, cmd));
                }
                catch (RejectedExecutionException)
                {
                    logger.LogWarning("RejectedExecutionException occurred when do SYNC process in RpcRequestProcessor");
                    sendResponseIfNecessary(ctx, type, CommandFactory.createExceptionResponse(id, ResponseStatus.SERVER_THREADPOOL_BUSY));
                }
                catch (System.Exception t)
                {
                    string errMsg = "SYNC process rpc request failed in RpcRequestProcessor, id=" + id;
                    logger.LogError(errMsg, t);
                    sendResponseIfNecessary(ctx, type, CommandFactory.createExceptionResponse(id, t, errMsg));
                }
            }
        }
        public async Task <string> SayHelloToActor()
        {
            // Read the data from the custom header
            var remotingContext =
                string.Join(", ", RemotingContext.Keys.Select(k => $"{k}: {RemotingContext.GetData(k)}"));

            ServiceEventSource.Current.ServiceMessage(Context, $"SayHelloToActor got context: {remotingContext}");

            // Call the actor using the same headers as received by this method
            var proxy    = ExtendedActorProxy.Create <IDemoActor>(new ActorId(1), CustomHeaders.FromRemotingContext);
            var response = await proxy.GetGreetingResponseAsync(CancellationToken.None);

            return($"DemoService passed context '{remotingContext}' to actor and got as response: {response}");
        }
Ejemplo n.º 15
0
 private void processException(RemotingContext ctx, object msg, System.Exception t)
 {
     if (msg is IList)
     {
         //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
         //ORIGINAL LINE: for (final Object m : (java.util.List<object><?>) msg)
         foreach (var m in (IList <object>)msg)
         {
             processExceptionForSingleCommand(ctx, m, t);
         }
     }
     else
     {
         processExceptionForSingleCommand(ctx, msg, t);
     }
 }
        /// <inheritdoc/>
        public override async Task <IServiceRemotingResponseMessage> HandleRequestResponseAsync(IServiceRemotingRequestContext requestContext,
                                                                                                IServiceRemotingRequestMessage requestMessage)
        {
            var handleExtended = false;
            Uri serviceUri     = null;

            object    state     = null;
            Exception exception = null;

            var header = requestMessage.GetHeader() as IActorRemotingMessageHeaders;

            //check to see if message headers are assignable
            if (header != null)
            {
                handleExtended = true;
                serviceUri     = (Uri)header.GetCustomHeaders()[CustomHeaders.ReservedHeaderServiceUri];
                RemotingContext.FromRemotingMessageHeader(header);
            }

            if (BeforeHandleRequestResponseAsync != null && handleExtended)
            {
                state = await BeforeHandleRequestResponseAsync.Invoke(new ActorRequestInfo(requestMessage, header.ActorId, header.MethodName, serviceUri));
            }

            IServiceRemotingResponseMessage responseMessage = null;

            try
            {
                responseMessage = await base.HandleRequestResponseAsync(requestContext, requestMessage);
            }
            catch (Exception ex)
            {
                exception = ex;
                throw;
            }
            finally
            {
                if (AfterHandleRequestResponseAsync != null && handleExtended)
                {
                    await AfterHandleRequestResponseAsync.Invoke(new ActorResponseInfo(responseMessage, header.ActorId, header.MethodName, serviceUri, state, exception));
                }
            }

            return(responseMessage);
        }
        /// <seealso cref= AbstractRemotingProcessor#doProcess(RemotingContext, RemotingCommand) </seealso>
        //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
        //ORIGINAL LINE: @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void doProcess(final RemotingContext ctx, RpcRequestCommand cmd) throws Exception
        //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
        public virtual void doProcess(RemotingContext ctx, RpcRequestCommand cmd)
        {
            long currentTimestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();

            preProcessRemotingContext(ctx, cmd, currentTimestamp);
            if (ctx.TimeoutDiscard && ctx.RequestTimeout)
            {
                timeoutLog(cmd, currentTimestamp, ctx); // do some log
                return;                                 // then, discard this request
            }
            debugLog(ctx, cmd, currentTimestamp);
            // decode request all
            if (!deserializeRequestCommand(ctx, cmd, RpcDeserializeLevel.DESERIALIZE_ALL))
            {
                return;
            }
            dispatchToUserProcessor(ctx, cmd);
        }
Ejemplo n.º 18
0
 //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
 //ORIGINAL LINE: @SuppressWarnings({ "rawtypes", "unchecked" }) private void process(RemotingContext ctx, Object msg)
 private void process(RemotingContext ctx, object msg)
 {
     try
     {
         //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
         //ORIGINAL LINE: final rpc.RpcCommand cmd = (rpc.RpcCommand) msg;
         RpcCommand cmd = (RpcCommand)msg;
         //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
         //ORIGINAL LINE: final RemotingProcessor processor = processorManager.getProcessor(cmd.getCmdCode());
         var processor = processorManager.getProcessor(cmd.CmdCode);
         processor.process(ctx, cmd, processorManager.DefaultExecutor);
     }
     //JAVA TO C# CONVERTER WARNING: 'final' catch parameters are not available in C#:
     //ORIGINAL LINE: catch (final Throwable t)
     catch (System.Exception t)
     {
         processException(ctx, msg, t);
     }
 }
        /// <summary>
        /// print some log when request timeout and discarded in io thread.
        /// </summary>
        //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
        //ORIGINAL LINE: private void timeoutLog(final RpcRequestCommand cmd, long currentTimestamp, RemotingContext ctx)
        private void timeoutLog(RpcRequestCommand cmd, long currentTimestamp, RemotingContext ctx)
        {
            if (logger.IsEnabled(LogLevel.Debug))
            {
                logger.LogDebug("request id [{}] currenTimestamp [{}] - arriveTime [{}] = server cost [{}] >= timeout value [{}].", cmd.Id, currentTimestamp, cmd.ArriveTime, currentTimestamp - cmd.ArriveTime, cmd.Timeout);
            }

            string remoteAddr = "UNKNOWN";

            if (null != ctx)
            {
                IChannelHandlerContext channelCtx = ctx.ChannelContext;
                IChannel channel = channelCtx.Channel;
                if (null != channel)
                {
                    remoteAddr = ((IPEndPoint)channel.RemoteAddress).ToString();
                }
            }
            logger.LogWarning("Rpc request id[{}], from remoteAddr[{}] stop process, total wait time in queue is [{}], client timeout setting is [{}].", cmd.Id, remoteAddr, currentTimestamp - cmd.ArriveTime, cmd.Timeout);
        }
Ejemplo n.º 20
0
        /*
         * Return error command if necessary.
         */
        private void processExceptionForSingleCommand(RemotingContext ctx, object msg, System.Exception t)
        {
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final int id = ((rpc.RpcCommand) msg).getId();
            int id = ((RpcCommand)msg).Id;
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final String emsg = "Exception caught when processing " + ((msg instanceof rpc.RequestCommand) ? "request, id=" : "response, id=");
            string emsg = "Exception caught when processing " + ((msg is RequestCommand) ? "request, id=" : "response, id=");

            logger.LogWarning(emsg + id, t);
            if (msg is RequestCommand)
            {
                //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
                //ORIGINAL LINE: final rpc.RequestCommand cmd = (rpc.RequestCommand) msg;
                RequestCommand cmd = (RequestCommand)msg;
                if (cmd.Type != RpcCommandType.REQUEST_ONEWAY)
                {
                    if (t is RejectedExecutionException)
                    {
                        ResponseCommand response = (ResponseCommand)commandFactory.createExceptionResponse(id, ResponseStatus.SERVER_THREADPOOL_BUSY);
                        var             task     = ctx.ChannelContext.WriteAndFlushAsync(response);
                        task.ContinueWith((writeFlushTask) =>
                        {
                            if (writeFlushTask.IsCompletedSuccessfully)
                            {
                                if (logger.IsEnabled(LogLevel.Information))
                                {
                                    logger.LogInformation("Write back exception response done, requestId={}, status={}", id, response.ResponseStatus);
                                }
                            }
                            else
                            {
                                logger.LogError("Write back exception response failed, requestId={}", id, writeFlushTask.Exception);
                            }
                        });
                    }
                }
            }
        }
        /// <inheritdoc/>
        public override async Task <IServiceRemotingResponseMessage> HandleRequestResponseAsync(IServiceRemotingRequestContext requestContext,
                                                                                                IServiceRemotingRequestMessage requestMessage)
        {
            var header = requestMessage.GetHeader();

            var serviceUri = (Uri)header.GetCustomHeaders()[CustomHeaders.ReservedHeaderServiceUri];

            RemotingContext.FromRemotingMessageHeader(header);

            object    state     = null;
            Exception exception = null;

            if (BeforeHandleRequestResponseAsync != null)
            {
                state = await BeforeHandleRequestResponseAsync.Invoke(new ServiceRequestInfo(requestMessage, header.MethodName, serviceUri));
            }

            IServiceRemotingResponseMessage responseMessage = null;

            try
            {
                responseMessage = await base.HandleRequestResponseAsync(requestContext, requestMessage);
            }
            catch (Exception ex)
            {
                exception = ex;
                throw;
            }
            finally
            {
                if (AfterHandleRequestResponseAsync != null)
                {
                    await AfterHandleRequestResponseAsync.Invoke(new ServiceResponseInfo(responseMessage, header.MethodName, serviceUri, state, exception));
                }
            }

            return(responseMessage);
        }
        /// <summary>
        /// deserialize request command
        /// </summary>
        /// <returns> true if deserialize success; false if exception catched </returns>
        private bool deserializeRequestCommand(RemotingContext ctx, RpcRequestCommand cmd, int level)
        {
            bool result;

            try
            {
                cmd.deserialize(level);
                result = true;
            }
            catch (DeserializationException e)
            {
                logger.LogError("DeserializationException occurred when process in RpcRequestProcessor, id={}, deserializeLevel={}", cmd.Id, RpcDeserializeLevel.valueOf(level), e);
                sendResponseIfNecessary(ctx, cmd.Type, CommandFactory.createExceptionResponse(cmd.Id, ResponseStatus.SERVER_DESERIAL_EXCEPTION, e));
                result = false;
            }
            catch (System.Exception t)
            {
                string errMsg = "Deserialize RpcRequestCommand failed in RpcRequestProcessor, id=" + cmd.Id + ", deserializeLevel=" + level;
                logger.LogError(errMsg, t);
                sendResponseIfNecessary(ctx, cmd.Type, CommandFactory.createExceptionResponse(cmd.Id, t, errMsg));
                result = false;
            }
            return(result);
        }
 public ProcessTask(RpcRequestProcessor outerInstance, RemotingContext ctx, RpcRequestCommand msg)
 {
     this.outerInstance = outerInstance;
     this.ctx           = ctx;
     this.msg           = msg;
 }
 /// <inheritdoc/>
 public override void HandleOneWayMessage(IServiceRemotingRequestMessage requestMessage)
 {
     RemotingContext.FromRemotingMessageHeader(requestMessage.GetHeader());
     base.HandleOneWayMessage(requestMessage);
 }
Ejemplo n.º 25
0
 /// <seealso cref= CommandHandler#handleCommand(RemotingContext, Object) </seealso>
 //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
 //ORIGINAL LINE: @Override public void handleCommand(RemotingContext ctx, Object msg) throws Exception
 public virtual void handleCommand(RemotingContext ctx, object msg)
 {
     handle(ctx, msg);
 }
Ejemplo n.º 26
0
 //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
 //ORIGINAL LINE: @Override public void doProcess(RemotingContext ctx, RemotingCommand msg) throws Exception
 public override void doProcess(RemotingContext ctx, RemotingCommand msg)
 {
     logger.LogError("No processor available for command code {}, msgId {}", msg.CmdCode, msg.Id);
 }
Ejemplo n.º 27
0
 public TempRunnable(RpcCommandHandler rpcCommandHandler, RemotingContext remotingContext, object msg)
 {
     this.rpcCommandHandler = rpcCommandHandler;
     this.remotingContext   = remotingContext;
     this.msg = msg;
 }
Ejemplo n.º 28
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="remotingCtx"> </param>
 public MyBizContext(PreHandleUserProcessor outerInstance, RemotingContext remotingCtx) : base(remotingCtx)
 {
     this.outerInstance = outerInstance;
 }
Ejemplo n.º 29
0
        public ILoggerFactory CreateLoggerFactory(string aiKey)
        {
            var configuration = new TelemetryConfiguration
            {
                InstrumentationKey = aiKey
            };

            configuration.TelemetryInitializers.Add(new OperationContextTelemetryInitializer(() =>
                                                                                             RemotingContext.GetData(HeaderIdentifiers.TraceId)?.ToString()));

            new LiveStreamProvider(configuration).Enable();

            var loggerFactory = new LoggerFactory();
            var logger        = new LoggerConfiguration()
                                .Enrich.FromLogContext()
                                .WriteTo
                                .ApplicationInsights(
                configuration,
                (logEvent, formatter) => new TelemetryBuilder(_context, logEvent).LogEventToTelemetryConverter())
                                .CreateLogger();

            InitContextProperties();

            loggerFactory.AddSerilog(logger, true);

            return(loggerFactory);
        }
        /// <seealso cref= AbstractRemotingProcessor#process(RemotingContext, RemotingCommand, java.util.concurrent.ExecutorService) </seealso>
        public override void process(RemotingContext ctx, RemotingCommand cmd, ExecutorService defaultExecutor)
        {
            var rpcRequestCommand = (RpcRequestCommand)cmd;

            if (!deserializeRequestCommand(ctx, rpcRequestCommand, RpcDeserializeLevel.DESERIALIZE_CLAZZ))
            {
                return;
            }
            UserProcessor userProcessor = ctx.getUserProcessor(rpcRequestCommand.RequestClass);

            if (userProcessor == null)
            {
                string errMsg = "No user processor found for request: " + rpcRequestCommand.RequestClass;
                logger.LogError(errMsg);
                sendResponseIfNecessary(ctx, rpcRequestCommand.Type, CommandFactory.createExceptionResponse(cmd.Id, errMsg));
                return; // must end process
            }

            // set timeout check state from user's processor
            ctx.setTimeoutDiscard(userProcessor.timeoutDiscard());

            // to check whether to process in io thread
            if (userProcessor.processInIOThread())
            {
                if (!deserializeRequestCommand(ctx, rpcRequestCommand, RpcDeserializeLevel.DESERIALIZE_ALL))
                {
                    return;
                }
                // process in io thread
                new ProcessTask(this, ctx, rpcRequestCommand).run();
                return; // end
            }

            Executor executor;

            // to check whether get executor using executor selector
            if (null == userProcessor.ExecutorSelector)
            {
                executor = userProcessor.Executor;
            }
            else
            {
                // in case haven't deserialized in io thread
                // it need to deserialize clazz and header before using executor dispath strategy
                if (!deserializeRequestCommand(ctx, rpcRequestCommand, RpcDeserializeLevel.DESERIALIZE_HEADER))
                {
                    return;
                }
                //try get executor with strategy
                executor = userProcessor.ExecutorSelector.select(rpcRequestCommand.RequestClass, rpcRequestCommand.RequestHeader);
            }

            // Till now, if executor still null, then try default
            if (executor == null)
            {
                executor = Executor ?? defaultExecutor;
            }

            // use the final executor dispatch process task
            executor.execute(new ProcessTask(this, ctx, rpcRequestCommand));
        }