Beispiel #1
0
        public async Task Invoke(HttpContext context, IBeatPulseService pulseService)
        {
            var request = context.Request;

            if (!IsBeatPulseRequest(request, out string beatPulsePath))
            {
                await _next.Invoke(context);

                return;
            }
            else
            {
                if (TryFromCache(beatPulsePath, out OutputMessage output))
                {
                    await WriteResponseAsync(request.HttpContext, output, _options.DetailedOutput);
                }
                else
                {
                    output = new OutputMessage();

                    using (var cancellationTokenSource = new CancellationTokenSource())
                    {
                        var task = pulseService.IsHealthy(beatPulsePath, context, cancellationTokenSource.Token);

                        if (await Task.WhenAny(task, Task.Delay(_options.Timeout, cancellationTokenSource.Token)) == task)
                        {
                            var responses = await task;

                            if (!responses.Any())
                            {
                                await WriteNotFoundAsync(request.HttpContext, _options.DetailedOutput);

                                return;
                            }

                            output.AddHealthCheckMessages(responses);
                            output.EndAtUtc = DateTime.UtcNow;

                            if (_options.CacheMode.UseServerMemory() && _options.CacheOutput)
                            {
                                _cache.TryAdd(beatPulsePath, output);
                            }

                            await WriteResponseAsync(request.HttpContext, output, _options.DetailedOutput);
                        }
                        else
                        {
                            //timeout
                            _cache.TryRemove(beatPulsePath, out OutputMessage removed);

                            cancellationTokenSource.Cancel();

                            await WriteTimeoutAsync(request.HttpContext, _options.DetailedOutput);
                        }
                    }
                }
            }
        }