LANCommander/LANCommander.Server/Controllers/Api/KeysController.cs
Pat Hartl 2805f34449 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

197 lines
7.8 KiB
C#

using AutoMapper;
using LANCommander.Server.Data;
using LANCommander.Server.Data.Models;
using LANCommander.Server.Extensions;
using LANCommander.Server.Services;
using LANCommander.SDK.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Identity;
using LANCommander.Server.Models;
using LANCommander.SDK.Enums;
using Microsoft.EntityFrameworkCore;
namespace LANCommander.Server.Controllers.Api
{
[Authorize(AuthenticationSchemes = "Bearer")]
[Route("api/[controller]")]
[ApiController]
public class KeysController : BaseApiController
{
private readonly IMapper Mapper;
private readonly KeyService KeyService;
private readonly GameService GameService;
private readonly UserService UserService;
public KeysController(
ILogger<KeysController> logger,
IMapper mapper,
KeyService keyService,
GameService gameService,
UserService userService) : base(logger)
{
Mapper = mapper;
KeyService = keyService;
GameService = gameService;
UserService = userService;
}
[HttpPost]
public async Task<ActionResult<SDK.Models.Key>> Get(KeyRequest keyRequest)
{
return await GetAllocated(keyRequest.GameId, keyRequest);
}
/// <summary>
/// Get allocated key (or allocate new key) based on game's key allocation method
/// </summary>
/// <param name="id">ID of the game</param>
/// <param name="keyRequest"></param>
/// <returns>Allocated key</returns>
[HttpPost("GetAllocated/{id}")]
public async Task<ActionResult<SDK.Models.Key>> GetAllocated(Guid id, KeyRequest keyRequest)
{
try
{
Data.Models.Key key = null;
var user = await UserService.Get(User?.Identity?.Name);
var game = await GameService.Get(id);
if (game == null)
{
Logger.LogError("Requested game with ID {GameId} does not exist", keyRequest.GameId);
return NotFound();
}
switch (game.KeyAllocationMethod)
{
case KeyAllocationMethod.MacAddress:
key = game.Keys.FirstOrDefault(k => k.AllocationMethod == KeyAllocationMethod.MacAddress && k.ClaimedByMacAddress == keyRequest.MacAddress);
break;
case KeyAllocationMethod.UserAccount:
key = game.Keys.FirstOrDefault(k => k.AllocationMethod == KeyAllocationMethod.UserAccount && k.ClaimedByUser?.Id == user.Id);
break;
default:
Logger?.LogError("Unhandled key allocation method {KeyAllocationMethod}", game.KeyAllocationMethod);
return NotFound();
break;
}
if (key != null)
return Ok(Mapper.Map<SDK.Models.Key>(key));
else
return Ok(Mapper.Map<SDK.Models.Key>(await AllocateNewKey(id, keyRequest, game.KeyAllocationMethod)));
}
catch (Exception ex) {
Logger?.LogError(ex, "An unknown error occurred while trying to get an allocated key for game with ID {GameId}", id);
return NotFound();
}
}
/// <summary>
/// Allocate a new key based on game's key allocation method
/// </summary>
/// <param name="id">ID of the game</param>
/// <param name="keyRequest"></param>
/// <returns>Newly allocated key</returns>
[HttpPost("Allocate/{id}")]
public async Task<ActionResult<SDK.Models.Key>> Allocate(Guid id, KeyRequest keyRequest)
{
try
{
Data.Models.Key key = null;
var user = await UserService.Get(User?.Identity?.Name);
var game = await GameService.Get(id);
if (game == null)
{
Logger.LogError("Requested game with ID {GameId} does not exist", keyRequest.GameId);
return NotFound();
}
switch (game.KeyAllocationMethod)
{
case KeyAllocationMethod.MacAddress:
key = game.Keys.FirstOrDefault(k => k.AllocationMethod == KeyAllocationMethod.MacAddress && k.ClaimedByMacAddress == keyRequest.MacAddress);
break;
case KeyAllocationMethod.UserAccount:
key = game.Keys.FirstOrDefault(k => k.AllocationMethod == KeyAllocationMethod.UserAccount && k.ClaimedByUser?.Id == user.Id);
break;
default:
Logger?.LogError("Unhandled key allocation method {KeyAllocationMethod}", game.KeyAllocationMethod);
return NotFound();
break;
}
var availableKey = game.Keys.FirstOrDefault(k =>
(k.AllocationMethod == KeyAllocationMethod.MacAddress && String.IsNullOrWhiteSpace(k.ClaimedByMacAddress))
||
(k.AllocationMethod == KeyAllocationMethod.UserAccount && k.ClaimedByUser == null));
if (availableKey == null && key != null)
return Ok(Mapper.Map<SDK.Models.Key>(key));
else if (availableKey == null)
return NotFound();
else
{
if (key != null)
await KeyService.Release(key.Id);
switch (game.KeyAllocationMethod)
{
case KeyAllocationMethod.MacAddress:
key = await KeyService.Allocate(availableKey, keyRequest.MacAddress);
break;
case KeyAllocationMethod.UserAccount:
key = await KeyService.Allocate(availableKey, user);
break;
}
return Ok(Mapper.Map<SDK.Models.Key>(key));
}
}
catch (Exception ex) {
Logger.LogError(ex, "An unknown error occurred while trying to allocate a new key for game with ID {GameId}", id);
return NotFound();
}
}
/// <summary>
/// Allocate a new key using specified allocation method
/// </summary>
/// <param name="id">The ID of the game</param>
/// <param name="keyRequest"></param>
/// <param name="keyAllocationMethod"></param>
/// <returns>Allocated key</returns>
private async Task<SDK.Models.Key> AllocateNewKey(Guid id, KeyRequest keyRequest, KeyAllocationMethod keyAllocationMethod)
{
var user = await UserService.Get(User?.Identity?.Name);
var keys = await KeyService.Get(k => k.Game.Id == id);
var availableKey = keys.Where(k =>
(k.AllocationMethod == KeyAllocationMethod.MacAddress && String.IsNullOrWhiteSpace(k.ClaimedByMacAddress))
||
(k.AllocationMethod == KeyAllocationMethod.UserAccount && k.ClaimedByUser == null))
.FirstOrDefault();
if (availableKey == null)
return null;
if (keyAllocationMethod == KeyAllocationMethod.MacAddress)
return Mapper.Map<SDK.Models.Key>(await KeyService.Allocate(availableKey, keyRequest.MacAddress));
else if (keyAllocationMethod == KeyAllocationMethod.UserAccount)
return Mapper.Map<SDK.Models.Key>(await KeyService.Allocate(availableKey, user));
else
return null;
}
}
}