/// <inheritdoc /> public async Task Invoke(RequestMessage request, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); Bucket?bucket = null; try { bucket = await bucketService.GetBucketAndWaitForAvailability(request.RequestDetails, cancellationToken); var httpRequest = new HttpRequestMessage { RequestUri = urlBuilder.BuildFromRequest(request.RequestDetails), Method = request.RequestDetails.Endpoint.GetMethod(), Content = CreateContent(request), }; logger.LogInformation("Sending request uri:{@uri} method:{@method} body:{@body}", httpRequest.RequestUri, httpRequest.Method, httpRequest.Content); var httpResponse = await client.SendAsync(httpRequest, cancellationToken); var responseString = await httpResponse.Content.ReadAsStringAsync(cancellationToken); _ = relay.Respond(request, httpResponse.StatusCode, responseString, cancellationToken); _ = relay.Complete(request, httpResponse.StatusCode, responseString, cancellationToken); logger.LogInformation("Received response from {@uri}: {@response}", httpRequest.RequestUri, responseString); bucket = await bucketService.MergeBucketIds(bucket, httpResponse, cancellationToken); bucketService.UpdateBucketHitsRemaining(bucket, httpResponse); bucketService.UpdateBucketResetAfter(bucket, httpResponse); if (httpResponse.StatusCode == HttpStatusCode.TooManyRequests) { // throw exception here _ = reporter.Report(default(RestApiRateLimitedMetric), cancellationToken); } } catch (Exception exception) { logger.LogError("Error occurred while attempting to invoke request: {@exception}", exception); _ = relay.Fail(request, 0, cancellationToken); _ = reporter.Report(default(RestApiFailedMessageMetric), cancellationToken); } if (bucket != null) { await bucketRepository.Save(bucket, cancellationToken); } }
private List <string> GetAvailableRecordIdentifiers(ESSearchResponse esResponse) { IEnumerable <IGrouping <string, string> > groupedTypes = esResponse.SearchResult.Hits.GroupBy(x => x.Type, x => x.Id); List <string> availableRecordIdentifiers = new List <string>(); Stopwatch sw = new Stopwatch(); sw.Start(); foreach (var groupedType in groupedTypes) { var condition = PrepareRightsCondition(esResponse, groupedType.Key, groupedType.ToList()); if (_userConnection.EntitySchemaManager.FindInstanceByName(condition.Key) == null || condition.Value.Count == 0) { _log.InfoFormat("Instance of entity with name {0} was not found while checking record permisiions.", condition.Key); continue; } var esq = new EntitySchemaQuery(_userConnection.EntitySchemaManager, condition.Key); esq.PrimaryQueryColumn.IsAlwaysSelect = true; foreach (string column in _userConnection.DBSecurityEngine.GetSchemaSignificantColumns(condition.Key)) { if (esq.RootSchema.Columns.FindByName(column) != null) { esq.AddColumn(column); } } esq.Filters.Add(esq.CreateFilterWithParameters(FilterComparisonType.Equal, esq.PrimaryQueryColumn.Name, condition.Value)); EntityCollection collection = esq.GetEntityCollection(_userConnection); AppendAvailableRecordIds(availableRecordIdentifiers, collection, groupedType.Key, esResponse); } sw.Stop(); _metricReporter.Report(new SearchMetric { Duration = sw.ElapsedMilliseconds, Source = SearchSource.Bpm }); return(availableRecordIdentifiers); }
private void RollingHeartBeat() { while (SYSTEM_STOP != SystemStatus) { HeartBeatProcessor(); metricReporter.Report(MetricCollections.Default).Wait(); Random random = new Random(DateTime.Now.Millisecond); Thread.Sleep(random.Next(1000, 1500)); } }
/// <inheritdoc /> public async Task Handle(ResumedEvent @event, CancellationToken cancellationToken) { await Task.CompletedTask; using var scope = logger.BeginScope("{@Event}", nameof(ResumedEvent)); cancellationToken.ThrowIfCancellationRequested(); _ = reporter.Report(default(ResumedEventMetric), cancellationToken); gateway.IsReady = true; }
/// <inheritdoc /> public async Task Handle(HelloEvent @event, CancellationToken cancellationToken) { using var scope = logger.BeginScope("{@Event}", nameof(HelloEvent)); cancellationToken.ThrowIfCancellationRequested(); _ = reporter.Report(default(HelloEventMetric), cancellationToken); await gateway.StartHeartbeat(@event.HeartbeatInterval); var message = gateway.SessionId == null || gateway.SequenceNumber == null?CreateIdentifyMessage() : CreateResumeMessage(); await gateway.Send(message, cancellationToken); }
/// <inheritdoc /> public async Task Handle(ReconnectEvent @event, CancellationToken cancellationToken) { using (var scope = logger.BeginScope("{@Event}", nameof(ReconnectEvent))) { cancellationToken.ThrowIfCancellationRequested(); var cancellationTokenSource = new CancellationTokenSource(); _ = reporter.Report(default(ReconnectEventMetric), cancellationToken); } await gateway.Restart(cancellationToken : CancellationToken.None); }
/// <inheritdoc /> public async Task Restart(IGatewayService gateway, bool resume, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); logger.LogInformation("Restarting the Gateway Service."); _ = reporter.Report(default(GatewayRestartMetric), cancellationToken); gateway.SessionId = resume ? gateway.SessionId : null; await gateway.StopAsync(cancellationToken); await utilsFactory.CreateRandomDelay(1000, 5000, cancellationToken); await gateway.StartAsync(cancellationToken); }
private IRestResponse ExecutePostRequest(RestRequest request) { Task <IRestResponse> task = null; try { task = RestClient.ExecutePostTaskAsync(request, CancellationToken); task.Wait(); } catch (Exception ex) { RestSharp.ResponseStatus status; if (ex is TimeoutException) { status = RestSharp.ResponseStatus.TimedOut; _metricReporter.Report(new ErrorMetric { SearchErrorCode = GlobalSearchErrorCode.Timeout }); } else if (ex is OperationCanceledException || (task != null && task.IsCanceled)) { status = RestSharp.ResponseStatus.Aborted; _metricReporter.Report(new ErrorMetric { SearchErrorCode = GlobalSearchErrorCode.Aborted }); } else { status = RestSharp.ResponseStatus.Error; _metricReporter.Report(new ErrorMetric { SearchErrorCode = GlobalSearchErrorCode.ElasticError }); } RestResponse response = new RestResponse { ResponseStatus = status, ErrorMessage = ex.Message }; return(response); } return(task.Result); }
/// <inheritdoc /> public async Task Handle(MessageCreateEvent @event, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using var trace = tracingService.StartTrace(); using var scope = logger.BeginScope("{@Event} {@TraceId}", nameof(MessageCreateEvent), trace.Id); tracingService.AddAnnotation("event", "incoming-message"); tracingService.AddAnnotation("messageId", @event.Message.Id); _ = reporter.Report(default(MessageCreateEventMetric), cancellationToken); if (await userService.IsUserRegistered(@event.Message.Author, cancellationToken)) { await HandleMessageFromRegisteredUser(@event, trace, cancellationToken); return; } if (@event.Message.Mentions.Any(mention => mention.Id == gateway.BotId)) { await PerformWelcome(@event, cancellationToken); } }