Пример #1
0
        public override async Task Invoke(MiddlewareContext context)
        {
            Assert.IsNotNull(context.WebServer, "Webserver is not null");
            Assert.IsNotNull(context.HttpContext, "HttpContext is not null");
            Assert.IsNotNull(context.Handled, "Handled is not null");

            await Task.Delay(10);

            context.HttpContext.JsonResponse(Json.Serialize(new {Status = "OK"}));

            context.Handled = true;
        }
Пример #2
0
    private static bool TryCompleteCompositeListValue(
        IOperationContext operationContext,
        MiddlewareContext resolverContext,
        ISelection selection,
        Path path,
        IType fieldType,
        string responseName,
        int responseIndex,
        object?result,
        List <ResolverTask> bufferedTasks,
        out object?completedResult)
    {
        ResultMapList resultList  = operationContext.Result.RentResultMapList();
        IType         elementType = fieldType.InnerType();

        resultList.IsNullable = elementType.Kind is not TypeKind.NonNull;

        if (result is Array array)
        {
            for (var i = 0; i < array.Length; i++)
            {
                if (!TryCompleteElement(path.Append(i), array.GetValue(i)))
                {
                    completedResult = null;
                    return(true);
                }
            }

            completedResult = resultList;
            return(true);
        }

        if (result is IList list)
        {
            for (var i = 0; i < list.Count; i++)
            {
                if (!TryCompleteElement(path.Append(i), list[i]))
                {
                    completedResult = null;
                    return(true);
                }
            }

            completedResult = resultList;
            return(true);
        }

        if (result is IEnumerable enumerable)
        {
            var index = 0;

            foreach (var element in enumerable)
            {
                if (!TryCompleteElement(path.Append(index++), element))
                {
                    completedResult = null;
                    return(true);
                }
            }

            completedResult = resultList;
            return(true);
        }

        ReportError(
            operationContext,
            resolverContext,
            selection,
            ListValueIsNotSupported(resultList.GetType(), selection.SyntaxNode, path));

        completedResult = null;
        return(false);

        bool TryCompleteElement(Path elementPath, object?elementResult)
        {
            if (TryComplete(
                    operationContext,
                    resolverContext,
                    selection,
                    elementPath,
                    elementType,
                    responseName,
                    responseIndex,
                    elementResult,
                    bufferedTasks,
                    out var completedElement) &&
                completedElement is ResultMap resultMap)
            {
                resultMap.Parent = resultList;
                resultList.Add(resultMap);
            }
            else if (resultList.IsNullable)
            {
                resultList.Add(null);
            }
            else
            {
                return(false);
            }

            return(true);
        }
    }
Пример #3
0
 internal AdaptorUserRepository(MiddlewareContext context)
     : base(context)
 {
 }
Пример #4
0
        public void Execute(MessageContext context, Action <MessageContext, MiddlewareContext> next, MiddlewareContext middlewarecontext)
        {
            var telemetry = new RequestTelemetry();

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            var name = context.Route.Name;

            if (!string.IsNullOrWhiteSpace(context.Saga?.Name))
            {
                name = $"{context.Saga?.Name}_{name}";
            }

            try
            {
                telemetry.Timestamp = context.DateTimeUtc;

                telemetry.Id = $"{context.Identity.Id}";

                telemetry.Name = name;

                telemetry.Source = context.Origin.From;

                PopulateProperties(telemetry.Properties, context);

                PopulateMetrics(telemetry.Metrics, context);

                PopulateContext(telemetry.Context, context);

                next(context, middlewarecontext);

                telemetry.ResponseCode = "200";

                telemetry.Success = true;
            }
            catch (Exception exception)
            {
                telemetry.ResponseCode = "500";

                telemetry.Success = false;

                var telemetryexception = new ExceptionTelemetry(exception);

                PopulateProperties(telemetryexception.Properties, context);

                PopulateMetrics(telemetryexception.Metrics, context);

                PopulateContext(telemetryexception.Context, context);

                Client.TrackException(telemetryexception);

                throw;
            }
            finally
            {
                telemetry.Duration = TimeSpan.FromMilliseconds(stopwatch.ElapsedMilliseconds);

                Client.TrackRequest(telemetry);
            }
        }
Пример #5
0
        public void Execute(MessageContext messagecontext, Action <MessageContext, MiddlewareContext> next, MiddlewareContext middlewarecontext)
        {
            var storage = _factory.Create <ISagaStorage>(Configuration.SagaStorageType);

            var serializer = _factory.Create <IMessageSerializer>(Configuration.MessageSerializerType);

            messagecontext.SagaContext.Status = DefaultStatus;

            var sagaentity = storage.GetSaga(messagecontext.SagaContext.Id);

            if (sagaentity != null)
            {
                messagecontext.AddTrack(messagecontext.Identity, messagecontext.Origin, messagecontext.Route, messagecontext.Saga, messagecontext.SagaContext);

                var data = serializer.Deserialize(sagaentity.Data, messagecontext.Saga.DataType);

                if (data != null)
                {
                    _router.Route(messagecontext, data);

                    sagaentity.Updated = messagecontext.DateTimeUtc;

                    SaveSaga(messagecontext, storage, sagaentity, serializer, data);

                    SaveMessage(messagecontext, storage, sagaentity);
                }
                else
                {
                    throw new ApplicationException($"Empty/Invalid data {messagecontext.Saga.DataType.FullName} for {messagecontext.Route.ContentType.FullName}, saga {messagecontext.Saga.Name} route {messagecontext.Route.Name}");
                }
            }
            else
            {
                throw new ApplicationException($"No data {messagecontext.Saga.DataType.FullName} for {messagecontext.Route.ContentType.FullName}, saga {messagecontext.Saga.Name} route {messagecontext.Route.Name}");
            }
        }
Пример #6
0
 public void Execute(MessageContext context, Action <MessageContext, MiddlewareContext> next, MiddlewareContext parameter)
 {
     if (!IsValid(context))
     {
         throw new SecurityException("Unauthorized");
     }
     next(context, parameter);
 }
 internal TaskSpecificationRequiredNodeRepository(MiddlewareContext context)
     : base(context)
 {
 }
Пример #8
0
        public void Execute(MessageContext messagecontext, Action <MessageContext, MiddlewareContext> next, MiddlewareContext middlewarecontext)
        {
            messagecontext.AddTrack(messagecontext.Identity, messagecontext.Origin, messagecontext.Route);

            if (_configuration.Storage.SaveMessage)
            {
                var storage = _factory.Create <ISagaStorage>(_configuration.SagaStorageType);

                var messageentity = new MessageEntity()
                {
                    Content     = messagecontext.Content,
                    ContentType = messagecontext.Route.ContentType.FullName,
                    Identity    = messagecontext.Identity,
                    Version     = messagecontext.Version,
                    RetryCount  = messagecontext.RetryCount,
                    LastRetry   = messagecontext.LastRetry,
                    Origin      = messagecontext.Origin,
                    Headers     = messagecontext.Headers,
                    DateTimeUtc = messagecontext.DateTimeUtc,
                    Name        = messagecontext.Route.Name,
                    Tracks      = messagecontext.Tracks,
                    ContentId   = messagecontext.ContentId,
                    Data        = string.Empty
                };

                try
                {
                    storage.CreateMessage(messagecontext, messageentity);
                }
                catch (Exception)
                {
                    if (!_configuration.Storage.IgnoreExceptionOnSaveMessage)
                    {
                        throw;
                    }
                }
            }

            _router.Route(messagecontext);
        }
Пример #9
0
 internal NotificationRepository(MiddlewareContext context)
     : base(context)
 {
 }
Пример #10
0
        public object Execute(MessageContext context, Func <MessageContext, MiddlewareContext, object> next, MiddlewareContext middlewarecontext)
        {
            var shuffler = _factory.Create <IChannelShuffler>(_configuration.ChannelShufflerType);

            var channels = shuffler.Shuffle(context.EndPoint.Channels.ToArray());

            var numberofchannels = channels.Length;

            var count = 0;

            var index = middlewarecontext.Index;

            foreach (var channel in channels)
            {
                middlewarecontext.Channel = channel;

                try
                {
                    count++;

                    return(next(context, middlewarecontext));
                }
                catch (Exception)
                {
                    if (count < numberofchannels)
                    {
                        middlewarecontext.Index = index;

                        _logger.Log($"Message {context.Identity.Id} failed to distribute ({count}), moving to the next channel");
                    }
                    else
                    {
                        _logger.Log($"Message {context.Identity.Id} failed to distribute ({count}), no more channels");

                        throw;
                    }
                }
            }

            return(null);
        }
 internal FileTransferMethodRepository(MiddlewareContext context)
     : base(context)
 {
 }
Пример #12
0
        public object Execute(MessageContext context, Func <MessageContext, MiddlewareContext, object> next, MiddlewareContext middlewarecontext)
        {
            if (middlewarecontext.Channel.IsValidEndpoint())
            {
                var channel = _factory.Create <IPointToPointChannel>(_configuration.PointToPointChannelType);

                channel.Send(middlewarecontext.Channel, context, middlewarecontext.Channel.GetPath(context.EndPoint.Name));
            }

            return(null);
        }
 internal SubmittedJobInfoRepository(MiddlewareContext context)
     : base(context)
 {
 }
Пример #14
0
 internal OpenStackDomainRepository(MiddlewareContext context)
     : base(context)
 {
 }
Пример #15
0
 internal PropertyChangeSpecificationRepository(MiddlewareContext context)
     : base(context)
 {
 }
Пример #16
0
 internal MessageTemplateRepository(MiddlewareContext context)
     : base(context)
 {
 }
 internal OpenStackInstanceRepository(MiddlewareContext context)
     : base(context)
 {
 }
Пример #18
0
        public void Execute(MessageContext messagecontext, Action <MessageContext, MiddlewareContext> next, MiddlewareContext middlewarecontext)
        {
            IRetryPolicy policy = null;

            try
            {
                if (HasRetry(messagecontext.Route))
                {
                    policy = GetRetryPolicy(messagecontext.Route);

                    if (policy != null)
                    {
                        var interval = policy.NextRetryInterval(messagecontext.RetryCount + 1);

                        messagecontext.LastRetry = !policy.CanRetry(messagecontext.RetryCount + 1, interval);
                    }
                    else
                    {
                        throw new ApplicationException("The retry policy cannot be null");
                    }
                }

                next(messagecontext, middlewarecontext);
            }
            catch (Exception ex)
            {
                if (policy != null)
                {
                    if (messagecontext.Route.RetryExceptionType == ex.GetType())
                    {
                        if (!messagecontext.LastRetry)
                        {
                            if (!string.IsNullOrWhiteSpace(messagecontext.Route.OnRetryEndPoint))
                            {
                                SendRetry(messagecontext.Route, messagecontext, policy);
                            }
                            else
                            {
                                if (!string.IsNullOrWhiteSpace(messagecontext.Route.OnErrorEndPoint))
                                {
                                    SendError(messagecontext.Route, messagecontext, ex);
                                }
                                else
                                {
                                    throw;
                                }
                            }
                        }
                        else
                        {
                            if (!string.IsNullOrWhiteSpace(messagecontext.Route.OnErrorEndPoint))
                            {
                                SendError(messagecontext.Route, messagecontext, ex);
                            }
                            else
                            {
                                throw;
                            }
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrWhiteSpace(messagecontext.Route.OnErrorEndPoint))
                        {
                            SendError(messagecontext.Route, messagecontext, ex);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(messagecontext.Route.OnErrorEndPoint))
                    {
                        SendError(messagecontext.Route, messagecontext, ex);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
        public async Task RequestIsNotSplitIfLessThanOrEqualToMaxTest(int maxRequestSize, [Frozen] MiddlewareContext context)
        {
            var options = new WebApiRequestOptions
            {
                BulkQueryParameterIdsName = "ids",
                EndpointPath  = "/some/endpoint",
                EndpointQuery = new Dictionary <string, string>
                {
                    ["ids"] = "K1,K2,K3"
                }
            };

            context.Request.Options.Returns(options);
            var elements = new[]
            {
                new Element {
                    Id = "K1", Value = "V1"
                },
                new Element {
                    Id = "K2", Value = "V2"
                },
                new Element {
                    Id = "K3", Value = "V3"
                }
            };

            var middleware = new RequestSplitterMiddleware {
                MaxRequestSize = maxRequestSize
            };
            var response = await middleware.OnRequestAsync(context, (c, t) =>
            {
                var ids = c.Request.Options.EndpointQuery["ids"].Split(',');
                ids.Should().HaveCountLessOrEqualTo(middleware.MaxRequestSize);
                ids.Should().BeEquivalentTo(elements.Select(x => x.Id));

                IWebApiResponse innerResponse = new WebApiResponse(JsonSerializer.Serialize(elements), CacheState.FromLive);
                return(Task.FromResult(innerResponse));
            });

            var actual = JsonSerializer.Deserialize <IList <Element> >(response.Content);

            actual.Should().BeEquivalentTo(elements);
        }
Пример #20
0
 public async Task Invoke(MiddlewareContext context)
 {
     await _next(context);
 }
 internal TaskTemplateRepository(MiddlewareContext context)
     : base(context)
 {
 }
Пример #22
0
 internal ClusterRepository(MiddlewareContext context)
     : base(context)
 {
 }
 internal FileSpecificationRepository(MiddlewareContext context)
     : base(context)
 {
 }
Пример #24
0
 protected GenericRepository(MiddlewareContext context)
 {
     _context = context;
     _dbSet   = context.Set <T>();
 }
Пример #25
0
 internal OpenStackSessionRepository(MiddlewareContext context)
     : base(context)
 {
 }
Пример #26
0
 public DatabaseUnitOfWork()
 {
     _context = new MiddlewareContext();
 }
Пример #27
0
        private async Task RouteContext(IUserState userState, ControllerContext context)
        {
            var callbackQuery = context.CallbackQuery;
            var message       = context.Message;

            var middlewareContext          = new MiddlewareContext(userState, context);
            var messageHasPassedMiddleware = await ApplyMessageMiddleware(middlewareContext).ConfigureAwait(false);

            if (!messageHasPassedMiddleware)
            {
                // middleware may have changed the state and set a response
                await _stateRepository.SetUserState(context.TelegramUserId, userState).ConfigureAwait(false);
                await SendResponses(context.ChatId, middlewareContext.Response).ConfigureAwait(false);

                return;
            }

            if (callbackQuery != null && callbackQuery.IsStateless())
            {
                try
                {
                    await ExecuteStatelessListener(context).ConfigureAwait(false);
                }
                catch (Exception e)
                {
                    await _exceptionHandler.Handle(e).ConfigureAwait(false);
                }
                return;
            }


            var controllerType = _controllerNameToType[userState.OuterState];
            var method         = controllerType.GetMethod(userState.InnerState);

            if (callbackQuery != null && !method.AcceptsCallbacks())
            {
                await _logger.LogError($"{method.Name} is not marked with {nameof(AcceptCallbacksAttribute)}.").ConfigureAwait(false);

                return;
            }

            // Forward context to controllers
            bool forwardToNewState;

            do
            {
                controllerType = _controllerNameToType[userState.OuterState];
                method         = controllerType.GetMethod(userState.InnerState);

                var controller = (BaseController)_container.GetInstance(controllerType);
                controller.Context = context;
                Transition transition;
                try
                {
                    var task = (Task <Transition>)method.Invoke(controller, null);
                    transition = await task.ConfigureAwait(false);
                }
                catch (Exception e)
                {
                    await _exceptionHandler.Handle(e).ConfigureAwait(false);

                    return;
                }

                forwardToNewState = await AdvanceState(userState, transition).ConfigureAwait(false);

                await _stateRepository.SetUserState(message.From.Id, userState).ConfigureAwait(false);
                await SendResponses(message.Chat.Id, transition.Response).ConfigureAwait(false);
            } while (forwardToNewState);
        }
 internal TaskParalizationSpecificationRepository(MiddlewareContext context)
     : base(context)
 {
 }
Пример #29
0
 public void Invoke(MiddlewareContext context, Action next)
 {
     log.Info("Before " + dependency.Id);
     next();
     log.Info("After " + dependency.Id);
 }