protected virtual async ValueTask <TContext> InvokingAsync(CancellationToken cancellation)
        {
            using var scope = ServiceScopeFactory.CreateScope();

            var context = new TContext
            {
                ServiceProvider   = scope.ServiceProvider,
                CancellationToken = cancellation
            };

            await Delegate.Invoke(context);

            return(context);
        }
示例#2
0
        public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
        {
            var concurrentPipelineCount = ConcurrentPipelineCount < 1
                    ? 1 : ConcurrentPipelineCount;

            foreach (var requestAndPipeline in _requestAndPipeline)
            {
                context.Add(requestAndPipeline.Context);
            }

            var remainingItems = _requestAndPipeline
                                 .Skip(concurrentPipelineCount)
                                 .Select(x => x);

            var runningTasks = _requestAndPipeline
                               .Take(concurrentPipelineCount)
                               .Select(x => x.InvokeAsync())
                               .ToList();

            while (runningTasks.Any())
            {
                var task = await Task.WhenAny(runningTasks.ToArray());

                runningTasks.Remove(task);

                var nextTask = remainingItems.FirstOrDefault();
                if (nextTask != null)
                {
                    runningTasks.Add(nextTask.InvokeAsync());
                    remainingItems = remainingItems.Skip(1);
                }
            }

            await next.Invoke();
        }
示例#3
0
        public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
        {
            if (context.GetFirst(out HttpResponseMessage responseMessage))
            {
                if (responseMessage.IsSuccessStatusCode)
                {
                    var response = await responseMessage.Content.ReadAsStringAsync();

                    if (string.Compare("Exception:", response.Substring(0, 10), true) == 0)
                    {
                        context.AddNotification(this, response);
                        return;
                    }
                }
                else
                {
                    context.AddNotification(this, $"Unsuccessful Response: {responseMessage.StatusCode}");
                }

                await next.Invoke();
            }
            else
            {
                throw new PipelineDependencyException <HttpRequestMessage>(this);
            }
        }
示例#4
0
        public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
        {
            await next.Invoke();

            if (context.GetFirst(out HttpResponseMessage httpResponseMessage))
            {
                var code = (int)httpResponseMessage.StatusCode;
                if ((Sanitize500s && Between(code, 500, 599)) ||
                    (Sanitize400s && Between(code, 400, 499)) ||
                    (Sanitize300s && Between(code, 300, 399)) ||
                    SanitizeResponseCodes.Contains(code))
                {
                    if (SaveOriginalContent)
                    {
                        var originalResponse = new ResponseSanitizerContent();
                        originalResponse.Copy(httpResponseMessage);
                        context.Add(originalResponse);
                    }

                    HttpResponseBuilder.HttpResponseMessage(httpResponseMessage)
                    .WithNoContent()
                    .WithReasonPhrase(string.Empty)
                    .If(ReturnErrorReference,
                        resp => resp.WithStringContent($"{{\"errorReference\":\"{context.Id}\"}}"))
                    .If(ReplacementResponseCode.HasValue,
                        resp => resp.WithStatusCode(ReplacementResponseCode.Value));
                }
            }
        }
示例#5
0
        public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
        {
            context.Remove(CircuitBreakerEnum.OpenState);

            CircuitState.State currentState = CircuitState.State.Closed;
            _circuitState.Invoke(x =>
                                 currentState = x.GetState());

            var activeStates = new[] { CircuitState.State.Closed, CircuitState.State.Half_Open };

            if (activeStates.Any(x => x == currentState))
            {
                await next.Invoke();

                if (!context.GetFirst(out HttpResponseMessage httpResponseMessage))
                {
                    throw new PipelineDependencyException <HttpResponseMessage>(this);
                }

                _circuitState.Invoke(x =>
                                     x.Update(!httpResponseMessage.IsTransientFailure()));
            }
            else
            {
                context.Add(CircuitBreakerEnum.OpenState);
            }
        }
示例#6
0
        public async Task Invoke(DataModel model, PipelineDelegate <DataModel> next)
        {
            if (_providers.ContainsKey(model.Guid) && model.RadioModel.Tone)
            {
                var token   = _providers[model.Guid];
                var current = DateTime.UtcNow.TimeOfDay;
                if ((current - token.TimeStamp) > TimeDifferencePlaying)
                {
                    _mixer.RemoveMixerInput(token.Provider);

                    var updatedSample = _toneProvider.CreateSampleProvider();
                    _providers[model.Guid] = new PlayerSampleToken
                    {
                        Provider  = updatedSample,
                        TimeStamp = current
                    };

                    _mixer.AddMixerInput(updatedSample);
                }
            }
            else if (model.RadioModel.Tone)
            {
                var sample    = _toneProvider.CreateSampleProvider();
                var timeStamp = DateTime.UtcNow.TimeOfDay;
                var token     = new PlayerSampleToken
                {
                    Provider  = sample,
                    TimeStamp = timeStamp
                };
                _providers[model.Guid] = token;

                _mixer.AddMixerInput(token.Provider);
            }
            await next.Invoke(model);
        }
示例#7
0
        public async Task <PipelineContext> InvokeAsync(PipelineContext context, Action <PipelineContext> invokeAction = null)
        {
            int index = 0;
            var ctx   = context ?? new PipelineContext();

            PipelineDelegate pipelineDelegate = null;

            pipelineDelegate =
                async() =>
            {
                var nextHandler = _pipelineHandlers.Skip(index).FirstOrDefault();
                index += 1;
                if (nextHandler != null)
                {
                    await nextHandler.InvokeAsync(ctx, pipelineDelegate);
                }
            };

            try
            {
                invokeAction?.Invoke(ctx);
                await pipelineDelegate.Invoke();
            }
            catch (Exception ex)
            {
                var handler = _pipelineHandlers.Skip(index - 1).FirstOrDefault();
                ctx
                .AddNotification(handler, $"Unhandled Exception: {ex.Message}")
                .AddNotification(handler, ex.ToString());
            }

            return(ctx);
        }
示例#8
0
        public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
        {
            if (!context.GetFirst(out HttpRequestMessage httpRequestMessage))
            {
                throw new PipelineDependencyException <HttpRequestMessage>(this);
            }

            HttpClientRequest       request = new HttpClientRequest(httpRequestMessage);
            CancellationTokenSource cts     = new CancellationTokenSource(RequestTimeout);

            var cancellationTokens = context.Get <CancellationToken>();
            var token = cancellationTokens.Any()
                    ? CancellationTokenSource.CreateLinkedTokenSource(
                cancellationTokens.Concat(new[] { cts.Token }).ToArray()
                ).Token
                    : cts.Token;

            try
            {
                var result = await request.InvokeAsync(token);

                context.Add(result);
                await next.Invoke();
            }
            catch (HttpRequestException ex)
            {
                throw new PipelineException(this, ex.Message, ex);
            }
            catch (Exception ex)
            {
                throw new PipelineException(this, ex.Message, ex);
            }
        }
示例#9
0
        public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
        {
            if (_queryParameters.Any())
            {
                if (!context.GetFirst(out Uri uri))
                {
                    throw new PipelineDependencyException <Uri>(this);
                }

                var keyValuePairs = NameValueToKeyValuePairs(HttpUtility.ParseQueryString(uri.Query));
                foreach (var queryParameter in _queryParameters)
                {
                    if (context.Get(queryParameter.ContextVariableName, out string contextParameterValue) && !string.IsNullOrEmpty(contextParameterValue))
                    {
                        keyValuePairs.Add(new KeyValuePair <string, string>(queryParameter.ContextVariableName, contextParameterValue));
                    }
                    else
                    if (!queryParameter.Optional)
                    {
                        context.AddNotification(this, $"Context variable '{queryParameter.ContextVariableName}' was not found or does not contain a value and is not optional");
                        return;
                    }
                }

                var          ub = new UriBuilder(uri);
                QueryBuilder qb = new QueryBuilder(keyValuePairs);
                ub.Query = qb.ToString();
                context.AddOrReplace(ub.Uri);

                await next.Invoke();
            }
        }
示例#10
0
        public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
        {
            await next.Invoke();

            if (BeforeAdditionalBranchAction?.Invoke(context) ?? true)
            {
                await AdditionalBranch?.InvokeAsync(context);
            }
        }
示例#11
0
        public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
        {
            if (context.GetFirst(out HttpRequestMessage httpRequestMessage))
            {
                //var match = MethodsAndRoutes.FirstOrDefault(x => )
            }

            await next.Invoke();
        }
示例#12
0
        public async Task Invoke(DataModel model, PipelineDelegate <DataModel> next)
        {
            if (model.NetworkTask != null &&
                Math.Abs(model.NetworkTask.Frequency - model.RadioModel.Frequency) < 0.001)
            {
                OnDataAvailable?.Invoke(this, new DataEventArgs <NetworkTaskData>(model.NetworkTask));
            }

            await next.Invoke(model);
        }
示例#13
0
        public async Task Invoke(DataModel model, PipelineDelegate <DataModel> next)
        {
            var buffer = _buffers.GetOrAdd(model.Guid, (guid) =>
            {
                var dictionaryBuffer = new BufferedWaveProvider(_format);
                _mixer.AddMixerInput(dictionaryBuffer);
                return(dictionaryBuffer);
            });

            buffer.AddSamples(model.RawAudioSample, 0, model.RawAudioSample.Length);
            await next.Invoke(model);
        }
示例#14
0
 public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
 {
     try
     {
         BeforeNextInvokeAction?.Invoke(context);
         await next.Invoke();
     }
     finally
     {
         AfterNextInvokeAction?.Invoke(context);
     }
 }
        public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
        {
            context.Remove(FixedIntervalRetryEnum.RetryCountExceeded);

            int index = 0;
            await next.Invoke();

            while (IsTransientFailure(context))
            {
                var delay = Configuration.GetInterval(index);
                if (!delay.HasValue)
                {
                    context.Add(FixedIntervalRetryEnum.RetryCountExceeded);
                    break;
                }

                await Task.Delay(delay.Value);

                await next.Invoke();
            }
        }
示例#16
0
        public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
        {
            bool useAlternateBranch = UseAlternateBranchAction?.Invoke(context) ?? false;

            if (useAlternateBranch)
            {
                await AlternateBranch.InvokeAsync(context);
            }
            else
            {
                await next.Invoke();
            }
        }
示例#17
0
 private void Provider_OnDataAvaliable(object sender, DataEventArgs <byte[]> e)
 {
     try
     {
         var decompressed = _compressor.Decompress(e.Data);
         var model        = _converter.ConvertFrom(decompressed);
         _pipeline.Invoke(model);
     }
     catch (Exception ex)
     {
         Debug.Write($"An exception in {nameof(AudioReceiverAndPlayer)} {ex.Message}.");
     }
 }
示例#18
0
        public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
        {
            if (!context.GetFirst(out HttpContext httpContext))
            {
                throw new PipelineDependencyException <HttpContext>(this);
            }

            PipelineConverters.Convert(httpContext.Request, out HttpRequestMessage httpRequestMessage, HeadersToRemove);
            context
            .Add(httpRequestMessage)
            .Add(httpContext.RequestAborted);

            await next.Invoke();
        }
示例#19
0
        public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
        {
            if (!context.GetFirst(out HttpContext httpContext))
            {
                throw new PipelineDependencyException <HttpContext>(this);
            }

            var(result, versionNo) = GetVersionHeader(httpContext.Request.Headers);
            if (result)
            {
                context.Add(versionNo);
            }

            await next.Invoke();
        }
示例#20
0
        public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
        {
            var stopWatch = new System.Diagnostics.Stopwatch();

            try
            {
                stopWatch.Start();
                await next.Invoke();
            }
            finally
            {
                context.Add(stopWatch.Elapsed);
                stopWatch.Stop();
            }
        }
示例#21
0
        public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
        {
            if (!context.GetFirst(out HttpRequestMessage httpRequestMessage))
            {
                throw new PipelineDependencyException <HttpRequestMessage>(this);
            }

            var parameters        = HttpUtility.ParseQueryString(httpRequestMessage.RequestUri.Query);
            var paramNameAndValue = parameters.Cast <string>()
                                    .Where(key => string.Compare(key, ParamName, true) == 0)
                                    .Select(key => new { key, value = parameters[key] })
                                    .FirstOrDefault();

            var matched = false;

            switch (ParamEvaluation)
            {
            case ParamEvaluationEnum.ParamExists:
                matched = paramNameAndValue != null;
                break;

            case ParamEvaluationEnum.ParamDoesNotExist:
                matched = paramNameAndValue == null;
                break;

            case ParamEvaluationEnum.ParamValueMatches:
                matched = string.Compare(paramNameAndValue?.value, ParamValue, true) == 0;
                break;

            case ParamEvaluationEnum.ParamValueDoesNotMatch:
                matched = (paramNameAndValue != null) &&
                          string.Compare(paramNameAndValue?.value, ParamValue, true) != 0;
                break;
            }

            if (matched)
            {
                UriBuilder builder = new UriBuilder(RedirectUrl)
                {
                    Query = httpRequestMessage.RequestUri.Query
                };
                var redirectedUri = builder.Uri;
                context.Add(new Redirected(httpRequestMessage, redirectedUri));
                httpRequestMessage.RequestUri = redirectedUri;
            }

            await next.Invoke();
        }
示例#22
0
        public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
        {
            PipelineContext parallelContext = new PipelineContext();
            Task            parallelTask    = new Task(async() =>
                                                       await ParallelPipelineRequest.InvokeAsync(parallelContext));

            parallelTask.Start();

            context.Add(new ParallelPipelineInfo()
            {
                Context      = parallelContext,
                ParallelTask = parallelTask
            });

            await Task.WhenAll(new Task[] { next.Invoke(), parallelTask });
        }
示例#23
0
        public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
        {
            await next.Invoke();

            if (!context.GetFirst(out HttpContext httpContext))
            {
                throw new PipelineDependencyException <HttpContext>(this);
            }

            if (!context.GetFirst(out HttpResponseMessage httpResponseMessage))
            {
                throw new PipelineDependencyException <HttpResponseMessage>(this);
            }

            await PipelineConverters.Convert(httpResponseMessage, httpContext.Response, HeadersToRemove);
        }
示例#24
0
 public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
 {
     if (context.GetFirst(out HttpRequestMessage httpRequestMessage))
     {
         UriBuilder builder = new UriBuilder(httpRequestMessage.RequestUri)
         {
             Host = RedirectHost,
             Port = RedirectPort
         };
         var redirectUri = builder.Uri;
         context.Add(new Redirected(httpRequestMessage, builder.Uri));
         httpRequestMessage.RequestUri = redirectUri;
         
         await next.Invoke();
     }
     else
         throw new PipelineDependencyException<HttpRequestMessage>(this);
 }
示例#25
0
 public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
 {
     if (context.Get("endpoint", out string endPoint))
     {
         if (BaseUrl == null)
         {
             context.AddNotification(this, "Missing BaseUrl value");
             return;
         }
         var uri = BaseUrl.Append(endPoint);
         context.Add(uri);
         await next.Invoke();
     }
     else
     {
         context.AddNotification(this, "Missing endpoint information");
     }
 }
示例#26
0
        public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
        {
            if (context.GetFirst(out HttpResponseMessage responseMessage))
            {
                if (responseMessage.IsSuccessStatusCode)
                {
                    var result = await responseMessage.Content.ReadAsStringAsync();

                    var response = JsonConvert.DeserializeObject <DublinBikeStation>(result);
                    context.Add("response", response);
                }

                await next.Invoke();
            }
            else
            {
                throw new PipelineDependencyException <HttpResponseMessage>(this);
            }
        }
示例#27
0
        public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
        {
            if (context.GetFirst(out HttpContext httpContext) && context.GetFirst(out string versionNo))
            {
                if (!string.IsNullOrEmpty(versionNo))
                {
                    var request      = httpContext.Request;
                    var pathSegments = request.Path.Value.Split('/').ToList();
                    if ((pathSegments.Count > 2) && (string.Compare(pathSegments[1], "api", true) == 0))
                    {
                        pathSegments.Insert(2, $"v{versionNo}");
                        var route = string.Join('/', pathSegments);
                        request.Path = route;
                    }
                }
            }

            await next.Invoke();
        }
示例#28
0
        public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
        {
            var count = Interlocked.Increment(ref _activeClients);

            try
            {
                if (count <= MaxClients)
                {
                    context.Remove(RateLimiterEnum.RateLimited);
                    await next.Invoke();

                    return;
                }
                context.Add(RateLimiterEnum.RateLimited);
            }
            finally
            {
                Interlocked.Decrement(ref _activeClients);
            }
        }
示例#29
0
        public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
        {
            try
            {
                await next.Invoke();
            }
            finally
            {
                IActionResult objectResult = null;
                if (context.Get("response", out T response))
                {
                    objectResult = new ObjectResult(response)
                    {
                        StatusCode = 200
                    }
                }
                ;
                else
                {
                    objectResult = new ObjectResult(
                        new
                    {
                        context.Id,
                        notifications = context
                                        .Get <Notification>()
                                        .Select((x, i) =>
                                                new
                        {
                            id      = i + 1,
                            Handler = x.Handler.ToString(),
                            x.ErrorMessage
                        })
                    })
                    {
                        StatusCode = 500
                    };
                }

                context.Add <IActionResult>(objectResult);
            }
        }
示例#30
0
        public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
        {
            if (context.GetFirst(out IEnumerable <DublinBikeStation> response))
            {
                if (context.Get("orderBy", out string value))
                {
                    var index = orderIdentifiers
                                .Select((x, i) => new { index = i, identifer = x })
                                .Where(x => string.Compare(x.identifer, value, true) == 0)
                                .Select(x => x.index)
                                .FirstOrDefault();

                    switch (index)
                    {
                    case 1:
                        response = response.OrderBy(x => x.Name);
                        break;

                    case 2:
                        response = response.OrderByDescending(x => x.Available_bikes);
                        break;

                    case 3:
                        response = response.OrderByDescending(x => x.Available_bike_stands);
                        break;

                    case 4:
                        response = response.OrderByDescending(x => x.Last_update);
                        break;

                    default:
                        response = response.OrderBy(x => x.Number);
                        break;
                    }

                    context.AddOrReplace("response", response.Select(x => x));
                }
            }

            await next.Invoke();
        }