/// <summary>
        ///   Creates an AMQP link for use with management operations.
        /// </summary>
        ///
        /// <param name="connection">The active and opened AMQP connection to use for this link.</param>
        /// <param name="timeout">The timeout to apply when creating the link.</param>
        /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
        ///
        /// <returns>A link for use with management operations.</returns>
        ///
        protected virtual async Task <RequestResponseAmqpLink> CreateManagementLinkAsync(AmqpConnection connection,
                                                                                         TimeSpan timeout,
                                                                                         CancellationToken cancellationToken)
        {
            Argument.AssertNotDisposed(IsDisposed, nameof(AmqpConnectionScope));
            cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();

            var session   = default(AmqpSession);
            var stopWatch = ValueStopwatch.StartNew();

            try
            {
                // Create and open the AMQP session associated with the link.

                var sessionSettings = new AmqpSessionSettings {
                    Properties = new Fields()
                };
                session = connection.CreateSession(sessionSettings);

                await OpenAmqpObjectAsync(session, timeout).ConfigureAwait(false);

                cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();

                // Create and open the link.

                var linkSettings = new AmqpLinkSettings();
                linkSettings.AddProperty(AmqpProperty.Timeout, (uint)timeout.CalculateRemaining(stopWatch.GetElapsedTime()).TotalMilliseconds);

                var link = new RequestResponseAmqpLink(AmqpManagement.LinkType, session, AmqpManagement.Address, linkSettings.Properties);

                // Track the link before returning it, so that it can be managed with the scope.

                BeginTrackingLinkAsActive(link);
                return(link);
            }
            catch
            {
                // Aborting the session will perform any necessary cleanup of
                // the associated link as well.

                session?.Abort();
                throw;
            }
        }
Example #2
0
        private async Task InvokeActionMethodAsync()
        {
            var controllerContext    = _controllerContext;
            var objectMethodExecutor = _cacheEntry.ObjectMethodExecutor;
            var controller           = _instance;
            var arguments            = _arguments;
            var actionMethodExecutor = _cacheEntry.ActionMethodExecutor;
            var orderedArguments     = PrepareArguments(arguments, objectMethodExecutor);

            var diagnosticSource = _diagnosticSource;
            var logger           = _logger;

            IActionResult result = null;

            try
            {
                diagnosticSource.BeforeActionMethod(
                    controllerContext,
                    arguments,
                    controller);
                logger.ActionMethodExecuting(controllerContext, orderedArguments);
                var stopwatch             = ValueStopwatch.StartNew();
                var actionResultValueTask = actionMethodExecutor.Execute(_mapper, objectMethodExecutor, controller, orderedArguments);
                if (actionResultValueTask.IsCompletedSuccessfully)
                {
                    result = actionResultValueTask.Result;
                }
                else
                {
                    result = await actionResultValueTask;
                }

                _result = result;
                logger.ActionMethodExecuted(controllerContext, result, stopwatch.GetElapsedTime());
            }
            finally
            {
                diagnosticSource.AfterActionMethod(
                    controllerContext,
                    arguments,
                    controllerContext,
                    result);
            }
        }
        public async Task ClassifyTestAsync(CancellationToken cancellationToken)
        {
            foreach (var modelBuilder in _modelBuilders)
            {
                var sw = ValueStopwatch.StartNew();
                Log.StartProcess(_logger, nameof(ClassifyTestAsync), modelBuilder.ModelName);

                var engineOptions = _engineOptionsMonitor.Get(modelBuilder.ModelName);

                if (engineOptions.ClassifyTestConfigurator != null)
                {
                    await engineOptions.ClassifyTestConfigurator(modelBuilder, _logger, cancellationToken);
                }

                Log.EndProcess(_logger, nameof(ClassifyTestAsync), modelBuilder.ModelName, sw.GetElapsedTime());
            }

            await Task.CompletedTask;
        }
Example #4
0
        public override async Task ClassifyTestAsync(CancellationToken cancellationToken)
        {
            // 5. predict on sample data
            _logger.LogInformation("[ClassifyTestAsync][Started]");

            var sw = ValueStopwatch.StartNew();

            var predictor = _modelBuilder.MLContext.Model.CreatePredictionEngine <SentimentIssue, SentimentPrediction>(_modelBuilder.Model);

            var tasks = new List <Task>
            {
                ClassifyAsync(predictor, "This is a very rude movie", false, cancellationToken),
                ClassifyAsync(predictor, "Hate All Of You're Work", true, cancellationToken)
            };

            await Task.WhenAll(tasks);

            _logger.LogInformation("[ClassifyTestAsync][Ended] elapsed time: {elapsed} ms", sw.GetElapsedTime().TotalMilliseconds);
        }
Example #5
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var stopWatch = ValueStopwatch.StartNew();

            HttpResponseMessage?response = null;

            try
            {
                // We measure until SendAsync returns - which is when the response HEADERS are seen.
                // The response body may continue streaming for a long time afterwards, which this does not measure.
                response = await base.SendAsync(request, cancellationToken);

                return(response);
            }
            finally
            {
                CreateChild(request, response).Observe(stopWatch.GetElapsedTime().TotalSeconds);
            }
        }
Example #6
0
        public async Task <IEnumerable <ReplicaWrapper> > GetReplicaListAsync(Guid partitionId, TimeSpan timeout, CancellationToken cancellationToken)
        {
            var replicaList = new List <ReplicaWrapper>();
            ServiceReplicaList previousResult = null;

            // Set up the counter that record the time lapse.
            var stopWatch = ValueStopwatch.StartNew();

            do
            {
                cancellationToken.ThrowIfCancellationRequested();
                var remaining = timeout - stopWatch.Elapsed;
                if (remaining.Ticks < 0)
                {
                    // If the passing time is longer than the timeout duration.
                    throw new TimeoutException($"Unable to enumerate all replicas pages in the allotted time budget of {timeout.TotalSeconds} seconds");
                }

                previousResult = await ExceptionsHelper.TranslateCancellations(
                    () => _queryClient.GetReplicaListAsync(
                        partitionId: partitionId,
                        continuationToken: previousResult?.ContinuationToken,
                        timeout: remaining,
                        cancellationToken: cancellationToken),
                    cancellationToken);

                foreach (var replica in previousResult)
                {
                    replicaList.Add(
                        new ReplicaWrapper
                    {
                        Id             = replica.Id,
                        ReplicaAddress = replica.ReplicaAddress,
                        ReplicaStatus  = replica.ReplicaStatus,
                        HealthState    = replica.HealthState,
                        ServiceKind    = replica.ServiceKind,
                        Role           = replica.ServiceKind == ServiceKind.Stateful ? ((StatefulServiceReplica)replica).ReplicaRole : (ReplicaRole?)null,
                    });
                }
            }while (!string.IsNullOrEmpty(previousResult?.ContinuationToken));

            return(replicaList);
        }
Example #7
0
        public virtual async Task OnStart(CancellationToken ct)
        {
            if (this.highStage.HasValue)
            {
                throw new InvalidOperationException("Lifecycle has already been started.");
            }
            try
            {
                foreach (IGrouping <int, OrderedObserver> observerGroup in this.subscribers
                         .GroupBy(orderedObserver => orderedObserver.Stage)
                         .OrderBy(group => group.Key))
                {
                    if (ct.IsCancellationRequested)
                    {
                        throw new OrleansLifecycleCanceledException("Lifecycle start canceled by request");
                    }

                    var stage = observerGroup.Key;
                    this.highStage = stage;
                    var stopWatch = ValueStopwatch.StartNew();
                    await Task.WhenAll(observerGroup.Select(orderedObserver => CallOnStart(observerGroup.Key, orderedObserver, ct)));

                    stopWatch.Stop();
                    this.PerfMeasureOnStart(stage, stopWatch.Elapsed);

                    this.OnStartStageCompleted(stage);
                }
            }
            catch (Exception ex) when(!(ex is OrleansLifecycleCanceledException))
            {
                this.logger?.LogError(
                    (int)ErrorCode.LifecycleStartFailure,
                    "Lifecycle start canceled due to errors at stage {Stage}: {Exception}",
                    this.highStage,
                    ex);
                throw;
            }

            async Task CallOnStart(int stage, OrderedObserver observer, CancellationToken cancellationToken)
            {
                await observer.Observer.OnStart(cancellationToken);
            }
        }
        protected async override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var stopwatch = ValueStopwatch.StartNew();

            using (Log.BeginRequestPipelineScope(_logger, request))
            {
                Log.RequestPipelineStart(_logger, request);
                var response = await base.SendAsync(request, cancellationToken);

                Log.RequestPipelineEnd(_logger, response, stopwatch.GetElapsedTime());

                return(response);
            }
        }
Example #9
0
        /// <inheritdoc />
        /// <remarks>Loggs the request to and response from the sent <see cref="HttpRequestMessage"/>.</remarks>
        protected async override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            Func <string, bool> shouldRedactHeaderValue = _options?.ShouldRedactHeaderValue ?? _shouldNotRedactHeaderValue;

            // Not using a scope here because we always expect this to be at the end of the pipeline, thus there's
            // not really anything to surround.
            Log.RequestStart(_logger, request, shouldRedactHeaderValue);
            var stopwatch = ValueStopwatch.StartNew();
            HttpResponseMessage response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);

            Log.RequestEnd(_logger, response, stopwatch.GetElapsedTime(), shouldRedactHeaderValue);

            return(response);
        }
            public static StoppableDelayRealtimePromise Create(TimeSpan delayTimeSpan, PlayerLoopTiming timing, CancellationToken cancellationToken, out short token)
            {
                if (!pool.TryPop(out var result))
                {
                    result = new StoppableDelayRealtimePromise();
                }

                result.stopwatch          = ValueStopwatch.StartNew();
                result.delayTimeSpanTicks = delayTimeSpan.Ticks;
                result.cancellationToken  = cancellationToken;
                result.externalStop       = false;

                TaskTracker.TrackActiveTask(result, 3);

                PlayerLoopHelper.AddAction(timing, result);

                token = result.core.Version;
                return(result);
            }
Example #11
0
        /// <summary>
        ///   Receives a batch of <see cref="EventData" /> from the Event Hub partition.
        /// </summary>
        ///
        /// <param name="maximumEventCount">The maximum number of messages to receive in this batch.</param>
        /// <param name="maximumWaitTime">The maximum amount of time to wait for events to become available, if no events can be read from the prefetch queue.  If not specified, the per-try timeout specified by the retry policy will be used.</param>
        /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
        ///
        /// <returns>The batch of <see cref="EventData" /> from the Event Hub partition this consumer is associated with.  If no events are present, an empty set is returned.</returns>
        ///
        /// <remarks>
        ///   When events are available in the prefetch queue, they will be used to form the batch as quickly as possible without waiting for additional events from the
        ///   Event Hubs service to try and meet the requested <paramref name="maximumEventCount" />.  When no events are available in prefetch, the receiver will wait up
        ///   to the <paramref name="maximumWaitTime"/> for events to be read from the service.  Once any events are available, they will be used to form the batch immediately.
        /// </remarks>
        ///
        public override async Task <IReadOnlyList <EventData> > ReceiveAsync(int maximumEventCount,
                                                                             TimeSpan?maximumWaitTime,
                                                                             CancellationToken cancellationToken)
        {
            Argument.AssertNotClosed(_closed, nameof(AmqpConsumer));
            Argument.AssertAtLeast(maximumEventCount, 1, nameof(maximumEventCount));

            var receivedEventCount = 0;
            var failedAttemptCount = 0;
            var tryTimeout         = RetryPolicy.CalculateTryTimeout(0);
            var waitTime           = (maximumWaitTime ?? tryTimeout);
            var operationId        = Guid.NewGuid().ToString("D", CultureInfo.InvariantCulture);
            var link              = default(ReceivingAmqpLink);
            var retryDelay        = default(TimeSpan?);
            var receivedEvents    = default(List <EventData>);
            var lastReceivedEvent = default(EventData);

            var stopWatch = ValueStopwatch.StartNew();

            try
            {
                while ((!cancellationToken.IsCancellationRequested) && (!_closed))
                {
                    try
                    {
                        // Creation of the link happens without explicit knowledge of the cancellation token
                        // used for this operation; validate the token state before attempting link creation and
                        // again after the operation completes to provide best efforts in respecting it.

                        EventHubsEventSource.Log.EventReceiveStart(EventHubName, ConsumerGroup, PartitionId, operationId);
                        cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();

                        link = await ReceiveLink.GetOrCreateAsync(UseMinimum(ConnectionScope.SessionTimeout, tryTimeout)).ConfigureAwait(false);

                        cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();

                        var messagesReceived = await Task.Factory.FromAsync <(ReceivingAmqpLink, int, TimeSpan), IEnumerable <AmqpMessage> >
                                               (
                            static (arguments, callback, state) =>
                        {
                            var(link, maximumEventCount, waitTime) = arguments;
                            return(link.BeginReceiveMessages(maximumEventCount, waitTime, callback, link));
                        },
        internal DiskManager(EngineSettings settings, Factories factories, IPieceWriter?writer = null)
        {
            ReadLimiter = new RateLimiter();
            ReadQueue   = new Queue <BufferedIO> ();

            WriteLimiter = new RateLimiter();
            WriteQueue   = new Queue <BufferedIO> ();

            UpdateTimer = ValueStopwatch.StartNew();

            Factories = factories ?? throw new ArgumentNullException(nameof(factories));
            Settings  = settings ?? throw new ArgumentNullException(nameof(settings));

            writer ??= factories.CreatePieceWriter(settings.MaximumOpenFiles);
            Cache = factories.CreateBlockCache(writer, settings.DiskCacheBytes, BufferPool);
            Cache.ReadThroughCache    += (o, e) => WriterReadMonitor.AddDelta(e.RequestLength);
            Cache.WrittenThroughCache += (o, e) => WriterWriteMonitor.AddDelta(e.RequestLength);
            IncrementalHashCache       = new Cache <IncrementalHashData> (() => new IncrementalHashData());
        }
Example #13
0
        private async Task <IViewComponentResult> InvokeAsyncCore(ObjectMethodExecutor executor, ViewComponentContext context)
        {
            var component = _viewComponentFactory.CreateViewComponent(context);

            using (_logger.ViewComponentScope(context))
            {
                var arguments = PrepareArguments(context.Arguments, executor);

                _diagnosticSource.BeforeViewComponent(context, component);
                _logger.ViewComponentExecuting(context, arguments);

                var stopwatch = ValueStopwatch.StartNew();

                object resultAsObject;
                var    returnType = executor.MethodReturnType;

                if (returnType == typeof(Task <IViewComponentResult>))
                {
                    resultAsObject = await(Task <IViewComponentResult>) executor.Execute(component, arguments);
                }
                else if (returnType == typeof(Task <string>))
                {
                    resultAsObject = await(Task <string>) executor.Execute(component, arguments);
                }
                else if (returnType == typeof(Task <IHtmlContent>))
                {
                    resultAsObject = await(Task <IHtmlContent>) executor.Execute(component, arguments);
                }
                else
                {
                    resultAsObject = await executor.ExecuteAsync(component, arguments);
                }

                var viewComponentResult = CoerceToViewComponentResult(resultAsObject);
                _logger.ViewComponentExecuted(context, stopwatch.GetElapsedTime(), viewComponentResult);
                _diagnosticSource.AfterViewComponent(context, viewComponentResult, component);

                _viewComponentFactory.ReleaseViewComponent(context, component);

                return(viewComponentResult);
            }
        }
Example #14
0
        /// <summary>
        /// Gets the details for all services of an application or just the specified service. If the services do not fit in a page, one
        /// page of results is returned as well as a continuation token which can be used to get the next page. Let serviceNameFilter to be null because we are getting all ServiceName.
        /// </summary>
        public async Task <IEnumerable <ServiceWrapper> > GetServiceListAsync(Uri applicationName, TimeSpan timeout, CancellationToken cancellationToken)
        {
            var         serviceList    = new List <ServiceWrapper>();
            ServiceList previousResult = null;

            // Set up the counter that record the time lapse.
            var stopWatch = ValueStopwatch.StartNew();

            do
            {
                cancellationToken.ThrowIfCancellationRequested();
                var remaining = timeout - stopWatch.Elapsed;
                if (remaining.Ticks < 0)
                {
                    // If the passing time is longer than the timeout duration.
                    throw new TimeoutException($"Unable to enumerate all service pages in the allotted time budget of {timeout.TotalSeconds} seconds");
                }

                previousResult = await ExceptionsHelper.TranslateCancellations(
                    () => _queryClient.GetServiceListAsync(
                        applicationName: applicationName,
                        serviceNameFilter: null,
                        continuationToken: previousResult?.ContinuationToken,
                        timeout: remaining,
                        cancellationToken: cancellationToken),
                    cancellationToken);

                foreach (var service in previousResult)
                {
                    serviceList.Add(
                        new ServiceWrapper
                    {
                        ServiceName            = service.ServiceName,
                        ServiceTypeName        = service.ServiceTypeName,
                        ServiceManifestVersion = service.ServiceManifestVersion,
                        ServiceKind            = service.ServiceKind,
                    });
                }
            }while (!string.IsNullOrEmpty(previousResult?.ContinuationToken));

            return(serviceList);
        }
Example #15
0
        public virtual async Task <(string Dump, RuleResult Result, TimeSpan Elapsed)> InvokeAsync(string actionName, string job)
        {
            try
            {
                var actionType  = typeNameRegistry.GetType(actionName);
                var actionWatch = ValueStopwatch.StartNew();

                var actionHandler = ruleActionHandlers[actionType];

                var deserialized = jsonSerializer.Deserialize <object>(job, actionHandler.DataType);

                var result = await actionHandler.ExecuteJobAsync(deserialized);

                var elapsed = TimeSpan.FromMilliseconds(actionWatch.Stop());

                var dumpBuilder = new StringBuilder(result.Dump);

                dumpBuilder.AppendLine();
                dumpBuilder.AppendFormat("Elapsed {0}.", elapsed);
                dumpBuilder.AppendLine();

                if (result.Exception is TimeoutException || result.Exception is OperationCanceledException)
                {
                    dumpBuilder.AppendLine();
                    dumpBuilder.AppendLine("Action timed out.");

                    return(dumpBuilder.ToString(), RuleResult.Timeout, elapsed);
                }
                else if (result.Exception != null)
                {
                    return(dumpBuilder.ToString(), RuleResult.Failed, elapsed);
                }
                else
                {
                    return(dumpBuilder.ToString(), RuleResult.Success, elapsed);
                }
            }
            catch (Exception ex)
            {
                return(ex.ToString(), RuleResult.Failed, TimeSpan.Zero);
            }
        }
Example #16
0
        public override async Task <HealthReport> CheckHealthAsync(
            Func <HealthCheckRegistration, bool> predicate,
            CancellationToken cancellationToken = default)
        {
            var registrations = _options.Value.Registrations;

            if (predicate != null)
            {
                registrations = registrations.Where(predicate).ToArray();
            }

            var totalTime = ValueStopwatch.StartNew();

            Log.HealthCheckProcessingBegin(_logger);

            var tasks = new Task <HealthReportEntry> [registrations.Count];
            var index = 0;

            using (var scope = _scopeFactory.CreateScope())
            {
                foreach (var registration in registrations)
                {
                    tasks[index++] = Task.Run(() => RunCheckAsync(scope, registration, cancellationToken), cancellationToken);
                }

                await Task.WhenAll(tasks).ConfigureAwait(false);
            }

            index = 0;
            var entries = new Dictionary <string, HealthReportEntry>(StringComparer.OrdinalIgnoreCase);

            foreach (var registration in registrations)
            {
                entries[registration.Name] = tasks[index++].Result;
            }

            var totalElapsedTime = totalTime.GetElapsedTime();
            var report           = new HealthReport(entries, totalElapsedTime);

            Log.HealthCheckProcessingEnd(_logger, report.Status, totalElapsedTime);
            return(report);
        }
Example #17
0
        async Task ScrapeTier(TrackerTier tier)
        {
            for (int i = 0; i < tier.Trackers.Count; i++)
            {
                int trackerIndex = (i + tier.ActiveTrackerIndex) % tier.Trackers.Count;
                var tracker      = tier.Trackers[trackerIndex];

                tier.LastScrape = ValueStopwatch.StartNew();
                if (tracker.CanScrape)
                {
                    await Scrape(tracker);
                }

                if (tier.LastScrapSucceeded)
                {
                    break;
                }
            }
            // All trackers failed to respond.
        }
Example #18
0
 public SiloHealthMonitor(
     SiloAddress siloAddress,
     Func <SiloHealthMonitor, ProbeResult, Task> onProbeResult,
     IOptions <ClusterMembershipOptions> clusterMembershipOptions,
     ILoggerFactory loggerFactory,
     IRemoteSiloProber remoteSiloProber,
     IAsyncTimerFactory asyncTimerFactory,
     ILocalSiloHealthMonitor localSiloHealthMonitor)
 {
     SiloAddress = siloAddress;
     _clusterMembershipOptions = clusterMembershipOptions.Value;
     _prober = remoteSiloProber;
     _localSiloHealthMonitor = localSiloHealthMonitor;
     _log       = loggerFactory.CreateLogger <SiloHealthMonitor>();
     _pingTimer = asyncTimerFactory.Create(
         _clusterMembershipOptions.ProbeTimeout,
         nameof(SiloHealthMonitor));
     _onProbeResult = onProbeResult;
     _elapsedSinceLastSuccessfulResponse = ValueStopwatch.StartNew();
 }
        /// <summary>
        ///   Opens an AMQP link for use with management operations.
        /// </summary>
        ///
        /// <param name="timeout">The timeout to apply when creating the link.</param>
        /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
        ///
        /// <returns>A link for use with management operations.</returns>
        ///
        /// <remarks>
        ///   The authorization for this link does not require periodic
        ///   refreshing.
        /// </remarks>
        ///
        public virtual async Task <RequestResponseAmqpLink> OpenManagementLinkAsync(TimeSpan timeout,
                                                                                    CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();

            var stopWatch  = ValueStopwatch.StartNew();
            var connection = await ActiveConnection.GetOrCreateAsync(timeout).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();

            var link = await CreateManagementLinkAsync(connection, timeout.CalculateRemaining(stopWatch.GetElapsedTime()), cancellationToken).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();

            await OpenAmqpObjectAsync(link, timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();

            return(link);
        }
Example #20
0
        public static IDisposable Trace(string key)
        {
            Guard.NotNull(key, nameof(key));

            var session = LocalSession.Value;

            if (session == null)
            {
                return(NoopDisposable.Instance);
            }

            var watch = ValueStopwatch.StartNew();

            return(new DelegateDisposable(() =>
            {
                var elapsedMs = watch.Stop();

                session.Measured(key, elapsedMs);
            }));
        }
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var stopwatch = ValueStopwatch.StartNew();
            var trackId   = Guid.NewGuid().ToString("N");

            request.Headers.TryAddWithoutValidation(WebApiClientConsts.HttpTrackIdHeadName, trackId);

            var response = await base.SendAsync(request, cancellationToken);

            response.Headers.TryAddWithoutValidation(WebApiClientConsts.HttpTrackIdHeadName, trackId);

            if (_auditingHelper.IsEnableHttpCallingAuditing())
            {
                var auditingInfo = await _auditingHelper.CreateAuditingInfo(trackId, request, stopwatch.GetElapsedTime().TotalMilliseconds, response.StatusCode, response);

                await _auditingHelper.SaveAsync(auditingInfo);
            }

            return(response);
        }
Example #22
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            context.HttpContext.Features.Set <IApiCostsFeature>(FilterDefinition);

            var appFeature = context.HttpContext.Features.Get <IAppFeature>();

            if (appFeature?.App != null && FilterDefinition.Weight > 0)
            {
                var appId = appFeature.App.Id.ToString();

                using (Profiler.Trace("CheckUsage"))
                {
                    var plan = appPlansProvider.GetPlanForApp(appFeature.App);

                    var usage = await usageTracker.GetMonthlyCallsAsync(appId, DateTime.Today);

                    if (plan.MaxApiCalls >= 0 && usage > plan.MaxApiCalls * 1.1)
                    {
                        context.Result = new StatusCodeResult(429);
                        return;
                    }
                }

                var watch = ValueStopwatch.StartNew();

                try
                {
                    await next();
                }
                finally
                {
                    var elapsedMs = watch.Stop();

                    await usageTracker.TrackAsync(appId, context.HttpContext.User.OpenIdClientId(), FilterDefinition.Weight, elapsedMs);
                }
            }
            else
            {
                await next();
            }
        }
        /// <inheritdoc />
        /// <remarks>Loggs the request to and response from the sent <see cref="HttpRequestMessage"/>.</remarks>
        protected async override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var stopwatch = ValueStopwatch.StartNew();

            Func <string, bool> shouldRedactHeaderValue = _options?.ShouldRedactHeaderValue ?? _shouldNotRedactHeaderValue;

            using (Log.BeginRequestPipelineScope(_logger, request))
            {
                Log.RequestPipelineStart(_logger, request, shouldRedactHeaderValue);
                HttpResponseMessage response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);

                Log.RequestPipelineEnd(_logger, response, stopwatch.GetElapsedTime(), shouldRedactHeaderValue);

                return(response);
            }
        }
Example #24
0
        async Task SendMessages()
        {
            for (int i = 0; i < 5 && SendQueue.Count > 0; i++)
            {
                SendDetails details = SendQueue.Dequeue();

                details.SentAt = ValueStopwatch.StartNew();
                if (details.Message is QueryMessage)
                {
                    WaitingResponse.Add(details.Message.TransactionId, details);
                }

                byte[] buffer = details.Message.Encode();
                try {
                    Monitor.SendMonitor.AddDelta(buffer.Length);
                    await Listener.SendAsync(buffer, details.Destination);
                } catch {
                    TimeoutMessage(details);
                }
            }
        }
Example #25
0
    private IViewComponentResult InvokeSyncCore(ObjectMethodExecutor executor, object component, ViewComponentContext context)
    {
        using (Log.ViewComponentScope(_logger, context))
        {
            var arguments = PrepareArguments(context.Arguments, executor);

            _diagnosticListener.BeforeViewComponent(context, component);
            Log.ViewComponentExecuting(_logger, context, arguments);

            var    stopwatch = ValueStopwatch.StartNew();
            object?result;

            result = executor.Execute(component, arguments);

            var viewComponentResult = CoerceToViewComponentResult(result);
            Log.ViewComponentExecuted(_logger, context, stopwatch.GetElapsedTime(), viewComponentResult);
            _diagnosticListener.AfterViewComponent(context, viewComponentResult, component);

            return(viewComponentResult);
        }
    }
        public override async Task ClassifyTestAsync(CancellationToken cancellationToken)
        {
            // 5. predict on sample data
            _logger.LogInformation("[ClassifyTestAsync][Started]");

            var sw = ValueStopwatch.StartNew();

            var predictor = _modelBuilder.MLContext.Model.CreatePredictionEngine <SpamInput, SpamPrediction>(_modelBuilder.Model);

            var tasks = new List <Task>
            {
                ClassifyAsync(predictor, "That's a great idea. It should work.", "ham", cancellationToken),
                ClassifyAsync(predictor, "free medicine winner! congratulations", "spam", cancellationToken),
                ClassifyAsync(predictor, "Yes we should meet over the weekend!", "ham", cancellationToken),
                ClassifyAsync(predictor, "you win pills and free entry vouchers", "spam", cancellationToken)
            };

            await Task.WhenAll(tasks);

            _logger.LogInformation("[ClassifyTestAsync][Ended] elapsed time: {elapsed} ms", sw.GetElapsedTime().TotalMilliseconds);
        }
        /// <summary>
        ///   Opens an AMQP link for use with consumer operations.
        /// </summary>
        ///
        /// <param name="consumerGroup">The name of the consumer group in the context of which events should be received.</param>
        /// <param name="partitionId">The identifier of the Event Hub partition from which events should be received.</param>
        /// <param name="eventPosition">The position of the event in the partition where the link should be filtered to.</param>
        /// <param name="prefetchCount">Controls the number of events received and queued locally without regard to whether an operation was requested.</param>
        /// <param name="ownerLevel">The relative priority to associate with the link; for a non-exclusive link, this value should be <c>null</c>.</param>
        /// <param name="trackLastEnqueuedEventProperties">Indicates whether information on the last enqueued event on the partition is sent as events are received.</param>
        /// <param name="timeout">The timeout to apply when creating the link.</param>
        /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
        ///
        /// <returns>A link for use with consumer operations.</returns>
        ///
        public virtual async Task <ReceivingAmqpLink> OpenConsumerLinkAsync(string consumerGroup,
                                                                            string partitionId,
                                                                            EventPosition eventPosition,
                                                                            TimeSpan timeout,
                                                                            uint prefetchCount,
                                                                            long?ownerLevel,
                                                                            bool trackLastEnqueuedEventProperties,
                                                                            CancellationToken cancellationToken)
        {
            Argument.AssertNotNullOrEmpty(consumerGroup, nameof(consumerGroup));
            Argument.AssertNotNullOrEmpty(partitionId, nameof(partitionId));

            cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();

            var stopWatch        = ValueStopwatch.StartNew();
            var consumerEndpoint = new Uri(ServiceEndpoint, string.Format(CultureInfo.InvariantCulture, ConsumerPathSuffixMask, EventHubName, consumerGroup, partitionId));

            var connection = await ActiveConnection.GetOrCreateAsync(timeout).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();

            var link = await CreateReceivingLinkAsync(
                connection,
                consumerEndpoint,
                eventPosition,
                timeout.CalculateRemaining(stopWatch.GetElapsedTime()),
                prefetchCount,
                ownerLevel,
                trackLastEnqueuedEventProperties,
                cancellationToken
                ).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();

            await OpenAmqpObjectAsync(link, timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();

            return(link);
        }
Example #28
0
        public virtual async Task InvokeAsync()
        {
            try
            {
                _diagnosticSource.BeforeAction(
                    _actionContext.ActionDescriptor,
                    _actionContext.HttpContext,
                    _actionContext.RouteData);

                using (_logger.ActionScope(_actionContext.ActionDescriptor))
                {
                    _logger.ExecutingAction(_actionContext.ActionDescriptor);

                    _logger.AuthorizationFiltersExecutionPlan(_filters);
                    _logger.ResourceFiltersExecutionPlan(_filters);
                    _logger.ActionFiltersExecutionPlan(_filters);
                    _logger.ExceptionFiltersExecutionPlan(_filters);
                    _logger.ResultFiltersExecutionPlan(_filters);

                    var stopwatch = ValueStopwatch.StartNew();

                    try
                    {
                        await InvokeFilterPipelineAsync();
                    }
                    finally
                    {
                        ReleaseResources();
                        _logger.ExecutedAction(_actionContext.ActionDescriptor, stopwatch.GetElapsedTime());
                    }
                }
            }
            finally
            {
                _diagnosticSource.AfterAction(
                    _actionContext.ActionDescriptor,
                    _actionContext.HttpContext,
                    _actionContext.RouteData);
            }
        }
Example #29
0
        /// <inheritdoc />
        /// <remarks>Loggs the request to and response from the sent <see cref="HttpRequestMessage"/>.</remarks>
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            ThrowHelper.ThrowIfNull(request);
            return(Core(request, cancellationToken));

            async Task <HttpResponseMessage> Core(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                var stopwatch = ValueStopwatch.StartNew();

                Func <string, bool> shouldRedactHeaderValue = _options?.ShouldRedactHeaderValue ?? _shouldNotRedactHeaderValue;

                using (Log.BeginRequestPipelineScope(_logger, request))
                {
                    Log.RequestPipelineStart(_logger, request, shouldRedactHeaderValue);
                    HttpResponseMessage response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);

                    Log.RequestPipelineEnd(_logger, response, stopwatch.GetElapsedTime(), shouldRedactHeaderValue);

                    return(response);
                }
            }
        }
Example #30
0
        private async Task <UserIterationResult> ExecuteTest(ILoadTest nextTest, IUserLoadTestHttpClient userLoadClient, Func <TimeSpan> getCurrentTimeSpan)
        {
            var userTime    = ValueStopwatch.StartNew();
            var startedTime = getCurrentTimeSpan();

            Exception exception = null;

            try
            {
                await nextTest.Execute(userLoadClient);
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            var elapsedTime = userTime.GetElapsedTime();

            var statusResults = userLoadClient.StatusResults();

            return(new UserIterationResult(_httpUser.BaseUrl, UserNumber, elapsedTime, Iteration, nextTest.Name, statusResults, startedTime, userLoadClient.UserDelay, exception?.ToString()));
        }