Skip to content
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
@@ -1,4 +1,5 @@
using System.Net;
using Microsoft.Extensions.Configuration;
using Xunit;
using XtremeIdiots.Portal.Repository.Abstractions.Constants.V1;
using XtremeIdiots.Portal.Repository.Abstractions.Interfaces.V1;
Expand All @@ -10,15 +11,17 @@ namespace XtremeIdiots.Portal.Repository.Api.Tests.V1.Controllers.V1;

public class DataMaintenanceControllerTests
{
private static readonly IConfiguration EmptyConfiguration = new ConfigurationBuilder().Build();

private DataMaintenanceController CreateController(PortalDbContext context)
{
return new DataMaintenanceController(context);
return new DataMaintenanceController(context, EmptyConfiguration);
}

[Fact]
public void Constructor_WithNullContext_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => new DataMaintenanceController(null!));
Assert.Throws<ArgumentNullException>(() => new DataMaintenanceController(null!, EmptyConfiguration));
}

[Fact(Skip = "Uses ExecuteSqlInterpolatedAsync which is not supported by the InMemory provider")]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System.Linq;
using System.Net;
using Azure.Identity;
Expand Down Expand Up @@ -29,16 +30,18 @@
public class DataMaintenanceController : ControllerBase, IDataMaintenanceApi
{
private readonly PortalDbContext context;
private readonly IConfiguration configuration;

/// <summary>
/// Initializes a new instance of the <see cref="DataMaintenanceController"/> class.
/// </summary>
/// <param name="context">The database context for data operations.</param>
/// <exception cref="ArgumentNullException">Thrown when context is null.</exception>
public DataMaintenanceController(PortalDbContext context)
public DataMaintenanceController(PortalDbContext context, IConfiguration configuration)
Comment thread
frasermolyneux marked this conversation as resolved.
{
ArgumentNullException.ThrowIfNull(context);
this.context = context;
Comment thread
frasermolyneux marked this conversation as resolved.
this.configuration = configuration;
}

/// <summary>
Expand Down Expand Up @@ -144,7 +147,8 @@
/// <returns>An API result indicating the operation completed successfully.</returns>
async Task<ApiResult> IDataMaintenanceApi.PruneRecentPlayers(CancellationToken cancellationToken)
{
var cutoffDate = DateTime.UtcNow.AddDays(-7);
var recentPlayersDays = int.TryParse(configuration["DataRetention:RecentPlayersDays"], out var rpd) ? rpd : 7;
Comment thread
frasermolyneux marked this conversation as resolved.
var cutoffDate = DateTime.UtcNow.AddDays(-recentPlayersDays);
await context.Database.ExecuteSqlInterpolatedAsync($"DELETE FROM [dbo].[RecentPlayers] WHERE [Timestamp] < {cutoffDate}", cancellationToken).ConfigureAwait(false);
return new ApiResponse().ToApiResult();
}
Expand Down Expand Up @@ -172,7 +176,8 @@
/// <returns>An API result indicating the operation completed successfully.</returns>
async Task<ApiResult> IDataMaintenanceApi.ResetSystemAssignedPlayerTags(CancellationToken cancellationToken)
{
var twoWeeksAgo = DateTime.UtcNow.AddDays(-14);
var inactivePlayerDays = int.TryParse(configuration["DataRetention:InactivePlayerDays"], out var ipd) ? ipd : 14;
Comment thread
frasermolyneux marked this conversation as resolved.
var twoWeeksAgo = DateTime.UtcNow.AddDays(-inactivePlayerDays);

// Get the tag IDs by name
var activeTag = await context.Tags
Expand Down Expand Up @@ -250,7 +255,7 @@
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>An API result indicating completion.</returns>
async Task<ApiResult> IDataMaintenanceApi.ValidateMapImages(CancellationToken cancellationToken)

Check warning on line 258 in src/XtremeIdiots.Portal.Repository.Api.V1/Controllers/V1/DataMaintenanceController.cs

View workflow job for this annotation

GitHub Actions / quality / Code Quality

Refactor this method to reduce its Cognitive Complexity from 38 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)
{
var blobEndpoint = Environment.GetEnvironmentVariable("appdata_storage_blob_endpoint");
if (string.IsNullOrEmpty(blobEndpoint))
Expand Down Expand Up @@ -317,7 +322,7 @@
await download.Value.Content.CopyToAsync(mem, 1024, cancellationToken).ConfigureAwait(false);
var bytes = mem.ToArray();
var head = Encoding.UTF8.GetString(bytes, 0, Math.Min(bytes.Length, 512));
var looksHtml = head.TrimStart().StartsWith("<") && head.IndexOf("<html", StringComparison.OrdinalIgnoreCase) >= 0;

Check warning on line 325 in src/XtremeIdiots.Portal.Repository.Api.V1/Controllers/V1/DataMaintenanceController.cs

View workflow job for this annotation

GitHub Actions / quality / Code Quality

"StartsWith" overloads that take a "char" should be used (https://rules.sonarsource.com/csharp/RSPEC-6610)

if (looksHtml)
{
Expand Down Expand Up @@ -406,7 +411,7 @@
return true;
}
}
catch { }

Check warning on line 414 in src/XtremeIdiots.Portal.Repository.Api.V1/Controllers/V1/DataMaintenanceController.cs

View workflow job for this annotation

GitHub Actions / quality / Code Quality

Either remove or fill this block of code. (https://rules.sonarsource.com/csharp/RSPEC-108)

Check warning on line 414 in src/XtremeIdiots.Portal.Repository.Api.V1/Controllers/V1/DataMaintenanceController.cs

View workflow job for this annotation

GitHub Actions / quality / Code Quality

Handle the exception or explain in a comment why it can be ignored. (https://rules.sonarsource.com/csharp/RSPEC-2486)
return false;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,8 @@
bool gametrackerFallback,
CancellationToken cancellationToken)
{
var gameTrackerImageUrl = $"https://cache.gametracker.com/server_info/{ipAddress}:{queryPort}/{imageName}";
var gameTrackerBannerBaseUrl = (configuration["GameTracker:BannerBaseUrl"] ?? "https://cache.gametracker.com/server_info/").TrimEnd('/') + "/";

Check warning on line 137 in src/XtremeIdiots.Portal.Repository.Api.V1/Controllers/V1/GameTrackerBannerController.cs

View workflow job for this annotation

GitHub Actions / quality / Code Quality

Refactor your code not to use hardcoded absolute paths or URIs. (https://rules.sonarsource.com/csharp/RSPEC-1075)

Check warning on line 137 in src/XtremeIdiots.Portal.Repository.Api.V1/Controllers/V1/GameTrackerBannerController.cs

View workflow job for this annotation

GitHub Actions / quality / Code Quality

Remove this hardcoded path-delimiter. (https://rules.sonarsource.com/csharp/RSPEC-1075)
var gameTrackerImageUrl = $"{gameTrackerBannerBaseUrl}{ipAddress}:{queryPort}/{imageName}";

try
{
Expand Down
41 changes: 23 additions & 18 deletions src/XtremeIdiots.Portal.Repository.Api.V1/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,32 @@
using XtremeIdiots.Portal.Repository.Api.V1;
using Asp.Versioning;
using XtremeIdiots.Portal.Repository.Api.V1.OpenApi;
using Azure.Core;
using Scalar.AspNetCore;

var builder = WebApplication.CreateBuilder(args);

var appConfigurationEndpoint = builder.Configuration["AzureAppConfiguration:Endpoint"];
var appConfigEndpoint = builder.Configuration["AzureAppConfiguration:Endpoint"];
var isAzureAppConfigurationEnabled = false;

if (!string.IsNullOrWhiteSpace(appConfigurationEndpoint))
if (!string.IsNullOrWhiteSpace(appConfigEndpoint))
{
var managedIdentityClientId = builder.Configuration["AzureAppConfiguration:ManagedIdentityClientId"];
TokenCredential identityCredential = string.IsNullOrWhiteSpace(managedIdentityClientId)
? new DefaultAzureCredential()
: new ManagedIdentityCredential(managedIdentityClientId);
var environmentLabel = builder.Configuration["AzureAppConfiguration:Environment"];

var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions
{
ManagedIdentityClientId = managedIdentityClientId,
});
Comment thread
frasermolyneux marked this conversation as resolved.

builder.Configuration.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(appConfigurationEndpoint), identityCredential)
.Select("XtremeIdiots.Portal.Repository.Api.V1:*", labelFilter: builder.Configuration["AzureAppConfiguration:Environment"])
.TrimKeyPrefix("XtremeIdiots.Portal.Repository.Api.V1:");
options.Connect(new Uri(appConfigEndpoint), credential)
.Select("XtremeIdiots.Portal.Repository.Api.V1:*", environmentLabel)
.TrimKeyPrefix("XtremeIdiots.Portal.Repository.Api.V1:")
.Select("GameTracker:*", environmentLabel)
.Select("SqlResilience:*", environmentLabel);

options.ConfigureKeyVault(keyVaultOptions =>
{
keyVaultOptions.SetCredential(identityCredential);
});
options.ConfigureKeyVault(kv => kv.SetCredential(credential));
});

builder.Services.AddAzureAppConfiguration();
Expand All @@ -57,9 +58,9 @@
telemetryProcessorChainBuilder.UseAdaptiveSampling(
settings: new SamplingPercentageEstimatorSettings
{
InitialSamplingPercentage = 5,
MinSamplingPercentage = 5,
MaxSamplingPercentage = 60
InitialSamplingPercentage = double.TryParse(builder.Configuration["ApplicationInsights:InitialSamplingPercentage"], out var initPct) ? initPct : 5,
MinSamplingPercentage = double.TryParse(builder.Configuration["ApplicationInsights:MinSamplingPercentage"], out var minPct) ? minPct : 5,
MaxSamplingPercentage = double.TryParse(builder.Configuration["ApplicationInsights:MaxSamplingPercentage"], out var maxPct) ? maxPct : 60
},
Comment thread
frasermolyneux marked this conversation as resolved.
callback: null,
excludedTypes: "Exception");
Expand All @@ -75,10 +76,14 @@

builder.Services.AddDbContext<PortalDbContext>(options =>
{
var retryCount = int.TryParse(builder.Configuration["SqlResilience:RetryCount"], out var rc) ? rc : 3;
var retryDelay = int.TryParse(builder.Configuration["SqlResilience:RetryDelaySeconds"], out var rd) ? rd : 5;
var commandTimeout = int.TryParse(builder.Configuration["SqlResilience:CommandTimeoutSeconds"], out var ct) ? ct : 180;

options.UseSqlServer(builder.Configuration["sql_connection_string"], sqlOptions =>
{
sqlOptions.EnableRetryOnFailure(3, TimeSpan.FromSeconds(5), null);
sqlOptions.CommandTimeout(180);
sqlOptions.EnableRetryOnFailure(retryCount, TimeSpan.FromSeconds(retryDelay), null);
sqlOptions.CommandTimeout(commandTimeout);
});
Comment thread
frasermolyneux marked this conversation as resolved.
});

Expand Down Expand Up @@ -139,6 +144,6 @@

app.MapGet("/", () => Results.Ok()).ExcludeFromDescription();

app.Run();

Check warning on line 147 in src/XtremeIdiots.Portal.Repository.Api.V1/Program.cs

View workflow job for this annotation

GitHub Actions / quality / Code Quality

Await RunAsync instead. (https://rules.sonarsource.com/csharp/RSPEC-6966)

public partial class Program { }

Check warning on line 149 in src/XtremeIdiots.Portal.Repository.Api.V1/Program.cs

View workflow job for this annotation

GitHub Actions / quality / Code Quality

Add a 'protected' constructor or the 'static' keyword to the class declaration. (https://rules.sonarsource.com/csharp/RSPEC-1118)
40 changes: 22 additions & 18 deletions src/XtremeIdiots.Portal.Repository.Api.V2/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,31 @@
using XtremeIdiots.Portal.Repository.Api.V2;
using Asp.Versioning;
using XtremeIdiots.Portal.Repository.Api.V2.OpenApi;
using Azure.Core;
using Scalar.AspNetCore;

var builder = WebApplication.CreateBuilder(args);

var appConfigurationEndpoint = builder.Configuration["AzureAppConfiguration:Endpoint"];
var appConfigEndpoint = builder.Configuration["AzureAppConfiguration:Endpoint"];
var isAzureAppConfigurationEnabled = false;

if (!string.IsNullOrWhiteSpace(appConfigurationEndpoint))
if (!string.IsNullOrWhiteSpace(appConfigEndpoint))
{
var managedIdentityClientId = builder.Configuration["AzureAppConfiguration:ManagedIdentityClientId"];
TokenCredential identityCredential = string.IsNullOrWhiteSpace(managedIdentityClientId)
? new DefaultAzureCredential()
: new ManagedIdentityCredential(managedIdentityClientId);
var environmentLabel = builder.Configuration["AzureAppConfiguration:Environment"];

var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions
{
ManagedIdentityClientId = managedIdentityClientId,
});
Comment thread
frasermolyneux marked this conversation as resolved.

builder.Configuration.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(appConfigurationEndpoint), identityCredential)
.Select("XtremeIdiots.Portal.Repository.Api.V2:*", labelFilter: builder.Configuration["AzureAppConfiguration:Environment"])
.TrimKeyPrefix("XtremeIdiots.Portal.Repository.Api.V2:");
options.Connect(new Uri(appConfigEndpoint), credential)
.Select("XtremeIdiots.Portal.Repository.Api.V2:*", environmentLabel)
.TrimKeyPrefix("XtremeIdiots.Portal.Repository.Api.V2:")
.Select("SqlResilience:*", environmentLabel);

options.ConfigureKeyVault(keyVaultOptions =>
{
keyVaultOptions.SetCredential(identityCredential);
});
options.ConfigureKeyVault(kv => kv.SetCredential(credential));
});

builder.Services.AddAzureAppConfiguration();
Expand All @@ -54,9 +54,9 @@
telemetryProcessorChainBuilder.UseAdaptiveSampling(
settings: new SamplingPercentageEstimatorSettings
{
InitialSamplingPercentage = 5,
MinSamplingPercentage = 5,
MaxSamplingPercentage = 60
InitialSamplingPercentage = double.TryParse(builder.Configuration["ApplicationInsights:InitialSamplingPercentage"], out var initPct) ? initPct : 5,
MinSamplingPercentage = double.TryParse(builder.Configuration["ApplicationInsights:MinSamplingPercentage"], out var minPct) ? minPct : 5,
MaxSamplingPercentage = double.TryParse(builder.Configuration["ApplicationInsights:MaxSamplingPercentage"], out var maxPct) ? maxPct : 60
},
Comment thread
frasermolyneux marked this conversation as resolved.
callback: null,
excludedTypes: "Exception");
Expand All @@ -72,10 +72,14 @@

builder.Services.AddDbContext<PortalDbContext>(options =>
{
var retryCount = int.TryParse(builder.Configuration["SqlResilience:RetryCount"], out var rc) ? rc : 3;
var retryDelay = int.TryParse(builder.Configuration["SqlResilience:RetryDelaySeconds"], out var rd) ? rd : 5;
var commandTimeout = int.TryParse(builder.Configuration["SqlResilience:CommandTimeoutSeconds"], out var ct) ? ct : 180;

options.UseSqlServer(builder.Configuration["sql_connection_string"], sqlOptions =>
{
sqlOptions.EnableRetryOnFailure(3, TimeSpan.FromSeconds(5), null);
sqlOptions.CommandTimeout(180);
sqlOptions.EnableRetryOnFailure(retryCount, TimeSpan.FromSeconds(retryDelay), null);
sqlOptions.CommandTimeout(commandTimeout);
});
Comment thread
frasermolyneux marked this conversation as resolved.
});

Expand Down Expand Up @@ -136,7 +140,7 @@

app.MapGet("/", () => Results.Ok()).ExcludeFromDescription();

app.Run();

Check warning on line 143 in src/XtremeIdiots.Portal.Repository.Api.V2/Program.cs

View workflow job for this annotation

GitHub Actions / quality / Code Quality

Await RunAsync instead. (https://rules.sonarsource.com/csharp/RSPEC-6966)

public partial class Program { }

Check warning on line 145 in src/XtremeIdiots.Portal.Repository.Api.V2/Program.cs

View workflow job for this annotation

GitHub Actions / quality / Code Quality

Add a 'protected' constructor or the 'static' keyword to the class declaration. (https://rules.sonarsource.com/csharp/RSPEC-1118)

Loading