LANCommander/LANCommander.Server/Program.cs

524 lines
21 KiB
C#
Raw Normal View History

2024-08-04 18:44:33 -05:00
using LANCommander.Server.Data;
using LANCommander.Server.Data.Models;
using LANCommander.Server.Hubs;
using LANCommander.Server.Services;
2023-01-02 15:44:04 -06:00
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
2023-01-04 23:45:11 -06:00
using Microsoft.IdentityModel.Tokens;
using System.Text;
2023-04-19 18:09:34 -05:00
using Hangfire;
2024-08-04 18:44:33 -05:00
using LANCommander.Server.Services.MediaGrabbers;
using LANCommander.Server.Extensions;
using Microsoft.AspNetCore.Http.Features;
2024-08-12 00:15:16 -05:00
using LANCommander.SDK.Enums;
using Serilog;
2024-08-29 00:19:56 -05:00
using Serilog.Sinks.AspNetCore.App.SignalR.Extensions;
using LANCommander.Server.Logging;
2024-10-12 18:36:00 -05:00
using LANCommander.Server.Data.Enums;
WIP fix for MySQL connection concurrency issues This is a large commit. There are a number of things that this commit does to try to fix various issues that were occurring when the database provider was set to MySQL: - The DAL `Repository` has been completely refactored to follow best practices. The repository is now being injected into services instead of the database context itself. This allows the DI to handle the repository's lifetime instead of creating a new repository for every transaction and sharing the context across repositories. As part of these changes, there is no more allowed usage of `IQueryable` and all service/repository methods must actually execute database queries before their return. This is to ensure that the context does not stay open longer than it needs to. Abusing `IQueryable`s by tossing them into Blazor components seems to be a big no-no. - Some deletion behaviors on relationships have been tweaked as MySQL wasn't able to apply migrations with behaviors that were contradictory. - A `ConnectionInterceptor` was added to try to keep track of `DatabaseContext` lifetimes. This is really only for debugging and should be put into `#if DEBUG` regions. This helped identify some potential issues where some contexts were basically never closing, causing the MySQL connector to not function. - Docs for generating migrations have been updated to reflect the addition of being able to specify the database provider and connection string when adding a migration, avoiding the need to edit `Settings.yml` - The application can now be put into a pause state on startup by adding the `--debugger` argument when used from the command line. When a debugger is attached, it resumes execution. - The application can now log to Seq when using debug build - Service lifetime on `DatabaseContext` has switched to transient. This may be reverted in the future. - Lazy loading has been disabled for debugging purposes. It didn't directly help the concurrency issues, but it needs to be tested individually to be re-enabled. - All usage of `UserManager`, `RoleManager`, and `SignInManager` have been removed from all controllers, pages, and Blazor components. Functionality has been moved to `UserService` and `RoleService`. This might have done the most amount of help, but could probably be improved upon in the future by not relying on them and instead having our own implementation. - Application startup migrations and server autostarts have been disabled temporarily. There might be an issue of `DatabaseContext` lifetimes that spawn from this.
2024-10-13 20:42:45 -05:00
using System.Diagnostics;
using LANCommander.Server.Services.Factories;
2024-10-18 19:15:05 -05:00
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Authentication;
2024-11-05 20:20:03 -06:00
using LANCommander.Server.Jobs.Background;
using LANCommander.Server.Services.Models;
2025-01-04 02:02:41 -06:00
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Data.Sqlite;
using Microsoft.OpenApi.Models;
using Microsoft.CodeAnalysis.Options;
using Scalar.AspNetCore;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
2023-08-11 15:12:16 -05:00
2024-08-04 18:44:33 -05:00
namespace LANCommander.Server
2023-02-12 17:32:59 -06:00
{
internal class Program
2023-01-04 23:45:11 -06:00
{
static async Task Main(string[] args)
2023-01-04 23:45:11 -06:00
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateBootstrapLogger();
WIP fix for MySQL connection concurrency issues This is a large commit. There are a number of things that this commit does to try to fix various issues that were occurring when the database provider was set to MySQL: - The DAL `Repository` has been completely refactored to follow best practices. The repository is now being injected into services instead of the database context itself. This allows the DI to handle the repository's lifetime instead of creating a new repository for every transaction and sharing the context across repositories. As part of these changes, there is no more allowed usage of `IQueryable` and all service/repository methods must actually execute database queries before their return. This is to ensure that the context does not stay open longer than it needs to. Abusing `IQueryable`s by tossing them into Blazor components seems to be a big no-no. - Some deletion behaviors on relationships have been tweaked as MySQL wasn't able to apply migrations with behaviors that were contradictory. - A `ConnectionInterceptor` was added to try to keep track of `DatabaseContext` lifetimes. This is really only for debugging and should be put into `#if DEBUG` regions. This helped identify some potential issues where some contexts were basically never closing, causing the MySQL connector to not function. - Docs for generating migrations have been updated to reflect the addition of being able to specify the database provider and connection string when adding a migration, avoiding the need to edit `Settings.yml` - The application can now be put into a pause state on startup by adding the `--debugger` argument when used from the command line. When a debugger is attached, it resumes execution. - The application can now log to Seq when using debug build - Service lifetime on `DatabaseContext` has switched to transient. This may be reverted in the future. - Lazy loading has been disabled for debugging purposes. It didn't directly help the concurrency issues, but it needs to be tested individually to be re-enabled. - All usage of `UserManager`, `RoleManager`, and `SignInManager` have been removed from all controllers, pages, and Blazor components. Functionality has been moved to `UserService` and `RoleService`. This might have done the most amount of help, but could probably be improved upon in the future by not relying on them and instead having our own implementation. - Application startup migrations and server autostarts have been disabled temporarily. There might be an issue of `DatabaseContext` lifetimes that spawn from this.
2024-10-13 20:42:45 -05:00
Log.Information("Starting application...");
var builder = WebApplication.CreateBuilder(args);
ConfigurationManager configuration = builder.Configuration;
WIP fix for MySQL connection concurrency issues This is a large commit. There are a number of things that this commit does to try to fix various issues that were occurring when the database provider was set to MySQL: - The DAL `Repository` has been completely refactored to follow best practices. The repository is now being injected into services instead of the database context itself. This allows the DI to handle the repository's lifetime instead of creating a new repository for every transaction and sharing the context across repositories. As part of these changes, there is no more allowed usage of `IQueryable` and all service/repository methods must actually execute database queries before their return. This is to ensure that the context does not stay open longer than it needs to. Abusing `IQueryable`s by tossing them into Blazor components seems to be a big no-no. - Some deletion behaviors on relationships have been tweaked as MySQL wasn't able to apply migrations with behaviors that were contradictory. - A `ConnectionInterceptor` was added to try to keep track of `DatabaseContext` lifetimes. This is really only for debugging and should be put into `#if DEBUG` regions. This helped identify some potential issues where some contexts were basically never closing, causing the MySQL connector to not function. - Docs for generating migrations have been updated to reflect the addition of being able to specify the database provider and connection string when adding a migration, avoiding the need to edit `Settings.yml` - The application can now be put into a pause state on startup by adding the `--debugger` argument when used from the command line. When a debugger is attached, it resumes execution. - The application can now log to Seq when using debug build - Service lifetime on `DatabaseContext` has switched to transient. This may be reverted in the future. - Lazy loading has been disabled for debugging purposes. It didn't directly help the concurrency issues, but it needs to be tested individually to be re-enabled. - All usage of `UserManager`, `RoleManager`, and `SignInManager` have been removed from all controllers, pages, and Blazor components. Functionality has been moved to `UserService` and `RoleService`. This might have done the most amount of help, but could probably be improved upon in the future by not relying on them and instead having our own implementation. - Application startup migrations and server autostarts have been disabled temporarily. There might be an issue of `DatabaseContext` lifetimes that spawn from this.
2024-10-13 20:42:45 -05:00
#region Debug
if (args.Contains("--debugger"))
{
var currentProcess = Process.GetCurrentProcess();
Console.WriteLine($"Waiting for debugger to attach... Process ID: {currentProcess.Id}");
while (!Debugger.IsAttached)
{
Thread.Sleep(100);
}
Console.WriteLine("Debugger attached.");
}
#endregion
// Add services to the container.
Log.Debug("Loading settings");
var settings = SettingService.GetSettings(true);
WIP fix for MySQL connection concurrency issues This is a large commit. There are a number of things that this commit does to try to fix various issues that were occurring when the database provider was set to MySQL: - The DAL `Repository` has been completely refactored to follow best practices. The repository is now being injected into services instead of the database context itself. This allows the DI to handle the repository's lifetime instead of creating a new repository for every transaction and sharing the context across repositories. As part of these changes, there is no more allowed usage of `IQueryable` and all service/repository methods must actually execute database queries before their return. This is to ensure that the context does not stay open longer than it needs to. Abusing `IQueryable`s by tossing them into Blazor components seems to be a big no-no. - Some deletion behaviors on relationships have been tweaked as MySQL wasn't able to apply migrations with behaviors that were contradictory. - A `ConnectionInterceptor` was added to try to keep track of `DatabaseContext` lifetimes. This is really only for debugging and should be put into `#if DEBUG` regions. This helped identify some potential issues where some contexts were basically never closing, causing the MySQL connector to not function. - Docs for generating migrations have been updated to reflect the addition of being able to specify the database provider and connection string when adding a migration, avoiding the need to edit `Settings.yml` - The application can now be put into a pause state on startup by adding the `--debugger` argument when used from the command line. When a debugger is attached, it resumes execution. - The application can now log to Seq when using debug build - Service lifetime on `DatabaseContext` has switched to transient. This may be reverted in the future. - Lazy loading has been disabled for debugging purposes. It didn't directly help the concurrency issues, but it needs to be tested individually to be re-enabled. - All usage of `UserManager`, `RoleManager`, and `SignInManager` have been removed from all controllers, pages, and Blazor components. Functionality has been moved to `UserService` and `RoleService`. This might have done the most amount of help, but could probably be improved upon in the future by not relying on them and instead having our own implementation. - Application startup migrations and server autostarts have been disabled temporarily. There might be an issue of `DatabaseContext` lifetimes that spawn from this.
2024-10-13 20:42:45 -05:00
var databaseProviderParameter = args.FirstOrDefault(arg => arg.StartsWith("--database-provider="))?.Split('=', 2).Last();
var connectionStringParameter = args.FirstOrDefault(arg => arg.StartsWith("--connection-string="))?.Split('=', 2).Last();
if (!String.IsNullOrWhiteSpace(databaseProviderParameter))
DatabaseContext.Provider = Enum.Parse<DatabaseProvider>(databaseProviderParameter);
else
DatabaseContext.Provider = settings.DatabaseProvider;
if (!String.IsNullOrWhiteSpace(connectionStringParameter))
DatabaseContext.ConnectionString = connectionStringParameter;
else
DatabaseContext.ConnectionString = settings.DatabaseConnectionString;
Log.Debug("Loaded!");
Log.Debug("Configuring logging");
2024-08-29 00:19:56 -05:00
builder.Services.AddSignalR().AddJsonProtocol(options =>
{
options.PayloadSerializerOptions.PropertyNamingPolicy = null;
});
2024-08-29 00:19:56 -05:00
builder.Services.AddSerilogHub<LoggingHub>();
builder.Services.AddSerilog((serviceProvider, config) => config
.WriteTo.Console()
.WriteTo.File(Path.Combine(settings.Logs.StoragePath, "log-.txt"), rollingInterval: (RollingInterval)(int)settings.Logs.ArchiveEvery)
WIP fix for MySQL connection concurrency issues This is a large commit. There are a number of things that this commit does to try to fix various issues that were occurring when the database provider was set to MySQL: - The DAL `Repository` has been completely refactored to follow best practices. The repository is now being injected into services instead of the database context itself. This allows the DI to handle the repository's lifetime instead of creating a new repository for every transaction and sharing the context across repositories. As part of these changes, there is no more allowed usage of `IQueryable` and all service/repository methods must actually execute database queries before their return. This is to ensure that the context does not stay open longer than it needs to. Abusing `IQueryable`s by tossing them into Blazor components seems to be a big no-no. - Some deletion behaviors on relationships have been tweaked as MySQL wasn't able to apply migrations with behaviors that were contradictory. - A `ConnectionInterceptor` was added to try to keep track of `DatabaseContext` lifetimes. This is really only for debugging and should be put into `#if DEBUG` regions. This helped identify some potential issues where some contexts were basically never closing, causing the MySQL connector to not function. - Docs for generating migrations have been updated to reflect the addition of being able to specify the database provider and connection string when adding a migration, avoiding the need to edit `Settings.yml` - The application can now be put into a pause state on startup by adding the `--debugger` argument when used from the command line. When a debugger is attached, it resumes execution. - The application can now log to Seq when using debug build - Service lifetime on `DatabaseContext` has switched to transient. This may be reverted in the future. - Lazy loading has been disabled for debugging purposes. It didn't directly help the concurrency issues, but it needs to be tested individually to be re-enabled. - All usage of `UserManager`, `RoleManager`, and `SignInManager` have been removed from all controllers, pages, and Blazor components. Functionality has been moved to `UserService` and `RoleService`. This might have done the most amount of help, but could probably be improved upon in the future by not relying on them and instead having our own implementation. - Application startup migrations and server autostarts have been disabled temporarily. There might be an issue of `DatabaseContext` lifetimes that spawn from this.
2024-10-13 20:42:45 -05:00
#if DEBUG
.WriteTo.Seq("http://localhost:5341")
.MinimumLevel.Debug()
#endif
2024-08-29 00:19:56 -05:00
.WriteTo.SignalR<LoggingHub>(
serviceProvider,
(context, message, logEvent) => LoggingHub.Log(context, message, logEvent)
));
#region Validate Settings
Log.Debug("Validating settings");
if (settings?.Authentication?.TokenSecret?.Length < 16)
{
Log.Debug("JWT token secret is too short. Regenerating...");
settings.Authentication.TokenSecret = Guid.NewGuid().ToString();
SettingService.SaveSettings(settings);
}
Log.Debug("Done validating settings");
#endregion
Log.Debug("Configuring MVC and Blazor");
builder.Services
.AddMvc(options => options.EnableEndpointRouting = false)
.AddRazorOptions(options =>
{
options.ViewLocationFormats.Clear();
options.ViewLocationFormats.Add("/UI/Views/{1}/{0}.cshtml");
options.ViewLocationFormats.Add("/UI/Views/Shared/{0}.cshtml");
options.ViewLocationFormats.Add("/UI/Pages/Shared/{0}.cshtml");
options.AreaViewLocationFormats.Clear();
options.AreaViewLocationFormats.Add("/Areas/{2}/Views/{1}/{0}.cshtml");
options.AreaViewLocationFormats.Add("/Areas/{2}/Views/Shared/{0}.cshtml");
options.AreaViewLocationFormats.Add("/UI/Views/Shared/{0}.cshtml");
options.AreaViewLocationFormats.Add("/UI/Pages/Shared/{0}.cshtml");
options.PageViewLocationFormats.Clear();
options.PageViewLocationFormats.Add("/UI/Pages/{1}/{0}.cshtml");
options.PageViewLocationFormats.Add("/UI/Pages/Shared/{0}.cshtml");
options.PageViewLocationFormats.Add("/UI/Views/Shared/{0}.cshtml");
options.AreaPageViewLocationFormats.Clear();
options.AreaPageViewLocationFormats.Add("/Areas/{2}/Pages/{1}/{0}.cshtml");
options.AreaPageViewLocationFormats.Add("/Areas/{2}/Pages/Shared/{0}.cshtml");
options.AreaPageViewLocationFormats.Add("/Areas/{2}/Views/Shared/{0}.cshtml");
options.AreaPageViewLocationFormats.Add("/UI/Pages/Shared/{0}.cshtml");
options.AreaPageViewLocationFormats.Add("/UI/Views/Shared/{0}.cshtml");
});
2024-06-18 18:06:22 -05:00
builder.Services.AddRazorPages(options =>
{
options.RootDirectory = "/UI/Pages";
});
2024-10-18 19:15:05 -05:00
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddAutoMapper(typeof(AutoMapper));
Log.Debug("Starting web server on port {Port}", settings.Port);
builder.WebHost.ConfigureKestrel(options =>
{
// Configure as HTTP only
options.ListenAnyIP(settings.Port);
});
builder.Services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyHeader()
.AllowAnyMethod()
.SetIsOriginAllowed((host) => true)
.AllowCredentials();
}));
Log.Debug("Initializing DatabaseContext with connection string {ConnectionString}", settings.DatabaseConnectionString);
builder.Services.AddDbContextFactory<DatabaseContext>();
builder.Services.AddDbContext<DatabaseContext>();
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
Log.Debug("Initializing Identity");
2024-10-18 19:15:05 -05:00
builder.Services.AddIdentityCore<User>((IdentityOptions options) =>
{
options.SignIn.RequireConfirmedAccount = false;
options.SignIn.RequireConfirmedEmail = false;
options.Password.RequireNonAlphanumeric = settings.Authentication.PasswordRequireNonAlphanumeric;
options.Password.RequireLowercase = settings.Authentication.PasswordRequireLowercase;
options.Password.RequireUppercase = settings.Authentication.PasswordRequireUppercase;
options.Password.RequireDigit = settings.Authentication.PasswordRequireDigit;
options.Password.RequiredLength = settings.Authentication.PasswordRequiredLength;
})
.AddRoles<Role>()
2024-10-15 20:48:06 -05:00
.AddEntityFrameworkStores<DatabaseContext>()
2024-10-18 19:15:05 -05:00
.AddSignInManager()
.AddDefaultTokenProviders();
2024-10-18 19:15:05 -05:00
var authBuilder = builder.Services.AddAuthentication(options =>
{
2024-10-18 19:15:05 -05:00
options.DefaultScheme = IdentityConstants.ApplicationScheme;
options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
/*options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;*/
2024-10-18 19:15:05 -05:00
});
foreach (var authenticationProvider in settings.Authentication.AuthenticationProviders)
{
try
{
switch (authenticationProvider.Type)
{
case AuthenticationProviderType.OAuth2:
authBuilder.AddOAuth(authenticationProvider);
break;
case AuthenticationProviderType.OpenIdConnect:
authBuilder.AddOpenIdConnect(authenticationProvider);
break;
case AuthenticationProviderType.Saml:
throw new NotImplementedException("SAML providers are not supported at this time.");
break;
}
}
catch (Exception ex)
{
Log.Error(ex, "Authentication Provider {Name} could not be registered",
authenticationProvider.Name);
}
}
2024-10-18 19:15:05 -05:00
authBuilder.AddIdentityCookies();
2025-01-06 17:03:40 -06:00
builder.Services.ConfigureApplicationCookie(options =>
{
options.LoginPath = "/Login";
options.LogoutPath = "/Logout";
options.AccessDeniedPath = "/AccessDenied";
});
2024-10-18 19:15:05 -05:00
authBuilder.AddJwtBearer(options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = false,
ValidateAudience = false,
// ValidAudience = configuration["JWT:ValidAudience"],
// ValidIssuer = configuration["JWT:ValidIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings.Authentication.TokenSecret))
};
});
Log.Debug("Initializing Controllers");
builder.Services.AddControllers().AddJsonOptions(x =>
{
x.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles;
});
Log.Debug("Initializing Hangfire");
builder.Services.AddHangfire(configuration =>
configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseInMemoryStorage());
builder.Services.AddHangfireServer();
builder.Services.AddFusionCache();
Log.Debug("Registering Swashbuckle");
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.CustomSchemaIds(type => type.ToString());
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Enter a valid access token",
Name = "Authorization",
Type = SecuritySchemeType.Http,
BearerFormat = "JWT",
Scheme = "Bearer"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[]{}
}
});
});
Log.Debug("Registering AntDesign Blazor");
builder.Services.AddAntDesign();
builder.Services.AddHttpClient();
Log.Debug("Registering Services");
2024-08-19 01:22:48 -05:00
builder.Services.AddSingleton<SDK.Client>(new SDK.Client("", ""));
builder.Services.AddSingleton<RepositoryFactory>();
2024-10-23 02:30:18 -05:00
builder.Services.AddScoped(typeof(Repository<>));
builder.Services.AddScoped<DatabaseServiceFactory>();
2024-10-23 02:30:18 -05:00
builder.Services.AddScoped<IdentityContextFactory>();
builder.Services.AddScoped<SettingService>();
2024-10-23 02:30:18 -05:00
builder.Services.AddScoped<ArchiveService>();
builder.Services.AddScoped<StorageLocationService>();
builder.Services.AddScoped<CategoryService>();
builder.Services.AddScoped<CollectionService>();
builder.Services.AddScoped<GameService>();
builder.Services.AddScoped<LibraryService>();
2024-10-23 02:30:18 -05:00
builder.Services.AddScoped<ScriptService>();
builder.Services.AddScoped<GenreService>();
builder.Services.AddScoped<PlatformService>();
builder.Services.AddScoped<KeyService>();
builder.Services.AddScoped<TagService>();
builder.Services.AddScoped<EngineService>();
builder.Services.AddScoped<CompanyService>();
builder.Services.AddScoped<IGDBService>();
builder.Services.AddScoped<ServerService>();
builder.Services.AddScoped<ServerConsoleService>();
builder.Services.AddScoped<GameSaveService>();
builder.Services.AddScoped<PlaySessionService>();
builder.Services.AddScoped<MediaService>();
builder.Services.AddScoped<RedistributableService>();
builder.Services.AddScoped<IMediaGrabberService, SteamGridDBMediaGrabber>();
builder.Services.AddScoped<UpdateService>();
builder.Services.AddScoped<IssueService>();
builder.Services.AddScoped<PageService>();
builder.Services.AddScoped<UserService>();
builder.Services.AddScoped<UserCustomFieldService>();
builder.Services.AddScoped<RoleService>();
2025-01-01 21:12:07 -06:00
builder.Services.AddScoped<Services.AuthenticationService>();
2024-10-23 02:30:18 -05:00
builder.Services.AddScoped<SetupService>();
builder.Services.AddSingleton<ServerProcessService>();
builder.Services.AddSingleton<IPXRelayService>();
if (settings.Beacon?.Enabled ?? false)
{
Log.Debug("The beacons have been lit! LANCommander calls for players!");
builder.Services.AddHostedService<BeaconService>();
}
builder.WebHost.UseStaticWebAssets();
builder.WebHost.UseKestrel(options =>
{
options.Limits.MaxRequestBodySize = long.MaxValue;
options.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(5);
});
builder.Services.Configure<FormOptions>(options =>
{
options.MultipartBodyLengthLimit = long.MaxValue;
});
Log.Debug("Building Application");
var app = builder.Build();
app.UseCors("CorsPolicy");
2025-01-04 18:07:37 -06:00
app.UseHttpsRedirection();
app.MapHub<GameServerHub>("/hubs/gameserver");
2025-01-06 17:59:53 -06:00
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
2024-07-25 21:25:47 -05:00
app.Use(async (context, next) =>
{
if (context.Request.Path.StartsWithSegments("/robots.txt"))
{
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync("User-agent: *\nDisallow: /Identity/");
}
else await next();
});
app.Use((context, next) =>
{
var headers = context.Response.Headers;
headers.Append("X-API-Version", UpdateService.GetCurrentVersion().ToString());
return next();
});
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
Log.Debug("App has been run in a development environment");
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseSwagger(options =>
{
options.RouteTemplate = "/openapi/{documentName}.json";
});
app.MapScalarApiReference();
app.UseHangfireDashboard();
// app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseMvcWithDefaultRoute();
Log.Debug("Registering Endpoints");
2024-07-25 21:25:47 -05:00
2024-08-29 00:19:56 -05:00
app.MapHub<LoggingHub>("/logging");
2024-10-18 19:15:05 -05:00
app.UseAntiforgery();
app.UseStaticFiles();
2025-01-04 01:53:16 -06:00
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedProto
});
2024-10-18 19:15:05 -05:00
app.MapRazorComponents<UI.App>()
2024-10-18 19:15:05 -05:00
.AddInteractiveServerRenderMode();
app.UseEndpoints(endpoints =>
{
endpoints.MapFallbackToPage("/_Host");
endpoints.MapControllers();
});
Log.Debug("Ensuring required directories exist");
if (!Directory.Exists(settings.UserSaves.StoragePath))
Directory.CreateDirectory(settings.UserSaves.StoragePath);
if (!Directory.Exists(settings.Update.StoragePath))
Directory.CreateDirectory(settings.Update.StoragePath);
if (!Directory.Exists("Snippets"))
Directory.CreateDirectory("Snippets");
2023-11-17 12:32:09 -06:00
if (!Directory.Exists("Backups"))
Directory.CreateDirectory("Backups");
// Migrate
Log.Debug("Migrating database if required");
if (DatabaseContext.Provider != DatabaseProvider.Unknown)
2023-11-17 12:32:09 -06:00
{
2024-10-12 18:36:00 -05:00
await using var scope = app.Services.CreateAsyncScope();
using var db = scope.ServiceProvider.GetService<DatabaseContext>();
if ((await db.Database.GetPendingMigrationsAsync()).Any())
{
2024-10-12 18:36:00 -05:00
if (DatabaseContext.Provider == DatabaseProvider.SQLite)
{
var dataSource = new SqliteConnectionStringBuilder(settings.DatabaseConnectionString).DataSource;
2023-11-17 12:32:09 -06:00
2024-10-12 18:36:00 -05:00
var backupName = Path.Combine("Backups", $"LANCommander.db.{DateTime.Now.ToString("dd-MM-yyyy-HH.mm.ss.bak")}");
2024-01-04 18:23:54 -06:00
2024-10-12 18:36:00 -05:00
if (File.Exists(dataSource))
{
Log.Information("Migrations pending, database will be backed up to {BackupName}", backupName);
File.Copy(dataSource, backupName);
}
}
2023-11-17 12:32:09 -06:00
2024-10-12 18:36:00 -05:00
await db.Database.MigrateAsync();
}
else
Log.Debug("No pending migrations are available. Skipping database migration.");
2024-10-12 18:36:00 -05:00
// Autostart any server processes
Log.Debug("Autostarting Servers");
var serverService = scope.ServiceProvider.GetService<ServerService>();
var serverProcessService = scope.ServiceProvider.GetService<ServerProcessService>();
foreach (var server in await serverService.GetAsync(s => s.Autostart && s.AutostartMethod == ServerAutostartMethod.OnApplicationStart))
{
2024-10-12 18:36:00 -05:00
try
{
Log.Debug("Autostarting server {ServerName} with a delay of {AutostartDelay} seconds", server.Name, server.AutostartDelay);
2024-10-12 18:36:00 -05:00
if (server.AutostartDelay > 0)
await Task.Delay(server.AutostartDelay);
2024-10-12 18:36:00 -05:00
serverProcessService.StartServerAsync(server.Id);
}
catch (Exception ex)
{
Log.Debug(ex, "An unexpected error occurred while trying to autostart the server {ServerName}", server.Name);
}
}
WIP fix for MySQL connection concurrency issues This is a large commit. There are a number of things that this commit does to try to fix various issues that were occurring when the database provider was set to MySQL: - The DAL `Repository` has been completely refactored to follow best practices. The repository is now being injected into services instead of the database context itself. This allows the DI to handle the repository's lifetime instead of creating a new repository for every transaction and sharing the context across repositories. As part of these changes, there is no more allowed usage of `IQueryable` and all service/repository methods must actually execute database queries before their return. This is to ensure that the context does not stay open longer than it needs to. Abusing `IQueryable`s by tossing them into Blazor components seems to be a big no-no. - Some deletion behaviors on relationships have been tweaked as MySQL wasn't able to apply migrations with behaviors that were contradictory. - A `ConnectionInterceptor` was added to try to keep track of `DatabaseContext` lifetimes. This is really only for debugging and should be put into `#if DEBUG` regions. This helped identify some potential issues where some contexts were basically never closing, causing the MySQL connector to not function. - Docs for generating migrations have been updated to reflect the addition of being able to specify the database provider and connection string when adding a migration, avoiding the need to edit `Settings.yml` - The application can now be put into a pause state on startup by adding the `--debugger` argument when used from the command line. When a debugger is attached, it resumes execution. - The application can now log to Seq when using debug build - Service lifetime on `DatabaseContext` has switched to transient. This may be reverted in the future. - Lazy loading has been disabled for debugging purposes. It didn't directly help the concurrency issues, but it needs to be tested individually to be re-enabled. - All usage of `UserManager`, `RoleManager`, and `SignInManager` have been removed from all controllers, pages, and Blazor components. Functionality has been moved to `UserService` and `RoleService`. This might have done the most amount of help, but could probably be improved upon in the future by not relying on them and instead having our own implementation. - Application startup migrations and server autostarts have been disabled temporarily. There might be an issue of `DatabaseContext` lifetimes that spawn from this.
2024-10-13 20:42:45 -05:00
await db.DisposeAsync();
await scope.DisposeAsync();
BackgroundJob.Enqueue<GenerateThumbnailsJob>(x => x.ExecuteAsync());
}
2024-10-12 18:36:00 -05:00
else
Log.Debug("No database provider has been setup, application is fresh and needs first time setup");
2024-11-05 20:20:03 -06:00
app.Run();
}
}
}