Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix RCS1090: add missing ConfigureAwait(false) #2035

Merged
merged 2 commits into from
Sep 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ private static void MapHealthCheckPushEndpoint(this IEndpointRouteBuilder builde
if (context.Request.IsAuthenticated())
{
using var streamReader = new StreamReader(context.Request.Body);
var content = await streamReader.ReadToEndAsync();
var content = await streamReader.ReadToEndAsync().ConfigureAwait(false);

var endpoint = JsonDocument.Parse(content);
var root = endpoint.RootElement;
Expand All @@ -47,15 +47,15 @@ private static void MapHealthCheckPushEndpoint(this IEndpointRouteBuilder builde

if (type == PushServiceKeys.ServiceAdded)
{
await pushService.AddAsync(name, uri);
await pushService.AddAsync(name, uri).ConfigureAwait(false);
}
else if (type == PushServiceKeys.ServiceRemoved)
{
await pushService.RemoveAsync(name);
await pushService.RemoveAsync(name).ConfigureAwait(false);
}
else if (type == PushServiceKeys.ServiceUpdated)
{
await pushService.UpdateAsync(name, uri);
await pushService.UpdateAsync(name, uri).ConfigureAwait(false);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,43 +16,43 @@ public HealthChecksPushService(HealthChecksDb db, ILogger<HealthChecksPushServic

public async Task AddAsync(string name, string uri)
{
if (await Get(name) == null)
if (await Get(name).ConfigureAwait(false) == null)
{
await _db.Configurations.AddAsync(new HealthCheckConfiguration
{
Name = name,
Uri = uri,
DiscoveryService = "kubernetes"
});
}).ConfigureAwait(false);

await _db.SaveChangesAsync();
await _db.SaveChangesAsync().ConfigureAwait(false);

_logger.LogInformation("[Push] New service added: {name} with uri: {uri}", name, uri);
}
}

public async Task RemoveAsync(string name)
{
var endpoint = await Get(name);
var endpoint = await Get(name).ConfigureAwait(false);

if (endpoint != null)
{
_db.Configurations.Remove(endpoint);
await _db.SaveChangesAsync();
await _db.SaveChangesAsync().ConfigureAwait(false);

_logger.LogInformation("[Push] Service removed: {name}", name);
}
}

public async Task UpdateAsync(string name, string uri)
{
var endpoint = await Get(name);
var endpoint = await Get(name).ConfigureAwait(false);

if (endpoint != null)
{
endpoint.Uri = uri;
_db.Configurations.Update(endpoint);
await _db.SaveChangesAsync();
await _db.SaveChangesAsync().ConfigureAwait(false);

_logger.LogInformation("[Push] Service updated: {name} with uri {uri}", name, uri);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<DockerfileContext>..\..</DockerfileContext>
<VersionPrefix>$(HealthChecksUIK8sOperator)</VersionPrefix>
<WarningsNotAsErrors>$(WarningsNotAsErrors);RCS1090</WarningsNotAsErrors>
<NoWarn>$(NoWarn);RCS1090</NoWarn>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ internal static async Task<V1ServiceList> GetServicesAsync(this IKubernetes clie
{
if (k8sNamespaces is null || k8sNamespaces.Count == 0)
{
return await client.CoreV1.ListServiceForAllNamespacesAsync(labelSelector: label, cancellationToken: cancellationToken);
return await client.CoreV1.ListServiceForAllNamespacesAsync(labelSelector: label, cancellationToken: cancellationToken).ConfigureAwait(false);
}
else
{
var responses = await Task.WhenAll(k8sNamespaces.Select(k8sNamespace => client.CoreV1.ListNamespacedServiceAsync(k8sNamespace, labelSelector: label, cancellationToken: cancellationToken)));
var responses = await Task.WhenAll(k8sNamespaces.Select(k8sNamespace => client.CoreV1.ListNamespacedServiceAsync(k8sNamespace, labelSelector: label, cancellationToken: cancellationToken))).ConfigureAwait(false);

return new V1ServiceList()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ private Task ExecuteAsync(CancellationToken cancellationToken)
#pragma warning disable IDISP003 // Dispose previous before re-assigning
_discoveryClient = InitializeKubernetesClient();
#pragma warning restore IDISP003 // Dispose previous before re-assigning
await StartK8sServiceAsync(cancellationToken);
await StartK8sServiceAsync(cancellationToken).ConfigureAwait(false);
}
catch (TaskCanceledException) when (cancellationToken.IsCancellationRequested)
{
Expand All @@ -84,7 +84,7 @@ private Task ExecuteAsync(CancellationToken cancellationToken)
public async Task StopAsync(CancellationToken cancellationToken)
{
if (_executingTask != null)
await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite, cancellationToken));
await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite, cancellationToken)).ConfigureAwait(false);
}

private async Task StartK8sServiceAsync(CancellationToken cancellationToken)
Expand All @@ -99,7 +99,7 @@ private async Task StartK8sServiceAsync(CancellationToken cancellationToken)

try
{
var services = await _discoveryClient!.GetServicesAsync(_discoveryOptions.ServicesLabel, _discoveryOptions.Namespaces, cancellationToken);
var services = await _discoveryClient!.GetServicesAsync(_discoveryOptions.ServicesLabel, _discoveryOptions.Namespaces, cancellationToken).ConfigureAwait(false);

if (services != null)
{
Expand All @@ -111,10 +111,10 @@ private async Task StartK8sServiceAsync(CancellationToken cancellationToken)

if (serviceAddress != null && !IsLivenessRegistered(livenessDbContext, serviceAddress))
{
var statusCode = await CallClusterServiceAsync(serviceAddress);
var statusCode = await CallClusterServiceAsync(serviceAddress).ConfigureAwait(false);
if (IsValidHealthChecksStatusCode(statusCode))
{
await RegisterDiscoveredLiveness(livenessDbContext, serviceAddress, item.Metadata.Name);
await RegisterDiscoveredLiveness(livenessDbContext, serviceAddress, item.Metadata.Name).ConfigureAwait(false);
_logger.LogInformation($"Registered discovered liveness on {serviceAddress} with name {item.Metadata.Name}");
}
}
Expand All @@ -131,7 +131,7 @@ private async Task StartK8sServiceAsync(CancellationToken cancellationToken)
_logger.LogError(ex, "An error occurred on kubernetes service discovery");
}

await Task.Delay(_discoveryOptions.RefreshTimeInSeconds * 1000);
await Task.Delay(_discoveryOptions.RefreshTimeInSeconds * 1000).ConfigureAwait(false);
}
}

Expand All @@ -148,7 +148,7 @@ private static bool IsValidHealthChecksStatusCode(HttpStatusCode statusCode)

private async Task<HttpStatusCode> CallClusterServiceAsync(string host)
{
using var response = await _clusterServiceClient.GetAsync(host, HttpCompletionOption.ResponseHeadersRead);
using var response = await _clusterServiceClient.GetAsync(host, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
return response.StatusCode;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public async Task Collect(CancellationToken cancellationToken)
{
using (_logger.BeginScope("HealthReportCollector is collecting health checks results."))
{
var healthChecks = await _db.Configurations.ToListAsync(cancellationToken);
var healthChecks = await _db.Configurations.ToListAsync(cancellationToken).ConfigureAwait(false);

foreach (var item in healthChecks.OrderBy(h => h.Id))
{
Expand All @@ -66,31 +66,31 @@ public async Task Collect(CancellationToken cancellationToken)

foreach (var interceptor in _interceptors)
{
await interceptor.OnCollectExecuting(item);
await interceptor.OnCollectExecuting(item).ConfigureAwait(false);
}

var healthReport = await GetHealthReportAsync(item);
var healthReport = await GetHealthReportAsync(item).ConfigureAwait(false);

if (healthReport.Status != UIHealthStatus.Healthy)
{
if (!_settings.NotifyUnHealthyOneTimeUntilChange || await ShouldNotifyAsync(item.Name))
if (!_settings.NotifyUnHealthyOneTimeUntilChange || await ShouldNotifyAsync(item.Name).ConfigureAwait(false))
{
await _healthCheckFailureNotifier.NotifyDown(item.Name, healthReport);
await _healthCheckFailureNotifier.NotifyDown(item.Name, healthReport).ConfigureAwait(false);
}
}
else
{
if (await HasLivenessRecoveredFromFailureAsync(item))
if (await HasLivenessRecoveredFromFailureAsync(item).ConfigureAwait(false))
{
await _healthCheckFailureNotifier.NotifyWakeUp(item.Name);
await _healthCheckFailureNotifier.NotifyWakeUp(item.Name).ConfigureAwait(false);
}
}

await SaveExecutionHistoryAsync(item, healthReport);
await SaveExecutionHistoryAsync(item, healthReport).ConfigureAwait(false);

foreach (var interceptor in _interceptors)
{
await interceptor.OnCollectExecuted(healthReport);
await interceptor.OnCollectExecuted(healthReport).ConfigureAwait(false);
}
}

Expand Down Expand Up @@ -135,18 +135,18 @@ private async Task<UIHealthReport> GetHealthReportAsync(HealthCheckConfiguration

using var requestMessage = new HttpRequestMessage(HttpMethod.Get, absoluteUri);
requestMessage.Headers.Authorization = new BasicAuthenticationHeaderValue(userInfoArr[0], userInfoArr[1]);
response = await _httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead);
response = await _httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
}
}

response ??= await _httpClient.GetAsync(absoluteUri, HttpCompletionOption.ResponseHeadersRead);
response ??= await _httpClient.GetAsync(absoluteUri, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

using (response)
{
if (!response.IsSuccessStatusCode && response.Content.Headers.ContentType?.MediaType != "application/json")
return UIHealthReport.CreateFrom(new InvalidOperationException($"HTTP response is not in valid state ({response.StatusCode}) when trying to get report from {uri} configured with name {name}."));

return await response.Content.ReadFromJsonAsync<UIHealthReport>(_options)
return await response.Content.ReadFromJsonAsync<UIHealthReport>(_options).ConfigureAwait(false)
?? throw new InvalidOperationException($"{nameof(HttpContentJsonExtensions.ReadFromJsonAsync)} returned null");
}
}
Expand Down Expand Up @@ -182,7 +182,7 @@ private Uri GetEndpointUri(HealthCheckConfiguration configuration)

private async Task<bool> HasLivenessRecoveredFromFailureAsync(HealthCheckConfiguration configuration)
{
var previous = await GetHealthCheckExecutionAsync(configuration);
var previous = await GetHealthCheckExecutionAsync(configuration).ConfigureAwait(false);

return previous != null && previous.Status != UIHealthStatus.Healthy;
}
Expand All @@ -193,7 +193,8 @@ private async Task<bool> HasLivenessRecoveredFromFailureAsync(HealthCheckConfigu
.Include(le => le.History)
.Include(le => le.Entries)
.Where(le => le.Name == configuration.Name)
.SingleOrDefaultAsync();
.SingleOrDefaultAsync()
.ConfigureAwait(false);
}

private async Task<bool> ShouldNotifyAsync(string healthCheckName)
Expand All @@ -202,7 +203,7 @@ private async Task<bool> ShouldNotifyAsync(string healthCheckName)
var lastNotifications = await _db.Failures
.Where(lf => string.Equals(lf.HealthCheckName, healthCheckName))
.OrderByDescending(lf => lf.LastNotified)
.Take(2).ToListAsync();
.Take(2).ToListAsync().ConfigureAwait(false);
#pragma warning restore RCS1155 // Use StringComparison when comparing strings.

if (lastNotifications?.Count == 2)
Expand All @@ -222,7 +223,7 @@ private async Task SaveExecutionHistoryAsync(HealthCheckConfiguration configurat
{
_logger.LogDebug("HealthReportCollector - health report execution history saved.");

var execution = await GetHealthCheckExecutionAsync(configuration);
var execution = await GetHealthCheckExecutionAsync(configuration).ConfigureAwait(false);

var lastExecutionTime = DateTime.UtcNow;

Expand Down Expand Up @@ -288,10 +289,11 @@ private async Task SaveExecutionHistoryAsync(HealthCheckConfiguration configurat
};

await _db.Executions
.AddAsync(execution);
.AddAsync(execution)
.ConfigureAwait(false);
}

await _db.SaveChangesAsync();
await _db.SaveChangesAsync().ConfigureAwait(false);
}

private static void UpdateUris(HealthCheckExecution execution, HealthCheckConfiguration configuration)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public async Task StopAsync(CancellationToken cancellationToken)
_cancellationTokenSource.Cancel();

if (_executingTask != null)
await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite, cancellationToken));
await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite, cancellationToken)).ConfigureAwait(false);
}

private Task ExecuteAsync(CancellationToken cancellationToken)
Expand All @@ -55,7 +55,7 @@ private Task ExecuteAsync(CancellationToken cancellationToken)
{
try
{
await CollectAsync(cancellationToken);
await CollectAsync(cancellationToken).ConfigureAwait(false);
}
catch (TaskCanceledException) when (cancellationToken.IsCancellationRequested)
{
Expand All @@ -81,7 +81,7 @@ private async Task CollectAsync(CancellationToken cancellationToken)
try
{
var runner = scope.ServiceProvider.GetRequiredService<IHealthCheckReportCollector>();
await runner.Collect(cancellationToken);
await runner.Collect(cancellationToken).ConfigureAwait(false);

_logger.LogDebug("HealthCheck collector HostedService executed successfully.");
}
Expand All @@ -91,7 +91,7 @@ private async Task CollectAsync(CancellationToken cancellationToken)
}
}

await Task.Delay(_settings.EvaluationTimeInSeconds * 1000, cancellationToken);
await Task.Delay(_settings.EvaluationTimeInSeconds * 1000, cancellationToken).ConfigureAwait(false);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public async Task StartAsync(CancellationToken cancellationToken)
var scopeFactory = _provider.GetRequiredService<IServiceScopeFactory>();
using var scope = scopeFactory.CreateScope();

await InitializeDatabaseAsync(scope.ServiceProvider);
await InitializeDatabaseAsync(scope.ServiceProvider).ConfigureAwait(false);
}

public Task StopAsync(CancellationToken cancellationToken)
Expand All @@ -45,10 +45,10 @@ private async Task InitializeDatabaseAsync(IServiceProvider sp)
var configuration = sp.GetRequiredService<IConfiguration>();
var settings = sp.GetRequiredService<IOptions<Settings>>();

if (await ShouldMigrateDatabaseAsync(context))
if (await ShouldMigrateDatabaseAsync(context).ConfigureAwait(false))
{
_logger.LogInformation("Executing database migrations");
await context.Database.MigrateAsync();
await context.Database.MigrateAsync().ConfigureAwait(false);
}

var healthCheckConfigurations = settings.Value?
Expand All @@ -59,19 +59,20 @@ private async Task InitializeDatabaseAsync(IServiceProvider sp)
Uri = s.Uri
});

bool isInitialized = await context.Configurations.AnyAsync();
bool isInitialized = await context.Configurations.AnyAsync().ConfigureAwait(false);

if (!isInitialized && healthCheckConfigurations != null && healthCheckConfigurations.Any())
{
_logger.LogInformation("Saving healthchecks configuration to database");

await context.Configurations
.AddRangeAsync(healthCheckConfigurations);
.AddRangeAsync(healthCheckConfigurations)
.ConfigureAwait(false);

}
else if (isInitialized && healthCheckConfigurations != null && healthCheckConfigurations.Any())
{
var dbConfigurations = await context.Configurations.ToListAsync();
var dbConfigurations = await context.Configurations.ToListAsync().ConfigureAwait(false);

var existingConfigurations = dbConfigurations
.Where(hc => healthCheckConfigurations.Any(dbc => string.Equals(hc.Name, dbc.Name, StringComparison.InvariantCultureIgnoreCase)));
Expand All @@ -94,18 +95,18 @@ await context.Configurations
foreach (var item in newConfigurations)
{
_logger.LogInformation("Adding new service {service} to database", item.Name);
await context.AddAsync(item);
await context.AddAsync(item).ConfigureAwait(false);
}
}
}

await context.SaveChangesAsync();
await context.SaveChangesAsync().ConfigureAwait(false);
}

private async Task<bool> ShouldMigrateDatabaseAsync(HealthChecksDb context)
{
return !_settings.DisableMigrations &&
!context.Database.IsInMemory() &&
(await context.Database.GetPendingMigrationsAsync()).Any();
(await context.Database.GetPendingMigrationsAsync().ConfigureAwait(false)).Any();
}
}
Loading