예제 #1
0
		public async Task ProcessAsync(ServiceContext context, Func<ServiceContext, Task> next)
		{
			var stopwatch = Stopwatch.StartNew();
			await next(context);
			stopwatch.Stop();
			//Console.WriteLine($"Service: {context.Service.Name}, Action: {context.Action.Name}, Execute Duration: {stopwatch.ElapsedMilliseconds}ms");
		}
예제 #2
0
        /// <summary>
        /// <para>determinate if the request path is Service path</para>
        /// <para>get and set Service to serviceContext</para>
        /// <para>compute and set ActionName to serviceContext.Request</para>
        /// </summary>
        /// <param name="serviceContext"></param>
        /// <returns></returns>
        public MapServiceResult MapService(ServiceContext serviceContext)
        {
            //var isServicePath = _config.Service?.Paths == null
            //	|| _config.Service.Paths
            //		.Any(it => serviceContext.Request.Path.StartsWith(it, StringComparison.OrdinalIgnoreCase));

            //if (!isServicePath)
            //	return MapServiceResult.Empty;

            var requestPath = serviceContext.Request.Path;
            if (string.IsNullOrWhiteSpace(requestPath))
                throw new ArgumentException("request.AppRelativeCurrentExecutionFilePath is null or white space");

            var service = _factory.Services.FirstOrDefault(it =>
                requestPath.StartsWith(it.Path, StringComparison.OrdinalIgnoreCase));
            if (service == null)
            {
                LogHelper.Debug("BeginProcessReques Can't find service " + requestPath);
                throw new ServiceNotFoundException(requestPath);
            }
            var actionName = requestPath.Substring(service.Path.Length);

            serviceContext.Request.ActionName = actionName;
            serviceContext.Service = service;

            return new MapServiceResult
            {
                IsServiceRequest = true,
                //ServiceContext = serviceContext,
            };
        }
예제 #3
0
		private void Session_OnEnd(object sender, ServiceContext e)
		{
			lock (_logLock)
			{
				_invokes.Add(((MeropsMonitorSession)sender).InvokeInfo);
			}
		}
예제 #4
0
		public async Task ProcessAsync(ServiceContext context, Func<ServiceContext, Task> next)
		{
			var stopwatch = Stopwatch.StartNew();
			await next(context);
			stopwatch.Stop();
			//Console.WriteLine($"Service: {context.Service.Name}, Action: {context.Action.Name}, Request Length: {context.Request.ContentLength}bytes");
		}
예제 #5
0
		public void OnExecuted(ServiceContext context)
		{
			if (context.Exception != null)
			{
				Console.WriteLine(context.Action.Name + " exception occored: " + context.Exception);
			}
			else
			{
				Console.WriteLine(context.Action.Name + " execute result: " + Newtonsoft.Json.JsonConvert.SerializeObject(context.Result).Substring(0, 100));
			}
		}
예제 #6
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task ProcessAsync(ServiceContext context)
        {
            LogHelper.Debug("RpcService.BeginProcessRequest");

            if (context.Request.ActionName == "?meta" || string.IsNullOrEmpty(context.Request.ActionName))
            {
                LogHelper.Debug("RpcService.BeginProcessRequest: start ActionHelper.InvokeAction");
                try
                {
                    var metaInfo = GetMetaInfo(context.Service);
                    context.Result = metaInfo;
                    context.Request.RequestType = RequestType.MetaData;
                }
                catch (Exception ex)
                {
                    context.Exception = ex;
                }
                LogHelper.Debug("RpcService.BeginProcessRequest: end ActionHelper.InvokeAction");

                return TaskHelper.FromResult((object)null);
            }

            LogHelper.Debug("RpcService.BeginProcessRequest: start ActionHelper.GetActionInfo");
            var action = _actionManager.GetAction(context.Request.ActionName);
            LogHelper.Debug("RpcService.BeginProcessRequest: end ActionHelper.GetActionInfo");
            if (action == null)
            {
                LogHelper.Debug("Action Not Found: " + context.Request.ActionName);
                throw new ActionNotFoundException(context.Request.ActionName);
            }

            LogHelper.Debug("RpcService.BeginProcessRequest: got requestObject");

            context.Action = action;

            GroupFilters();
            var filterFunc = GetProcessFilterFunc();

            return filterFunc(context);
        }
예제 #7
0
		public IServiceMonitorSession GetServiceSession(ServiceContext context)
		{
			var session = new MeropsMonitorSession();
			session.OnEnd += Session_OnEnd;
			return session;
		}
예제 #8
0
		public void EndRequest(ServiceContext context)
		{
			_info.Action = context.Action.Name;
			_info.EndDate = DateTime.UtcNow;
			_info.Duration = (int)(_info.EndDate - _info.StartDate).TotalMilliseconds;
			OnEnd?.Invoke(this, context);
		}
예제 #9
0
		public void BeginRequest(ServiceContext context)
		{
			_info.Id = Guid.NewGuid().ToString();
			_info.Service = context.Service.Name;
			_info.StartDate = DateTime.UtcNow;
		}
예제 #10
0
 /// <summary>
 /// <para>determinate if the request path is Service path</para>
 /// <para>get and set Service to serviceContext</para>
 /// <para>compute and set ActionName to serviceContext.Request</para>
 /// </summary>
 /// <param name="serviceContext"></param>
 /// <returns></returns>
 public MapServiceResult MapService(ServiceContext serviceContext)
 {
     return _serviceMapper.MapService(serviceContext);
 }
예제 #11
0
        private void EndProcessRequest(ServiceContext context)
        {
            //LogHelper.Debug("RpcAsyncHandler.EndProcessRequest start RpcService.EndProcessRequest(result);");

            var httpContext = context.ExecutingContext;

            if (httpContext == null)
            {
                //LogHelper.Error("ServiceContext is null", null);
                return;
            }

            httpContext.ResponseContentType = context.Response.ContentType;

            #if DEBUG
            var startTimeObj = context.GetExtensionData("StartTime");
            var endTimeObj = context.GetExtensionData("EndTime");
            if (startTimeObj != null && endTimeObj != null)
            {
                httpContext.SetResponseHeader(HeaderName.ExecutionDuration,
                    ((DateTime)endTimeObj - (DateTime)startTimeObj).TotalMilliseconds.ToString(CultureInfo.InvariantCulture));
            }
            #endif

            if (context.Exception != null)
            {
                httpContext.SetResponseHeader(HeaderName.ExceptionType, context.Exception.GetType().FullName);
                httpContext.SetResponseHeader(HeaderName.ExceptionAssembly, context.Exception.GetType()
            #if NETCORE
                    .GetTypeInfo()
            #endif
                    .Assembly.FullName);
                httpContext.SetResponseHeader(HeaderName.StatusCode, RpcStatusCode.InternalServerError);
                //httpContext.SetResponseStatusCode((int)HttpStatusCode.InternalServerError);

                if (context.Formatter == null)
                    throw context.Exception;

                //var stream = new MemoryStream();
                //context.Formatter.Serialize(stream, context.Exception);

            #if OUTPUT_SERIALIZATION_TIME
                var serializationStopwatch = Stopwatch.StartNew();
            #endif
                if (context.Formatter.SupportException)
                    context.Formatter.Serialize(context.Response.ResponseStream, context.Exception, context.Exception.GetType());
            #if OUTPUT_SERIALIZATION_TIME
                serializationStopwatch.Stop();
                Console.WriteLine("serializationStopwatch.ElapsedMilliseconds {0}", serializationStopwatch.ElapsedMilliseconds);
            #endif
            }
            else
            {
                httpContext.SetResponseHeader(HeaderName.StatusCode, RpcStatusCode.Ok);

                if (context.Result != null)
                {
                    if (context.Request.RequestType == RequestType.MetaData)
                    {
                        if (string.IsNullOrWhiteSpace(context.Request.ContentType))
                        {
                            httpContext.ResponseContentType = "text/html";
                            using (var writer = new StreamWriter(context.Response.ResponseStream))
                            {
                                var value = context.Result.ToString();
                                var html = WebUtility.HtmlEncode(value);
                                html = html
                                    .Replace(" ", "&nbsp;")
                                    .Replace(Environment.NewLine, "<br />");
                                writer.Write(html);
                            }
                        }
                        else
                        {
            #if OUTPUT_SERIALIZATION_TIME
                            var serializationStopwatch = Stopwatch.StartNew();
            #endif
                            context.Formatter.Serialize(context.Response.ResponseStream, context.Result, context.Action.ResultType);
            #if OUTPUT_SERIALIZATION_TIME
                            serializationStopwatch.Stop();
                            Console.WriteLine("serializationStopwatch.ElapsedMilliseconds {0}", serializationStopwatch.ElapsedMilliseconds);
            #endif
                        }
                    }
                    else if (context.Action != null && context.Action.HasReturnValue)
                    {
            #if OUTPUT_SERIALIZATION_TIME
                        var serializationStopwatch = Stopwatch.StartNew();
            #endif
                        context.Formatter.Serialize(context.Response.ResponseStream, context.Result, context.Action.ResultType);
            #if OUTPUT_SERIALIZATION_TIME
                        serializationStopwatch.Stop();
                        Console.WriteLine("serializationStopwatch.ElapsedMilliseconds {0}", serializationStopwatch.ElapsedMilliseconds);
            #endif
                    }
                }
            }

            //LogHelper.Debug("RpcAsyncHandler.EndProcessRequest end RpcService.EndProcessRequest(result);");
        }
예제 #12
0
        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="filter"></param>
        //public void AddFilter(IRpcServiceFilter filter)
        //{
        //    Filters.Add(filter);
        //}
        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="filter"></param>
        //public void RemoveFilter(IRpcServiceFilter filter)
        //{
        //    Filters.Remove(filter);
        //}
        /// <summary>
        /// 
        /// </summary>
        /// <param name="serverContext"></param>
        /// <returns>if true process processed or else the path not a service path</returns>
        public Task<bool> ProcessAsync(IServerContext serverContext)
        {
            if (serverContext == null)
                throw new ArgumentNullException(nameof(serverContext));

            var serviceContext = new ServiceContext
            {
                Request = new ServiceRequest
                {
                    RequestStream = serverContext.RequestStream,
                    Path = serverContext.RequestPath,
                    ContentType = serverContext.RequestContentType,
                    ContentLength = serverContext.RequestContentLength,
                },
                Response = new ServiceResponse
                {
                    ResponseStream = serverContext.ResponseStream,
                },
                ExecutingContext = serverContext,
            };

            return ProcessInternalAsync(serviceContext)
                .ContinueWith(tsk =>
                {
                    if (tsk.Exception == null)
                        return tsk.Result;

                    LogHelper.Error(tsk.Exception.InnerException);
                    return true;
                });
        }
예제 #13
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public IServiceMonitorSession GetServiceSession(ServiceContext context)
 {
     return new ConsoleMonitorSession();
 }
예제 #14
0
        private void ApplyExecutingFilters(ServiceContext context)
        {
            if (!(Service?.ActionExecteFilter?.Count > 0))
                return;

            foreach (var item in Service.ActionExecteFilter)
            {
                try
                {
                    item.OnExecuting(context);
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                }
            }
        }
예제 #15
0
 //private IMonitor _monitor;
 ///// <summary>
 ///// 
 ///// </summary>
 ///// <param name="monitor"></param>
 //public ConsoleMonitorSession(IMonitor monitor)
 //{
 //    _monitor = monitor;
 //}
 /// <summary>
 /// 
 /// </summary>
 /// <param name="context"></param>
 public void BeginRequest(ServiceContext context)
 {
 }
예제 #16
0
        private static Task InvokeTaskInternal(ServiceContext context)
        {
            object serviceObject = null;
            if (!context.Action.IsStatic)
            {
                var serviceContainer = ServiceFactory.GetService(context.Action);
                context.ServiceContainer = serviceContainer;
                serviceObject = serviceContainer.ServiceObject;
            }

            var ar = (Task)context.Action.InvokeTask(serviceObject, context.Argument);
            return ar;
        }
예제 #17
0
        private static object GetResultObject(IAsyncResult ar, ServiceContext context)
        {
            object resultObject = null;
            var serviceContainer = (ServiceInstanceContainer)context.ServiceContainer;

            try
            {
                if (context.Action.IsTask)
                {
                    var task = ar as Task;
                    if (task == null)
                        throw new ServiceException("task async api return no Task result");

                    resultObject = GetTaskResult(task);
                }
                else
                {
                    if (context.Action.HasReturnValue)
                    {
                        resultObject = context.Result;
                    }
                }
            }
            finally
            {
                if (serviceContainer != null && !context.Action.IsStatic)
                {
                    serviceContainer.Dispose();
                }
            }

            return resultObject;
        }
예제 #18
0
        /// <summary>
        /// invoke methods
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task ExecuteAsync(ServiceContext context)
        {
            if (ArgumentCount > 0)
            {
                try
                {
                    context.Argument = context.Request.ContentLength > 0
                        ? GetRequestObject(context.Request.RequestStream, context.Formatter, ArgumentType)
                        : DefaultArgument;
                }
                catch (Exception ex)
                {
                    context.Exception = new DeserializeRequestException("deserialize request error", ex);
                    return TaskHelper.FromResult<object>(null);
                }
            }

            ApplyExecutingFilters(context);

            if (IsTask)
            {
                try
                {
                    var task = InvokeTaskInternal(context);

                    var waitTask = task.ContinueWith(tsk =>
                    {
                        if (tsk.Exception != null)
                        {
                            context.Exception = tsk.Exception.InnerException;
                        }
                        else
                        {
                            var result = GetResultObject(tsk, context);
                            context.Result = result;
                        }

                        ApplyExecutedFilters(context);
                    });

                    return waitTask;
                }
                catch (Exception ex)
                {
                    context.Exception = ex;
                    ApplyExecutedFilters(context);

                    return TaskHelper.FromResult<object>(null);
                }
            }
            else
            {
                LogHelper.Debug("RpcService.BeginProcessRequest: start ActionHelper.InvokeAction");
                try
                {
                    context.Result = InvokeAction(context.Argument);
                }
                catch (Exception ex)
                {
                    context.Exception = ex;

                    var tcs = new TaskCompletionSource<object>();
                    tcs.SetResult(null);
                    return tcs.Task;
                }
                ApplyExecutedFilters(context);
                LogHelper.Debug("RpcService.BeginProcessRequest: end ActionHelper.InvokeAction");

                return TaskHelper.FromResult(context.Result);
            }
        }
예제 #19
0
 /// <summary>
 /// <para>determinate if the request path is Service path</para>
 /// <para>get and set Service to serviceContext</para>
 /// <para>compute and set ActionName to serviceContext.Request</para>
 /// </summary>
 /// <param name="serviceContext"></param>
 /// <returns></returns>
 public MapServiceResult MapService(ServiceContext serviceContext)
 {
     return(_serviceMapper.MapService(serviceContext));
 }
예제 #20
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="context"></param>
 public void EndRequest(ServiceContext context)
 {
 }
예제 #21
0
        private void ApplyBeforeInvokeFilters(ServiceContext context)
        {
            if (_invokeFilters == null) return;

            foreach (var item in _invokeFilters)
            {
                try
                {
                    item.OnInvoking(context);
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                }
            }
        }
예제 #22
0
		public void OnExecuting(ServiceContext context)
		{
			Console.WriteLine(context.Action.Name + " before execute action");
		}
예제 #23
0
		public async Task ProcessAsync(ServiceContext context, Func<ServiceContext, Task> next)
		{
			await next(context);
		}
예제 #24
0
        private Task ProcessRequest(ServiceContext context)
        {
            ApplyBeforeInvokeFilters(context);

            var task = context.Action.ExecuteAsync(context);
            var waitTask = task.ContinueWith(tsk =>
            {
                ApplyAfterInvokeFilters(context);
            });

            return waitTask;
        }