public static Task HandleNotification(IHandlerDescriptor instance)
        {
            var method = instance.HandlerType.GetTypeInfo()
                         .GetMethod(nameof(INotificationHandler.Handle), BindingFlags.Public | BindingFlags.Instance);

            return((Task)method.Invoke(instance.Handler, new object[0]));
        }
        public static Task HandleRequest(IHandlerDescriptor instance, object @params, CancellationToken token)
        {
            var method = instance.HandlerType.GetTypeInfo()
                         .GetMethod(nameof(IRequestHandler <object, object> .Handle), BindingFlags.Public | BindingFlags.Instance);

            return((Task)method.Invoke(instance.Handler, new[] { @params, token }));
        }
示例#3
0
        protected virtual async Task <ErrorResponse> RouteRequest(IHandlerDescriptor handler, Request request, CancellationToken token)
        {
            if (request.Method is null)
            {
                return(new MethodNotFound(request.Id, request.Method));
            }

            object @params;

            try
            {
                @params = request.Params.ToObject(handler.Params, _serializer.JsonSerializer);
            }
            catch
            {
                return(new InvalidParams(request.Id));
            }

            var result = ReflectionRequestHandlers.HandleRequest(handler, @params, token);

            await result.ConfigureAwait(false);

            object responseValue = null;

            if (result.GetType().GetTypeInfo().IsGenericType)
            {
                var property = typeof(Task <>)
                               .MakeGenericType(result.GetType().GetTypeInfo().GetGenericArguments()[0]).GetTypeInfo()
                               .GetProperty(nameof(Task <object> .Result), BindingFlags.Public | BindingFlags.Instance);

                responseValue = property.GetValue(result);
            }

            return(new Client.Response(request.Id, responseValue));
        }
示例#4
0
 public async Task RouteNotification(IHandlerDescriptor descriptor, Notification notification)
 {
     using (_logger.TimeDebug("Routing Notification {Method}", notification.Method))
     {
         using (_logger.BeginScope(new KeyValuePair <string, string>[] {
             new KeyValuePair <string, string>("Method", notification.Method),
             new KeyValuePair <string, string>("Params", notification.Params?.ToString())
         }))
         {
             try
             {
                 if (descriptor.Params is null)
                 {
                     await ReflectionRequestHandlers.HandleNotification(descriptor);
                 }
                 else
                 {
                     _logger.LogDebug("Converting params for Notification {Method} to {Type}", notification.Method, descriptor.Params.FullName);
                     var @params = notification.Params.ToObject(descriptor.Params, _serializer.JsonSerializer);
                     await ReflectionRequestHandlers.HandleNotification(descriptor, @params);
                 }
             }
             catch (Exception e)
             {
                 _logger.LogCritical(Events.UnhandledRequest, e, "Failed to handle request {Method}", notification.Method);
             }
         }
     }
 }
        public RequestProcessType Identify(IHandlerDescriptor descriptor)
        {
            if (_cache.TryGetValue(descriptor.HandlerType, out var type))
            {
                return(type);
            }

            type = _defaultRequestProcessType;
            var handlerType      = descriptor.ImplementationType;
            var processAttribute = descriptor.ImplementationType
                                   .GetCustomAttributes(true)
                                   .Concat(descriptor.HandlerType.GetCustomAttributes(true))
                                   .Concat(descriptor.ImplementationType.GetInterfaces().SelectMany(x => x.GetCustomAttributes()))
                                   .Concat(descriptor.HandlerType.GetInterfaces().SelectMany(x => x.GetCustomAttributes()))
                                   .OfType <ProcessAttribute>()
                                   .FirstOrDefault();

            if (processAttribute != null)
            {
                type = processAttribute.Type;
            }

            _cache.TryAdd(descriptor.HandlerType, type);

            return(type);
        }
示例#6
0
        public async Task RouteNotification(IHandlerDescriptor descriptor, Notification notification)
        {
            using (_logger.TimeDebug("Routing Notification {Method}", notification.Method))
            {
                using (_logger.BeginScope(new[] {
                    new KeyValuePair <string, string>("Method", notification.Method),
                    new KeyValuePair <string, string>("Params", notification.Params?.ToString())
                }))
                    using (var scope = _serviceScopeFactory.CreateScope())
                    {
                        var context = scope.ServiceProvider.GetRequiredService <IRequestContext>();
                        context.Descriptor = descriptor;
                        var mediator = scope.ServiceProvider.GetRequiredService <IMediator>();

                        try
                        {
                            if (descriptor.Params is null)
                            {
                                await MediatRHandlers.HandleNotification(mediator, descriptor, EmptyRequest.Instance, CancellationToken.None);
                            }
                            else
                            {
                                _logger.LogDebug("Converting params for Notification {Method} to {Type}", notification.Method, descriptor.Params.FullName);
                                var @params = (notification.Params ?? new JObject()).ToObject(descriptor.Params, _serializer.JsonSerializer);

                                await MediatRHandlers.HandleNotification(mediator, descriptor, @params ?? EmptyRequest.Instance, CancellationToken.None);
                            }
                        }
                        catch (Exception e)
                        {
                            _logger.LogCritical(Events.UnhandledRequest, e, "Failed to handle request {Method}", notification.Method);
                        }
                    }
            }
        }
示例#7
0
        public async Task RouteNotification(IHandlerDescriptor handler, Notification notification)
        {
            using (var scope = _serviceScopeFactory.CreateScope())
            {
                var context = scope.ServiceProvider.GetRequiredService <IRequestContext>();
                context.Descriptor = handler;

                object @params = null;
                if (!(handler.Params is null))
                {
                    @params = notification.Params.ToObject(handler.Params, _serializer.JsonSerializer);
                }
                await MediatRHandlers.HandleNotification(scope.ServiceProvider.GetRequiredService <IMediator>(), handler, @params ?? EmptyRequest.Instance, CancellationToken.None).ConfigureAwait(false);
            }
        }
 public static Task HandleRequest(IMediator mediator, IHandlerDescriptor descriptor, object @params, CancellationToken token)
 {
     if (!descriptor.HasReturnType)
     {
         return((Task)SendRequestUnit
                .MakeGenericMethod(descriptor.Params)
                .Invoke(null, new object[] { mediator, @params, token }));
     }
     else
     {
         return((Task)SendRequestResponse
                .MakeGenericMethod(descriptor.Params, descriptor.Response)
                .Invoke(null, new object[] { mediator, @params, token }));
     }
 }
示例#9
0
        public async Task RouteNotification(IHandlerDescriptor handler, Notification notification)
        {
            Task result;

            if (handler.Params is null)
            {
                result = ReflectionRequestHandlers.HandleNotification(handler);
            }
            else
            {
                var @params = notification.Params.ToObject(handler.Params, _serializer.JsonSerializer);
                result = ReflectionRequestHandlers.HandleNotification(handler, @params);
            }
            await result.ConfigureAwait(false);
        }
 public static Task HandleRequest(IMediator mediator, IHandlerDescriptor handler, object @params, CancellationToken token)
 {
     if (handler.HandlerType.GetInterfaces().Any(x =>
                                                 x.IsGenericType && typeof(IRequestHandler <>).IsAssignableFrom(x.GetGenericTypeDefinition())))
     {
         return((Task)SendRequestUnit
                .MakeGenericMethod(handler.Params)
                .Invoke(null, new object[] { mediator, @params, token }));
     }
     else
     {
         return((Task)SendRequestResponse
                .MakeGenericMethod(handler.Params, handler.Response)
                .Invoke(null, new object[] { mediator, @params, token }));
     }
 }
示例#11
0
        protected virtual async Task <ErrorResponse> RouteRequest(IHandlerDescriptor handler, Request request, CancellationToken token)
        {
            using (var scope = _serviceScopeFactory.CreateScope())
            {
                var context = scope.ServiceProvider.GetRequiredService <IRequestContext>();
                context.Descriptor = handler;

                if (request.Method is null)
                {
                    return(new MethodNotFound(request.Id, request.Method));
                }

                object @params;
                try
                {
                    @params = request.Params.ToObject(handler.Params, _serializer.JsonSerializer);
                }
                catch
                {
                    return(new InvalidParams(request.Id));
                }

                var result = MediatRHandlers.HandleRequest(scope.ServiceProvider.GetRequiredService <IMediator>(), handler, @params, token);

                await result.ConfigureAwait(false);

                object responseValue = null;
                if (result.GetType().GetTypeInfo().IsGenericType)
                {
                    var property = typeof(Task <>)
                                   .MakeGenericType(result.GetType().GetTypeInfo().GetGenericArguments()[0]).GetTypeInfo()
                                   .GetProperty(nameof(Task <object> .Result), BindingFlags.Public | BindingFlags.Instance);

                    responseValue = property.GetValue(result);
                    if (responseValue?.GetType() == typeof(Unit))
                    {
                        responseValue = null;
                    }
                }

                return(new Client.Response(request.Id, responseValue));
            }
        }
        public async Task RouteNotification(IHandlerDescriptor handler, Notification notification)
        {
            try
            {
                Task result;
                if (handler.Params is null)
                {
                    result = ReflectionRequestHandlers.HandleNotification(handler);
                }
                else
                {
                    var @params = notification.Params.ToObject(handler.Params);
                    result = ReflectionRequestHandlers.HandleNotification(handler, @params);
                }

                await result;
            }
            catch (Exception e)
            {
                _logger.LogCritical(Events.UnhandledRequest, e, "Failed to handle request {Method}", notification.Method);
            }
        }
        public async Task RouteNotification(IHandlerDescriptor descriptor, Notification notification)
        {
            using (_logger.TimeDebug("Routing Notification {Method}", notification.Method))
            {
                using (_logger.BeginScope(new KeyValuePair <string, string>[] {
                    new KeyValuePair <string, string>("Method", notification.Method),
                    new KeyValuePair <string, string>("Params", notification.Params?.ToString())
                }))
                {
                    try
                    {
                        if (descriptor.Params is null)
                        {
                            await ReflectionRequestHandlers.HandleNotification(descriptor);
                        }
                        else
                        {
                            _logger.LogDebug("Converting params for Notification {Method} to {Type}", notification.Method, descriptor.Params.FullName);
                            var @params = notification.Params.ToObject(descriptor.Params, _serializer.JsonSerializer);

                            var lspDescriptor = descriptor as ILspHandlerDescriptor;

                            foreach (var preProcessor in _routeMatchers.ForHandlerPreProcessorMatcher()
                                     .SelectMany(strat => strat.FindPreProcessor(lspDescriptor, @params)))
                            {
                                @params = preProcessor.Process(lspDescriptor, @params);
                            }

                            await ReflectionRequestHandlers.HandleNotification(descriptor, @params);
                        }
                    }
                    catch (Exception e)
                    {
                        _logger.LogCritical(Events.UnhandledRequest, e, "Failed to handle request {Method}", notification.Method);
                    }
                }
            }
        }
        public RequestProcessType Identify(IHandlerDescriptor descriptor)
        {
            if (descriptor.RequestProcessType.HasValue)
            {
                return(descriptor.RequestProcessType.Value);
            }

            if (_cache.TryGetValue(descriptor.HandlerType, out var type))
            {
                return(type);
            }

            type = _defaultRequestProcessType;
            var typeDescriptor = HandlerTypeDescriptorHelper.GetHandlerTypeDescriptor(descriptor.HandlerType);

            if (typeDescriptor?.RequestProcessType.HasValue == true)
            {
                type = typeDescriptor.RequestProcessType.Value;
            }
            else
            {
                var processAttribute = descriptor.ImplementationType
                                       .GetCustomAttributes(true)
                                       .Concat(descriptor.HandlerType.GetCustomAttributes(true))
                                       .OfType <ProcessAttribute>()
                                       .FirstOrDefault();
                if (processAttribute != null)
                {
                    type = processAttribute.Type;
                }
            }

            _cache.TryAdd(descriptor.HandlerType, type);

            return(type);
        }
示例#15
0
        public RequestProcessType Identify(IHandlerDescriptor descriptor)
        {
            if (_cache.TryGetValue(descriptor.HandlerType, out var type))
            {
                return(type);
            }

            type = _defaultRequestProcessType;
            var handlerType      = descriptor.Handler.GetType().GetTypeInfo();
            var processAttribute = handlerType
                                   .GetCustomAttributes(true)
                                   .Concat(descriptor.HandlerType.GetTypeInfo().GetCustomAttributes(true))
                                   .OfType <ProcessAttribute>()
                                   .FirstOrDefault();

            if (processAttribute != null)
            {
                type = processAttribute.Type;
            }

            _cache.TryAdd(descriptor.HandlerType, type);

            return(type);
        }
示例#16
0
        public async Task <ErrorResponse> RouteRequest(IHandlerDescriptor descriptor, Request request)
        {
            using (_logger.TimeDebug("Routing Request ({Id}) {Method}", request.Id, request.Method))
            {
                using (_logger.BeginScope(new[] {
                    new KeyValuePair <string, string>("Id", request.Id?.ToString()),
                    new KeyValuePair <string, string>("Method", request.Method),
                    new KeyValuePair <string, string>("Params", request.Params?.ToString())
                }))
                    using (var scope = _serviceScopeFactory.CreateScope())
                    {
                        var context = scope.ServiceProvider.GetRequiredService <IRequestContext>();
                        context.Descriptor = descriptor;
                        var mediator = scope.ServiceProvider.GetRequiredService <IMediator>();

                        var id  = GetId(request.Id);
                        var cts = new CancellationTokenSource();
                        _requests.TryAdd(id, cts);

                        // TODO: Try / catch for Internal Error
                        try
                        {
                            if (descriptor is null)
                            {
                                _logger.LogDebug("descriptor not found for Request ({Id}) {Method}", request.Id, request.Method);
                                return(new MethodNotFound(request.Id, request.Method));
                            }

                            object @params;
                            try
                            {
                                _logger.LogDebug("Converting params for Request ({Id}) {Method} to {Type}", request.Id, request.Method, descriptor.Params.FullName);
                                @params = request.Params?.ToObject(descriptor.Params, _serializer.JsonSerializer);
                            }
                            catch (Exception cannotDeserializeRequestParams)
                            {
                                _logger.LogError(new EventId(-32602), cannotDeserializeRequestParams, "Failed to deserialise request parameters.");
                                return(new InvalidParams(request.Id));
                            }

                            var   result = MediatRHandlers.HandleRequest(mediator, descriptor, @params ?? EmptyRequest.Instance, cts.Token);
                            await result;

                            _logger.LogDebug("Result was {Type}", result.GetType().FullName);

                            object responseValue = null;
                            if (result.GetType().GetTypeInfo().IsGenericType)
                            {
                                var property = typeof(Task <>)
                                               .MakeGenericType(result.GetType().GetTypeInfo().GetGenericArguments()[0]).GetTypeInfo()
                                               .GetProperty(nameof(Task <object> .Result), BindingFlags.Public | BindingFlags.Instance);

                                responseValue = property.GetValue(result);
                                if (responseValue?.GetType() == typeof(Unit))
                                {
                                    responseValue = null;
                                }
                                _logger.LogDebug("Response value was {Type}", responseValue?.GetType().FullName);
                            }

                            return(new JsonRpc.Client.Response(request.Id, responseValue));
                        }
                        catch (TaskCanceledException e)
                        {
                            _logger.LogDebug("Request {Id} was cancelled", id);
                            return(new RequestCancelled());
                        }
                        catch (Exception e)
                        {
                            _logger.LogCritical(Events.UnhandledRequest, e, "Failed to handle notification {Method}", request.Method);
                            return(new InternalError(id, e.ToString()));
                        }
                        finally
                        {
                            _requests.TryRemove(id, out var _);
                        }
                    }
            }
        }
 public RequestProcessType Identify(IHandlerDescriptor descriptor)
 {
     return(descriptor.RequestProcessType ?? RequestProcessType.Parallel);
 }
示例#18
0
 public Task <ErrorResponse> RouteRequest(IHandlerDescriptor descriptor, Request request)
 {
     return(RouteRequest(descriptor, request, CancellationToken.None));
 }
        public async Task <ErrorResponse> RouteRequest(IHandlerDescriptor descriptor, Request request)
        {
            var id  = GetId(request.Id);
            var cts = new CancellationTokenSource();

            _requests.TryAdd(id, cts);

            // TODO: Try / catch for Internal Error
            try
            {
                if (descriptor is null)
                {
                    return(new MethodNotFound(request.Id, request.Method));
                }

                Task result;
                if (descriptor.Params is null)
                {
                    result = ReflectionRequestHandlers.HandleRequest(descriptor, cts.Token);
                }
                else
                {
                    object @params;
                    try
                    {
                        @params = request.Params.ToObject(descriptor.Params);
                    }
                    catch
                    {
                        return(new InvalidParams(request.Id));
                    }

                    result = ReflectionRequestHandlers.HandleRequest(descriptor, @params, cts.Token);
                }

                await result.ConfigureAwait(false);

                object responseValue = null;
                if (result.GetType().GetTypeInfo().IsGenericType)
                {
                    var property = typeof(Task <>)
                                   .MakeGenericType(result.GetType().GetTypeInfo().GetGenericArguments()[0]).GetTypeInfo()
                                   .GetProperty(nameof(Task <object> .Result), BindingFlags.Public | BindingFlags.Instance);

                    responseValue = property.GetValue(result);
                }

                return(new JsonRpc.Client.Response(request.Id, responseValue));
            }
            catch (TaskCanceledException)
            {
                return(new RequestCancelled());
            }
            catch (Exception e)
            {
                _logger.LogCritical(Events.UnhandledRequest, e, "Failed to handle notification {Method}", request.Method);
                return(new InternalError(id));
            }
            finally
            {
                _requests.TryRemove(id, out var _);
            }
        }
 public static Task HandleNotification(IMediator mediator, IHandlerDescriptor handler, object @params, CancellationToken token)
 {
     return((Task)SendRequestUnit
            .MakeGenericMethod(handler.Params ?? typeof(EmptyRequest))
            .Invoke(null, new object[] { mediator, @params, token }));
 }
        public async Task <ErrorResponse> RouteRequest(IHandlerDescriptor descriptor, Request request)
        {
            using (_logger.TimeDebug("Routing Request ({Id}) {Method}", request.Id, request.Method))
            {
                using (_logger.BeginScope(new KeyValuePair <string, string>[] {
                    new KeyValuePair <string, string>("Id", request.Id?.ToString()),
                    new KeyValuePair <string, string>("Method", request.Method),
                    new KeyValuePair <string, string>("Params", request.Params?.ToString())
                }))
                {
                    var id  = GetId(request.Id);
                    var cts = new CancellationTokenSource();
                    _requests.TryAdd(id, cts);

                    // TODO: Try / catch for Internal Error
                    try
                    {
                        if (descriptor is null)
                        {
                            _logger.LogDebug("descriptor not found for Request ({Id}) {Method}", request.Id, request.Method);
                            return(new MethodNotFound(request.Id, request.Method));
                        }

                        object @params;
                        try
                        {
                            _logger.LogDebug("Converting params for Request ({Id}) {Method} to {Type}", request.Id, request.Method, descriptor.Params.FullName);
                            @params = request.Params?.ToObject(descriptor.Params, _serializer.JsonSerializer);
                        }
                        catch (Exception cannotDeserializeRequestParams)
                        {
                            _logger.LogError(new EventId(-32602), cannotDeserializeRequestParams, "Failed to deserialise request parameters.");
                            return(new InvalidParams(request.Id));
                        }

                        var lspDescriptor = descriptor as ILspHandlerDescriptor;

                        foreach (var preProcessor in _routeMatchers.ForHandlerPreProcessorMatcher()
                                 .SelectMany(strat => strat.FindPreProcessor(lspDescriptor, @params)))
                        {
                            @params = preProcessor.Process(lspDescriptor, @params);
                        }

                        var   result = ReflectionRequestHandlers.HandleRequest(descriptor, @params, cts.Token);
                        await result;

                        _logger.LogDebug("Result was {Type}", result.GetType().FullName);

                        object responseValue = null;
                        if (result.GetType().GetTypeInfo().IsGenericType)
                        {
                            var property = typeof(Task <>)
                                           .MakeGenericType(result.GetType().GetTypeInfo().GetGenericArguments()[0]).GetTypeInfo()
                                           .GetProperty(nameof(Task <object> .Result), BindingFlags.Public | BindingFlags.Instance);

                            responseValue = property.GetValue(result);
                            _logger.LogDebug("Response value was {Type}", responseValue?.GetType().FullName);

                            foreach (var postProcessor in _routeMatchers.ForHandlerPostProcessorMatcher()
                                     .SelectMany(strat => strat.FindPostProcessor(lspDescriptor, @params, responseValue)))
                            {
                                responseValue = postProcessor.Process(lspDescriptor, @params, responseValue);
                            }
                        }

                        return(new JsonRpc.Client.Response(request.Id, responseValue));
                    }
                    catch (TaskCanceledException e)
                    {
                        _logger.LogDebug("Request {Id} was cancelled", id);
                        return(new RequestCancelled());
                    }
                    catch (Exception e)
                    {
                        _logger.LogCritical(Events.UnhandledRequest, e, "Failed to handle notification {Method}", request.Method);
                        return(new InternalError(id));
                    }
                    finally
                    {
                        _requests.TryRemove(id, out var _);
                    }
                }
            }
        }
 public LinkedHandler(string method, IHandlerDescriptor descriptor, Action disposeAction)
 {
     _descriptor    = descriptor;
     _disposeAction = disposeAction;
     Method         = method;
 }
 Task IRequestRouter <IHandlerDescriptor> .RouteNotification(IHandlerDescriptor descriptor, Notification notification, CancellationToken token) =>
 RouteNotification(
示例#24
0
 public RequestProcessType Identify(IHandlerDescriptor descriptor) => descriptor.RequestProcessType ?? RequestProcessType.Serial;
 public RequestProcessType Identify(IHandlerDescriptor descriptor)
 {
     return(RequestProcessType.Serial);
 }