From b29de8c0eb5e09deddc3bac5ddbeb32a06377204 Mon Sep 17 00:00:00 2001 From: pkoelemij <13510367+pkoelemij@users.noreply.github.com> Date: Wed, 10 Jul 2024 21:27:02 +0200 Subject: [PATCH 1/2] Rework Eve Mapper Service and pull the caching to a seperate component (#285) * Add comment * Change styling * Remove unused usings * Add tests for EveMapperAccessHelper * Refactor EveMapperEntity cache clearing methods and write tests * Fix spelling * Rename to EveMapperEntity to EveMapperService * Add extra component for caching and add tests * Fix waiting in the EveMapperService * Remove creds * Rename cache tests * Fix namespace add tests for mapperservice * Fix test --- .../EveMapper/EveMapperAccessHelperTests.cs | 134 ++++ .../EveMapper/EveMapperCacheServiceTests.cs | 93 +++ .../EveMapper/EveMapperServiceTests.cs | 60 ++ .../WHHelper/EveWHMapperEntityTest.cs | 162 ++-- .../WHHelper/EveWHMapperHelperTest.cs | 60 +- src/WHMapper/Pages/Mapper/Add.cs | 2 +- .../Pages/Mapper/LinkInfos/Overview.cs | 2 +- src/WHMapper/Program.cs | 3 +- .../Repositories/IDefaultRepository.cs | 7 +- .../EveMapper/EveMapperAccessHelper.cs | 20 +- .../EveMapper/EveMapperCacheService.cs | 96 +++ .../Services/EveMapper/EveMapperEntity.cs | 725 ------------------ .../Services/EveMapper/EveMapperHelper.cs | 4 +- .../Services/EveMapper/EveMapperService.cs | 134 ++++ .../Services/EveMapper/EveMapperTracker.cs | 4 +- .../EveMapper/IEveMapperCacheService.cs | 28 + .../Services/EveMapper/IEveMapperEntity.cs | 40 - .../Services/EveMapper/IEveMapperService.cs | 18 + src/WHMapper/WHMapper.csproj | 1 - 19 files changed, 696 insertions(+), 897 deletions(-) create mode 100644 src/WHMapper.Tests/Services/EveMapper/EveMapperAccessHelperTests.cs create mode 100644 src/WHMapper.Tests/Services/EveMapper/EveMapperCacheServiceTests.cs create mode 100644 src/WHMapper.Tests/Services/EveMapper/EveMapperServiceTests.cs create mode 100644 src/WHMapper/Services/EveMapper/EveMapperCacheService.cs delete mode 100644 src/WHMapper/Services/EveMapper/EveMapperEntity.cs create mode 100644 src/WHMapper/Services/EveMapper/EveMapperService.cs create mode 100644 src/WHMapper/Services/EveMapper/IEveMapperCacheService.cs delete mode 100644 src/WHMapper/Services/EveMapper/IEveMapperEntity.cs create mode 100644 src/WHMapper/Services/EveMapper/IEveMapperService.cs diff --git a/src/WHMapper.Tests/Services/EveMapper/EveMapperAccessHelperTests.cs b/src/WHMapper.Tests/Services/EveMapper/EveMapperAccessHelperTests.cs new file mode 100644 index 00000000..5151a811 --- /dev/null +++ b/src/WHMapper.Tests/Services/EveMapper/EveMapperAccessHelperTests.cs @@ -0,0 +1,134 @@ +using AutoFixture.Xunit2; +using Moq; +using WHMapper.Models.Db; +using WHMapper.Models.DTO.EveAPI.Character; +using WHMapper.Repositories.WHAccesses; +using WHMapper.Repositories.WHAdmins; +using WHMapper.Services.EveAPI.Characters; +using WHMapper.Services.EveMapper; + +namespace WHMapper.Tests.Services.EveMapper +{ + public class EveMapperAccessHelperTests + { + #region IsEveMapperUserAccessAuthorized() + [Theory] + [InlineAutoMoqData(1)] + [InlineAutoMoqData(10000)] + [InlineAutoMoqData(int.MinValue)] + [InlineAutoMoqData(int.MaxValue)] + public async Task IfAccessRepositoryIsEmpty_WhenGettingState_ReturnsTrue( + int characterId, + [Frozen] Mock accessRepository, + EveMapperAccessHelper sut + ) + { + var accessRepositoryReturn = Task.FromResult(new List() as IEnumerable); + accessRepository.Setup(x => x.GetAll()).Returns(accessRepositoryReturn!); + + Assert.True(await sut.IsEveMapperUserAccessAuthorized(characterId)); + } + + [Theory, AutoDomainData] + public async Task IfWHAccessExistsAndCharacterIsNull_WhenGettingAccess_ReturnsFalse( + WHAccess wHAccess, + [Frozen] Mock accessRepository, + [Frozen] Mock characterServices, + EveMapperAccessHelper sut + ) + { + var accessRepositoryReturn = Task.FromResult(new List() { wHAccess } as IEnumerable); + accessRepository.Setup(x => x.GetAll()).Returns(accessRepositoryReturn!); + + Character? characterReturn = null!; + characterServices.Setup(x => x.GetCharacter(It.IsAny())).Returns(Task.FromResult(characterReturn)); + + Assert.False(await sut.IsEveMapperUserAccessAuthorized(1)); + } + + [Theory, AutoDomainData] + public async Task IfWHAccessExistsAndCharacterNotExists_WhenGettingAccess_ReturnsFalse( + WHAccess wHAccess, + [Frozen] Mock accessRepository, + EveMapperAccessHelper sut + ) + { + var accessRepositoryReturn = Task.FromResult(new List() { wHAccess } as IEnumerable); + accessRepository.Setup(x => x.GetAll()).Returns(accessRepositoryReturn!); + + Assert.False(await sut.IsEveMapperUserAccessAuthorized(1)); + } + + [Theory, AutoDomainData] + public async Task IfWHAccessExistsAndCharacterExists_WhenGettingAccess_ReturnsTrue( + WHAccess wHAccess, + [Frozen] Mock accessRepository, + EveMapperAccessHelper sut + ) + { + wHAccess.EveEntityId = 2; + var accessRepositoryReturn = Task.FromResult(new List() { wHAccess } as IEnumerable); + accessRepository.Setup(x => x.GetAll()).Returns(accessRepositoryReturn!); + + Assert.True(await sut.IsEveMapperUserAccessAuthorized(2)); + } + #endregion + + #region IsEveMapperAdminAccessAuthorized() + [Theory] + [InlineAutoMoqData(1)] + [InlineAutoMoqData(10000)] + [InlineAutoMoqData(int.MinValue)] + [InlineAutoMoqData(int.MaxValue)] + public async Task IfAccessRepositoryIsEmpty_WhenGettingAdminState_ReturnsTrue( + int characterId, + [Frozen] Mock accessRepository, + EveMapperAccessHelper sut + ) + { + var accessRepositoryReturn = Task.FromResult(new List() as IEnumerable); + accessRepository.Setup(x => x.GetAll()).Returns(accessRepositoryReturn!); + + Assert.True(await sut.IsEveMapperUserAccessAuthorized(characterId)); + } + + [Theory] + [InlineAutoMoqData(1)] + [InlineAutoMoqData(10000)] + [InlineAutoMoqData(int.MinValue)] + [InlineAutoMoqData(int.MaxValue)] + public async Task IfAccessRepositoryIsPopulatedGettingUnknownCharacterId_WhenGettingAdminState_ReturnsFalse( + int characterId, + WHAdmin wHAdmin, + [Frozen] Mock accessRepository, + EveMapperAccessHelper sut + ) + { + wHAdmin.EveCharacterId = 2; + var accessRepositoryReturn = Task.FromResult(new List() { wHAdmin } as IEnumerable); + accessRepository.Setup(x => x.GetAll()).Returns(accessRepositoryReturn!); + + Assert.True(await sut.IsEveMapperUserAccessAuthorized(characterId)); + } + + [Theory] + [InlineAutoMoqData(1)] + [InlineAutoMoqData(10000)] + [InlineAutoMoqData(int.MinValue)] + [InlineAutoMoqData(int.MaxValue)] + public async Task IfAccessRepositoryIsPopulatedGettingKnownCharacterId_WhenGettingAdminState_ReturnsFalse( + int characterId, + WHAdmin wHAdmin, + [Frozen] Mock accessRepository, + EveMapperAccessHelper sut + ) + { + wHAdmin.EveCharacterId = characterId; + var accessRepositoryReturn = Task.FromResult(new List() { wHAdmin } as IEnumerable); + accessRepository.Setup(x => x.GetAll()).Returns(accessRepositoryReturn!); + + Assert.True(await sut.IsEveMapperUserAccessAuthorized(characterId)); + } + #endregion + } +} diff --git a/src/WHMapper.Tests/Services/EveMapper/EveMapperCacheServiceTests.cs b/src/WHMapper.Tests/Services/EveMapper/EveMapperCacheServiceTests.cs new file mode 100644 index 00000000..85d4843c --- /dev/null +++ b/src/WHMapper.Tests/Services/EveMapper/EveMapperCacheServiceTests.cs @@ -0,0 +1,93 @@ +using AutoFixture.Xunit2; +using Moq; +using WHMapper.Models.DTO.EveMapper.EveEntity; +using WHMapper.Services.Cache; +using WHMapper.Services.EveMapper; + +namespace WHMapper.Tests.Services.EveMapper +{ + public class EveMapperCacheServiceTests + { + [Theory] + [InlineAutoMoqData(typeof(AllianceEntity), IEveMapperCacheService.REDIS_ALLIANCE_KEY)] + [InlineAutoMoqData(typeof(CorporationEntity), IEveMapperCacheService.REDIS_COORPORATION_KEY)] + [InlineAutoMoqData(typeof(CharactereEntity), IEveMapperCacheService.REDIS_CHARACTER_KEY)] + [InlineAutoMoqData(typeof(ShipEntity), IEveMapperCacheService.REDIS_SHIP_KEY)] + [InlineAutoMoqData(typeof(SystemEntity), IEveMapperCacheService.REDIS_SYSTEM_KEY)] + [InlineAutoMoqData(typeof(ConstellationEntity), IEveMapperCacheService.REDIS_CONSTELLATION_KEY)] + [InlineAutoMoqData(typeof(RegionEntity), IEveMapperCacheService.REDIS_REGION_KEY)] + [InlineAutoMoqData(typeof(StargateEntity), IEveMapperCacheService.REDIS_STARTGATE_KEY)] + [InlineAutoMoqData(typeof(GroupEntity), IEveMapperCacheService.REDIS_GROUP_KEY)] + [InlineAutoMoqData(typeof(WHEntity), IEveMapperCacheService.REDIS_WORMHOLE_KEY)] + [InlineAutoMoqData(typeof(SunEntity), IEveMapperCacheService.REDIS_SUN_KEY)] + public async Task IfEntityIsMapped_WhenClearingCache_CallsRemoveForCorrectEntity( + Type entityType, + string redisKey, + [Frozen] Mock cacheService, + EveMapperCacheService sut + ) + { + cacheService.Setup(x => x.Remove(It.Is(x => x.Contains(redisKey)))) + .Returns(Task.FromResult(true)) + .Verifiable(); + + var sutMethod = sut.GetType().GetMethod("ClearCacheAsync")!.MakeGenericMethod(entityType); + + var result = await (Task)sutMethod.Invoke(sut, null)!; + + Assert.True(result); + cacheService.Verify(x => x.Remove(It.Is(x => x.Contains(redisKey))), Times.Once); + cacheService.VerifyNoOtherCalls(); + } + + [Theory] + [InlineAutoMoqData(typeof(AllianceEntity), IEveMapperCacheService.REDIS_ALLIANCE_KEY)] + [InlineAutoMoqData(typeof(CorporationEntity), IEveMapperCacheService.REDIS_COORPORATION_KEY)] + [InlineAutoMoqData(typeof(CharactereEntity), IEveMapperCacheService.REDIS_CHARACTER_KEY)] + [InlineAutoMoqData(typeof(ShipEntity), IEveMapperCacheService.REDIS_SHIP_KEY)] + [InlineAutoMoqData(typeof(SystemEntity), IEveMapperCacheService.REDIS_SYSTEM_KEY)] + [InlineAutoMoqData(typeof(ConstellationEntity), IEveMapperCacheService.REDIS_CONSTELLATION_KEY)] + [InlineAutoMoqData(typeof(RegionEntity), IEveMapperCacheService.REDIS_REGION_KEY)] + [InlineAutoMoqData(typeof(StargateEntity), IEveMapperCacheService.REDIS_STARTGATE_KEY)] + [InlineAutoMoqData(typeof(GroupEntity), IEveMapperCacheService.REDIS_GROUP_KEY)] + [InlineAutoMoqData(typeof(WHEntity), IEveMapperCacheService.REDIS_WORMHOLE_KEY)] + [InlineAutoMoqData(typeof(SunEntity), IEveMapperCacheService.REDIS_SUN_KEY)] + public async Task IfCacheThrowsException_WhenClearingCache_ReturnsFalse( + Type entityType, + string redisKey, + [Frozen] Mock cacheService, + EveMapperCacheService sut + ) + { + cacheService.Setup(x => x.Remove(It.Is(x => x.Contains(redisKey)))) + .Throws() + .Verifiable(); + + var sutMethod = sut.GetType().GetMethod("ClearCacheAsync")!.MakeGenericMethod(entityType); + var result = await (Task)sutMethod.Invoke(sut, null)!; + + Assert.False(result); + cacheService.Verify(x => x.Remove(It.Is(x => x.Contains(redisKey))), Times.Once); + cacheService.VerifyNoOtherCalls(); + } + + [Theory] + [InlineAutoMoqData(typeof(AEveEntity))] + public async Task IfEntityIsNotMapped_WhenClearingCache_ReturnsFalse( + Type entityType, + [Frozen] Mock cacheService, + EveMapperCacheService sut + ) + { + cacheService.Setup(x => x.Remove(It.IsAny())) + .Returns(Task.FromResult(true)) + .Verifiable(); + + var sutMethod = sut.GetType().GetMethod("ClearCacheAsync")!.MakeGenericMethod(entityType); + var result = await (Task)sutMethod.Invoke(sut, null)!; + + Assert.False(result); + cacheService.VerifyNoOtherCalls(); + } + } +} diff --git a/src/WHMapper.Tests/Services/EveMapper/EveMapperServiceTests.cs b/src/WHMapper.Tests/Services/EveMapper/EveMapperServiceTests.cs new file mode 100644 index 00000000..8ce332c6 --- /dev/null +++ b/src/WHMapper.Tests/Services/EveMapper/EveMapperServiceTests.cs @@ -0,0 +1,60 @@ +using AutoFixture.Xunit2; +using Moq; +using WHMapper.Models.DTO.EveMapper.EveEntity; +using WHMapper.Services.EveAPI; +using WHMapper.Services.EveMapper; + +namespace WHMapper.Tests.Services.EveMapper +{ + public class EveMapperServiceTests + { + [Theory] + [AutoMoqData] + public async Task CacheContainsGroup_WhenGettingGroup_ReturnsItemFromCache( + [Frozen] Mock cacheService, + [Frozen] Mock apiService, + EveMapperService sut + ) + { + var groupEntity = new GroupEntity(1, new WHMapper.Models.DTO.EveAPI.Universe.Group(1, "1", true, 1, [])); + cacheService.Setup(x => x.GetAsync(1)) + .ReturnsAsync(groupEntity) + .Verifiable(); + + var result = await sut.GetGroup(1); + + Assert.NotNull(result); + Assert.Equal(groupEntity, result); + cacheService.Verify(x => x.GetAsync(1), Times.Once); + cacheService.VerifyNoOtherCalls(); + apiService.VerifyNoOtherCalls(); + } + + [Theory] + [AutoMoqData] + public async Task ApiReturnsGroup_WhenGettingGroup_ReturnsItemFromCache( + [Frozen] Mock cacheService, + [Frozen] Mock apiService, + EveMapperService sut + ) + { + GroupEntity groupEntity = null!; + cacheService.Setup(x => x.GetAsync(1)) + .ReturnsAsync(groupEntity) + .Verifiable(); + + var group = new WHMapper.Models.DTO.EveAPI.Universe.Group(1, "hi", true, 1, []); + apiService.Setup(x => x.UniverseServices.GetGroup(1)).ReturnsAsync(group); + + var result = await sut.GetGroup(1); + + Assert.NotNull(result); + cacheService.Verify(x => x.GetAsync(1), Times.Once); + cacheService.Verify(x => x.AddAsync(It.IsAny()), Times.Once); + cacheService.VerifyNoOtherCalls(); + + apiService.Verify(x => x.UniverseServices.GetGroup(1), Times.Once); + apiService.VerifyNoOtherCalls(); + } + } +} diff --git a/src/WHMapper.Tests/WHHelper/EveWHMapperEntityTest.cs b/src/WHMapper.Tests/WHHelper/EveWHMapperEntityTest.cs index f565738e..11a97ba5 100644 --- a/src/WHMapper.Tests/WHHelper/EveWHMapperEntityTest.cs +++ b/src/WHMapper.Tests/WHHelper/EveWHMapperEntityTest.cs @@ -1,4 +1,3 @@ - using System.Diagnostics; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Configuration; @@ -6,6 +5,7 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using WHMapper.Models.DTO; +using WHMapper.Models.DTO.EveMapper.EveEntity; using WHMapper.Services.Cache; using WHMapper.Services.EveAPI; using WHMapper.Services.EveMapper; @@ -44,7 +44,7 @@ public class EveWHMapperEntityTest private const int STARGATE_JITA_TO_MAURASI_ID = 50001248; private const string STARGATE_JITA_TO_MAURASI_NAME = "Maurasi"; - + private const int GROUPE_WORMHOLE_ID = 988; @@ -53,7 +53,8 @@ public class EveWHMapperEntityTest private const int WH_TYPE_ID1 = 30583; private const int WH_TYPE_ID2 = 30584; - private readonly IEveMapperEntity _whMapperEntity; + private readonly IEveMapperService _eveMapperService; + private readonly IEveMapperCacheService _eveMapperCacheService; public EveWHMapperEntityTest() { @@ -78,64 +79,67 @@ public EveWHMapperEntityTest() var httpclientfactory = provider.GetService(); IDistributedCache? _distriCache = provider.GetService(); - if(_distriCache != null && httpclientfactory!=null) + if (_distriCache != null && httpclientfactory != null) { var userInfoService = new EveUserInfosServices(null!); - ILogger logger = new NullLogger(); + ILogger logger = new NullLogger(); ILogger loggerAPI = new NullLogger(); ILogger loggerCacheService = new NullLogger(); + ILogger loggereveMapperCacheService = new NullLogger(); + + var cacheService = new CacheService(loggerCacheService, _distriCache); + _eveMapperCacheService = new EveMapperCacheService(loggereveMapperCacheService, cacheService); + var eveApiservice = new EveAPIServices(loggerAPI, httpclientfactory, new TokenProvider(), userInfoService); - _whMapperEntity = new EveMapperEntity(logger, - new CacheService(loggerCacheService, _distriCache), - new EveAPIServices(loggerAPI, httpclientfactory, new TokenProvider(), userInfoService)); + _eveMapperService = new EveMapperService(logger, _eveMapperCacheService, eveApiservice); } } } [Fact, Priority(1)] - - private async Task Get_Character_Test() - { - var clearing = await _whMapperEntity.ClearCharacterCache(); + + public async Task Get_Character_Test() + { + var clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); - - var character = await _whMapperEntity.GetCharacter(BAD_ID); + + var character = await _eveMapperService.GetCharacter(BAD_ID); Assert.Null(character); Stopwatch sw = new Stopwatch(); sw.Start(); - character = await _whMapperEntity.GetCharacter(CHARACTER_GOONS_ID); + character = await _eveMapperService.GetCharacter(CHARACTER_GOONS_ID); sw.Stop(); Assert.NotNull(character); Assert.Equal(CHARACTER_GOONS_NAME, character.Name); long without_cache = sw.ElapsedMilliseconds; - + //Check if cache is working sw.Reset(); sw.Restart(); - character = await _whMapperEntity.GetCharacter(CHARACTER_GOONS_ID); + character = await _eveMapperService.GetCharacter(CHARACTER_GOONS_ID); sw.Stop(); long with_cache = sw.ElapsedMilliseconds; Assert.NotNull(character); Assert.Equal(CHARACTER_GOONS_NAME, character.Name); Assert.True(with_cache < without_cache); - clearing = await _whMapperEntity.ClearCharacterCache(); + clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); } [Fact, Priority(2)] - private async Task Get_Corporation_Test() + public async Task Get_Corporation_Test() { - var clearing = await _whMapperEntity.ClearCorporationCache(); + var clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); - var corporation = await _whMapperEntity.GetCorporation(BAD_ID); + var corporation = await _eveMapperService.GetCorporation(BAD_ID); Assert.Null(corporation); Stopwatch sw = new Stopwatch(); sw.Start(); - corporation = await _whMapperEntity.GetCorporation(CORPORATION_GOONS_ID); + corporation = await _eveMapperService.GetCorporation(CORPORATION_GOONS_ID); sw.Stop(); Assert.NotNull(corporation); Assert.Equal(CORPORATION_GOONS_NAME, corporation.Name); @@ -144,29 +148,29 @@ private async Task Get_Corporation_Test() //Check if cache is working sw.Reset(); sw.Restart(); - corporation = await _whMapperEntity.GetCorporation(CORPORATION_GOONS_ID); + corporation = await _eveMapperService.GetCorporation(CORPORATION_GOONS_ID); sw.Stop(); long with_cache = sw.ElapsedMilliseconds; Assert.NotNull(corporation); Assert.Equal(CORPORATION_GOONS_NAME, corporation.Name); Assert.True(with_cache < without_cache); - clearing = await _whMapperEntity.ClearCorporationCache(); + clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); } [Fact, Priority(3)] - private async Task Get_Alliance_Test() + public async Task Get_Alliance_Test() { - var clearing = await _whMapperEntity.ClearAllianceCache(); + var clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); - var alliance = await _whMapperEntity.GetAlliance(BAD_ID); + var alliance = await _eveMapperService.GetAlliance(BAD_ID); Assert.Null(alliance); Stopwatch sw = new Stopwatch(); sw.Start(); - alliance = await _whMapperEntity.GetAlliance(ALLIANCE_GOONS_ID); + alliance = await _eveMapperService.GetAlliance(ALLIANCE_GOONS_ID); sw.Stop(); Assert.NotNull(alliance); Assert.Equal(ALLIANCE_GOONS_NAME, alliance.Name); @@ -175,29 +179,29 @@ private async Task Get_Alliance_Test() //Check if cache is working sw.Reset(); sw.Restart(); - alliance = await _whMapperEntity.GetAlliance(ALLIANCE_GOONS_ID); + alliance = await _eveMapperService.GetAlliance(ALLIANCE_GOONS_ID); sw.Stop(); long with_cache = sw.ElapsedMilliseconds; Assert.NotNull(alliance); Assert.Equal(ALLIANCE_GOONS_NAME, alliance.Name); Assert.True(with_cache < without_cache); - clearing = await _whMapperEntity.ClearAllianceCache(); + clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); } [Fact, Priority(4)] - private async Task Get_Ship_Test() + public async Task Get_Ship_Test() { - var clearing = await _whMapperEntity.ClearShipCache(); + var clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); - var ship = await _whMapperEntity.GetShip(BAD_ID); + var ship = await _eveMapperService.GetShip(BAD_ID); Assert.Null(ship); Stopwatch sw = new Stopwatch(); sw.Start(); - ship = await _whMapperEntity.GetShip(SHIP_RIFTER_ID); + ship = await _eveMapperService.GetShip(SHIP_RIFTER_ID); sw.Stop(); Assert.NotNull(ship); Assert.Equal(SHIP_RIFTER_NAME, ship.Name); @@ -206,29 +210,29 @@ private async Task Get_Ship_Test() //Check if cache is working sw.Reset(); sw.Restart(); - ship = await _whMapperEntity.GetShip(SHIP_RIFTER_ID); + ship = await _eveMapperService.GetShip(SHIP_RIFTER_ID); sw.Stop(); long with_cache = sw.ElapsedMilliseconds; Assert.NotNull(ship); Assert.Equal(SHIP_RIFTER_NAME, ship.Name); Assert.True(with_cache < without_cache); - clearing = await _whMapperEntity.ClearShipCache(); + clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); } [Fact, Priority(5)] - private async Task Get_System_Test() + public async Task Get_System_Test() { - var clearing = await _whMapperEntity.ClearSystemCache(); + var clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); - var system = await _whMapperEntity.GetSystem(BAD_ID); + var system = await _eveMapperService.GetSystem(BAD_ID); Assert.Null(system); Stopwatch sw = new Stopwatch(); sw.Start(); - system = await _whMapperEntity.GetSystem(SYSTEM_JITA_ID); + system = await _eveMapperService.GetSystem(SYSTEM_JITA_ID); sw.Stop(); Assert.NotNull(system); Assert.Equal(SYSTEM_JITA_NAME, system.Name); @@ -237,29 +241,29 @@ private async Task Get_System_Test() //Check if cache is working sw.Reset(); sw.Restart(); - system = await _whMapperEntity.GetSystem(SYSTEM_JITA_ID); + system = await _eveMapperService.GetSystem(SYSTEM_JITA_ID); sw.Stop(); long with_cache = sw.ElapsedMilliseconds; Assert.NotNull(system); Assert.Equal(SYSTEM_JITA_NAME, system.Name); Assert.True(with_cache < without_cache); - clearing = await _whMapperEntity.ClearSystemCache(); + clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); } [Fact, Priority(6)] - private async Task Get_Constellation_Test() + public async Task Get_Constellation_Test() { - var clearing = await _whMapperEntity.ClearConstellationCache(); + var clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); - var constellation = await _whMapperEntity.GetConstellation(BAD_ID); + var constellation = await _eveMapperService.GetConstellation(BAD_ID); Assert.Null(constellation); Stopwatch sw = new Stopwatch(); sw.Start(); - constellation = await _whMapperEntity.GetConstellation(CONSTELLATION_Kimotoro_ID); + constellation = await _eveMapperService.GetConstellation(CONSTELLATION_Kimotoro_ID); sw.Stop(); Assert.NotNull(constellation); Assert.Equal(CONSTELLATION_Kimotoro_NAME, constellation.Name); @@ -268,29 +272,29 @@ private async Task Get_Constellation_Test() //Check if cache is working sw.Reset(); sw.Restart(); - constellation = await _whMapperEntity.GetConstellation(CONSTELLATION_Kimotoro_ID); + constellation = await _eveMapperService.GetConstellation(CONSTELLATION_Kimotoro_ID); sw.Stop(); long with_cache = sw.ElapsedMilliseconds; Assert.NotNull(constellation); Assert.Equal(CONSTELLATION_Kimotoro_NAME, constellation.Name); Assert.True(with_cache < without_cache); - clearing = await _whMapperEntity.ClearConstellationCache(); + clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); } [Fact, Priority(7)] - private async Task Get_Region_Test() + public async Task Get_Region_Test() { - var clearing = await _whMapperEntity.ClearRegionCache(); + var clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); - var region = await _whMapperEntity.GetRegion(BAD_ID); + var region = await _eveMapperService.GetRegion(BAD_ID); Assert.Null(region); Stopwatch sw = new Stopwatch(); sw.Start(); - region = await _whMapperEntity.GetRegion(REGION_THE_FORGE_ID); + region = await _eveMapperService.GetRegion(REGION_THE_FORGE_ID); sw.Stop(); Assert.NotNull(region); Assert.Equal(REGION_THE_FORGE_NAME, region.Name); @@ -299,29 +303,29 @@ private async Task Get_Region_Test() //Check if cache is working sw.Reset(); sw.Restart(); - region = await _whMapperEntity.GetRegion(REGION_THE_FORGE_ID); + region = await _eveMapperService.GetRegion(REGION_THE_FORGE_ID); sw.Stop(); long with_cache = sw.ElapsedMilliseconds; Assert.NotNull(region); Assert.Equal(REGION_THE_FORGE_NAME, region.Name); Assert.True(with_cache < without_cache); - clearing = await _whMapperEntity.ClearRegionCache(); + clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); } [Fact, Priority(8)] - private async Task Get_Stargate_Test() + public async Task Get_Stargate_Test() { - var clearing = await _whMapperEntity.ClearStargateCache(); + var clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); - var stargate = await _whMapperEntity.GetStargate(BAD_ID); + var stargate = await _eveMapperService.GetStargate(BAD_ID); Assert.Null(stargate); Stopwatch sw = new Stopwatch(); sw.Start(); - stargate = await _whMapperEntity.GetStargate(STARGATE_JITA_TO_MAURASI_ID); + stargate = await _eveMapperService.GetStargate(STARGATE_JITA_TO_MAURASI_ID); sw.Stop(); Assert.NotNull(stargate); Assert.Equal(SYSTEM_JITA_ID, stargate.SourceId); @@ -331,7 +335,7 @@ private async Task Get_Stargate_Test() //Check if cache is working sw.Reset(); sw.Restart(); - stargate = await _whMapperEntity.GetStargate(STARGATE_JITA_TO_MAURASI_ID); + stargate = await _eveMapperService.GetStargate(STARGATE_JITA_TO_MAURASI_ID); sw.Stop(); long with_cache = sw.ElapsedMilliseconds; Assert.NotNull(stargate); @@ -339,22 +343,22 @@ private async Task Get_Stargate_Test() Assert.Equal(SYSTEM_JITA_ID, stargate.SourceId); Assert.True(with_cache < without_cache); - clearing = await _whMapperEntity.ClearStargateCache(); + clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); } [Fact, Priority(9)] - private async Task Get_Group_Test() + public async Task Get_Group_Test() { - var clearing = await _whMapperEntity.ClearGroupCache(); + var clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); - var group = await _whMapperEntity.GetGroup(BAD_ID); + var group = await _eveMapperService.GetGroup(BAD_ID); Assert.Null(group); Stopwatch sw = new Stopwatch(); sw.Start(); - group = await _whMapperEntity.GetGroup(GROUPE_WORMHOLE_ID); + group = await _eveMapperService.GetGroup(GROUPE_WORMHOLE_ID); sw.Stop(); Assert.NotNull(group); Assert.NotEmpty(group.Types); @@ -364,7 +368,7 @@ private async Task Get_Group_Test() //Check if cache is working sw.Reset(); sw.Restart(); - group = await _whMapperEntity.GetGroup(GROUPE_WORMHOLE_ID); + group = await _eveMapperService.GetGroup(GROUPE_WORMHOLE_ID); sw.Stop(); long with_cache = sw.ElapsedMilliseconds; Assert.NotNull(group); @@ -372,22 +376,22 @@ private async Task Get_Group_Test() Assert.Equal(GROUPE_WORMHOLE_ID, group.Id); Assert.True(with_cache < without_cache); - clearing = await _whMapperEntity.ClearGroupCache(); + clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); } [Fact, Priority(10)] - private async Task Get_Wormhole_Test() + public async Task Get_Wormhole_Test() { - var clearing = await _whMapperEntity.ClearWormholeCache(); + var clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); - var wormhole = await _whMapperEntity.GetWormhole(BAD_ID); + var wormhole = await _eveMapperService.GetWormhole(BAD_ID); Assert.Null(wormhole); Stopwatch sw = new Stopwatch(); sw.Start(); - wormhole = await _whMapperEntity.GetWormhole(WH_TYPE_ID1); + wormhole = await _eveMapperService.GetWormhole(WH_TYPE_ID1); sw.Stop(); Assert.NotNull(wormhole); Assert.Equal(WH_TYPE_ID1, wormhole.Id); @@ -396,29 +400,29 @@ private async Task Get_Wormhole_Test() //Check if cache is working sw.Reset(); sw.Restart(); - wormhole = await _whMapperEntity.GetWormhole(WH_TYPE_ID1); + wormhole = await _eveMapperService.GetWormhole(WH_TYPE_ID1); sw.Stop(); long with_cache = sw.ElapsedMilliseconds; Assert.NotNull(wormhole); Assert.Equal(WH_TYPE_ID1, wormhole.Id); Assert.True(with_cache < without_cache); - clearing = await _whMapperEntity.ClearWormholeCache(); + clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); } [Fact, Priority(11)] - private async Task Get_Sun_Test() + public async Task Get_Sun_Test() { - var clearing = await _whMapperEntity.ClearSunCache(); + var clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); - var sun = await _whMapperEntity.GetSun(BAD_ID); + var sun = await _eveMapperService.GetSun(BAD_ID); Assert.Null(sun); Stopwatch sw = new Stopwatch(); sw.Start(); - sun = await _whMapperEntity.GetSun(SECONDARY_SUN_ID_TYPE); + sun = await _eveMapperService.GetSun(SECONDARY_SUN_ID_TYPE); sw.Stop(); Assert.NotNull(sun); Assert.Equal(SECONDARY_SUN_ID_TYPE, sun.Id); @@ -427,16 +431,14 @@ private async Task Get_Sun_Test() //Check if cache is working sw.Reset(); sw.Restart(); - sun = await _whMapperEntity.GetSun(SECONDARY_SUN_ID_TYPE); + sun = await _eveMapperService.GetSun(SECONDARY_SUN_ID_TYPE); sw.Stop(); long with_cache = sw.ElapsedMilliseconds; Assert.NotNull(sun); Assert.Equal(SECONDARY_SUN_ID_TYPE, sun.Id); Assert.True(with_cache < without_cache); - clearing = await _whMapperEntity.ClearSunCache(); + clearing = await _eveMapperCacheService.ClearCacheAsync(); Assert.True(clearing); } - - } \ No newline at end of file diff --git a/src/WHMapper.Tests/WHHelper/EveWHMapperHelperTest.cs b/src/WHMapper.Tests/WHHelper/EveWHMapperHelperTest.cs index b9e634f8..a2327186 100644 --- a/src/WHMapper.Tests/WHHelper/EveWHMapperHelperTest.cs +++ b/src/WHMapper.Tests/WHHelper/EveWHMapperHelperTest.cs @@ -21,7 +21,6 @@ namespace WHMapper.Tests.WHHelper; - [Collection("C6-WHHelper")] [TestCaseOrderer(PriorityOrderer.Name, PriorityOrderer.Assembly)] public class EveWHMapperHelperTest @@ -51,15 +50,14 @@ public class EveWHMapperHelperTest private const WHEffect SOLAR_SYSTEM_WH_EFFECT = WHEffect.Pulsar; private const string SOLAR_SYSTEM_WH_STATICS = "D845"; - private const string REGION_WH_C1_NAME = "A-R00001"; private const string SOLAR_SYSTEM_WH_C1_NAME = "J100744"; private const string REGION_WH_C2_NAME = "B-R00004"; - private const string SOLAR_SYSTEM_WH_C2_NAME = "J101524"; + private const string SOLAR_SYSTEM_WH_C2_NAME = "J101524"; private const string REGION_WH_C4_NAME = "D-R00016"; - private const string SOLAR_SYSTEM_WH_C4_NAME = "J104754"; + private const string SOLAR_SYSTEM_WH_C4_NAME = "J104754"; private const string REGION_WH_C5_NAME = "E-R00024"; private const string SOLAR_SYSTEM_WH_C5_NAME = "J103251"; @@ -121,16 +119,18 @@ public EveWHMapperHelperTest() ILogger loggerAPI = new NullLogger(); ILogger loggerWHNoteRepository = new NullLogger(); ILogger loggerCacheService = new NullLogger(); - ILogger loggerEveMapperEntity = new NullLogger(); + ILogger loggerEveMapperEntity = new NullLogger(); ILogger loggerSdeDataSupplier = new NullLogger(); + ILogger loggereveMapperCacheService = new NullLogger(); if (httpclientfactory != null && _contextFactory != null && _distriCache != null) { ICacheService cacheService = new CacheService(loggerCacheService, _distriCache); + IEveMapperCacheService eveMapperCacheService = new EveMapperCacheService(loggereveMapperCacheService, cacheService); var userInfoService = new EveUserInfosServices(null!); var apiServices = new EveAPIServices(loggerAPI, httpclientfactory, new TokenProvider(), userInfoService); - var mapperEntity = new EveMapperEntity(loggerEveMapperEntity, cacheService, apiServices); + var mapperEntity = new EveMapperService(loggerEveMapperEntity, eveMapperCacheService, apiServices); IFileSystem fileSystem = new FileSystem(); HttpClient httpClient = new HttpClient() { BaseAddress = new Uri(configuration.GetValue("SdeDataSupplier:BaseUrl")) }; @@ -162,62 +162,61 @@ public Task Is_Wormhole() return Task.CompletedTask; } - [Fact, Priority(2)] public async Task Get_Wormhole_Class() { - var result_C3_Bis= await _whEveMapper.GetWHClass(new SystemEntity(31001123, SOLAR_SYSTEM_WH_NAME,CONSTELLATION_WH_ID,-1.0f, new int[]{})); + var result_C3_Bis = await _whEveMapper.GetWHClass(new SystemEntity(31001123, SOLAR_SYSTEM_WH_NAME, CONSTELLATION_WH_ID, -1.0f, new int[] { })); Assert.Equal(EveSystemType.C3, result_C3_Bis); - var result_HS = await _whEveMapper.GetWHClass(REGION_JITA_NAME, "UNUSED", SOLAR_SYSTEM_JITA_NAME,1.0f); + var result_HS = await _whEveMapper.GetWHClass(REGION_JITA_NAME, "UNUSED", SOLAR_SYSTEM_JITA_NAME, 1.0f); Assert.Equal(EveSystemType.HS, result_HS); - var result_LS = await _whEveMapper.GetWHClass(REGION_AMAMAKE_NAME, "UNUSED", SOLAR_SYSTEM_AMAMAKE_NAME,0.4f); + var result_LS = await _whEveMapper.GetWHClass(REGION_AMAMAKE_NAME, "UNUSED", SOLAR_SYSTEM_AMAMAKE_NAME, 0.4f); Assert.Equal(EveSystemType.LS, result_LS); - var result_NS = await _whEveMapper.GetWHClass(REGION_FDMLJ_NAME, "UNUSED", SOLAR_SYSTEM_FDMLJ_NAME,0.0f); + var result_NS = await _whEveMapper.GetWHClass(REGION_FDMLJ_NAME, "UNUSED", SOLAR_SYSTEM_FDMLJ_NAME, 0.0f); Assert.Equal(EveSystemType.NS, result_NS); - var result_C1 = await _whEveMapper.GetWHClass(REGION_WH_C1_NAME, "UNUSED", SOLAR_SYSTEM_WH_C1_NAME,-1.0f); + var result_C1 = await _whEveMapper.GetWHClass(REGION_WH_C1_NAME, "UNUSED", SOLAR_SYSTEM_WH_C1_NAME, -1.0f); Assert.Equal(EveSystemType.C1, result_C1); - var result_C2 = await _whEveMapper.GetWHClass(REGION_WH_C2_NAME, "UNUSED", SOLAR_SYSTEM_WH_C2_NAME,-1.0f); + var result_C2 = await _whEveMapper.GetWHClass(REGION_WH_C2_NAME, "UNUSED", SOLAR_SYSTEM_WH_C2_NAME, -1.0f); Assert.Equal(EveSystemType.C2, result_C2); - var result_C3 = await _whEveMapper.GetWHClass(REGION_WH_NAME, "UNUSED", SOLAR_SYSTEM_WH_NAME,-1.0f); + var result_C3 = await _whEveMapper.GetWHClass(REGION_WH_NAME, "UNUSED", SOLAR_SYSTEM_WH_NAME, -1.0f); Assert.Equal(EveSystemType.C3, result_C3); - var result_C4 = await _whEveMapper.GetWHClass(REGION_WH_C4_NAME, "UNUSED", SOLAR_SYSTEM_WH_C4_NAME,-1.0f); + var result_C4 = await _whEveMapper.GetWHClass(REGION_WH_C4_NAME, "UNUSED", SOLAR_SYSTEM_WH_C4_NAME, -1.0f); Assert.Equal(EveSystemType.C4, result_C4); - var result_C5 = await _whEveMapper.GetWHClass(REGION_WH_C5_NAME, "UNUSED", SOLAR_SYSTEM_WH_C5_NAME,-1.0f); + var result_C5 = await _whEveMapper.GetWHClass(REGION_WH_C5_NAME, "UNUSED", SOLAR_SYSTEM_WH_C5_NAME, -1.0f); Assert.Equal(EveSystemType.C5, result_C5); - var result_C6 = await _whEveMapper.GetWHClass(REGION_WH_C6_NAME, "UNUSED", SOLAR_SYSTEM_WH_C6_NAME,-1.0f); + var result_C6 = await _whEveMapper.GetWHClass(REGION_WH_C6_NAME, "UNUSED", SOLAR_SYSTEM_WH_C6_NAME, -1.0f); Assert.Equal(EveSystemType.C6, result_C6); - var result_THERA= await _whEveMapper.GetWHClass(REGION_WH_THERA_NAME, "UNUSED", SOLAR_SYSTEM_WH_THERA_NAME,-1.0f); + var result_THERA = await _whEveMapper.GetWHClass(REGION_WH_THERA_NAME, "UNUSED", SOLAR_SYSTEM_WH_THERA_NAME, -1.0f); Assert.Equal(EveSystemType.Thera, result_THERA); - var result_C13 = await _whEveMapper.GetWHClass(REGION_WH_C13_NAME, "UNUSED", SOLAR_SYSTEM_WH_C13_NAME,-1.0f); + var result_C13 = await _whEveMapper.GetWHClass(REGION_WH_C13_NAME, "UNUSED", SOLAR_SYSTEM_WH_C13_NAME, -1.0f); Assert.Equal(EveSystemType.C13, result_C13); - var result_C14 = await _whEveMapper.GetWHClass(REGION_SPECIAL, "UNUSED", C14_NAME,-1.0f); + var result_C14 = await _whEveMapper.GetWHClass(REGION_SPECIAL, "UNUSED", C14_NAME, -1.0f); Assert.Equal(EveSystemType.C14, result_C14); - var result_C15 = await _whEveMapper.GetWHClass(REGION_SPECIAL, "UNUSED", C15_NAME,-1.0f); + var result_C15 = await _whEveMapper.GetWHClass(REGION_SPECIAL, "UNUSED", C15_NAME, -1.0f); Assert.Equal(EveSystemType.C15, result_C15); - var result_C16 = await _whEveMapper.GetWHClass(REGION_SPECIAL, "UNUSED", C16_NAME,-1.0f); + var result_C16 = await _whEveMapper.GetWHClass(REGION_SPECIAL, "UNUSED", C16_NAME, -1.0f); Assert.Equal(EveSystemType.C16, result_C16); - var result_C17 = await _whEveMapper.GetWHClass(REGION_SPECIAL, "UNUSED", C17_NAME,-1.0f); + var result_C17 = await _whEveMapper.GetWHClass(REGION_SPECIAL, "UNUSED", C17_NAME, -1.0f); Assert.Equal(EveSystemType.C17, result_C17); - var result_C18 = await _whEveMapper.GetWHClass(REGION_SPECIAL, "UNUSED", C18_NAME,-1.0f); + var result_C18 = await _whEveMapper.GetWHClass(REGION_SPECIAL, "UNUSED", C18_NAME, -1.0f); Assert.Equal(EveSystemType.C18, result_C18); - var result_POCHVEN = await _whEveMapper.GetWHClass(REGION_WH_POCHVEN_NAME, "UNUSED", SOLAR_SYSTEM_WH_POCHVEN_NAME,-1.0f); + var result_POCHVEN = await _whEveMapper.GetWHClass(REGION_WH_POCHVEN_NAME, "UNUSED", SOLAR_SYSTEM_WH_POCHVEN_NAME, -1.0f); Assert.Equal(EveSystemType.Pochven, result_POCHVEN); } @@ -228,14 +227,13 @@ public async Task Define_Eve_System_Node_Model() Assert.NotNull(jita_result); Assert.Equal(EveSystemType.HS, jita_result.SystemType); - var wh_result = await _whEveMapper.DefineEveSystemNodeModel(new WHSystem(DEFAULT_MAP_ID, SOLAR_SYSTEM_WH_ID, SOLAR_SYSTEM_WH_NAME, -1.0f)); Assert.Equal(SOLAR_SYSTEM_WH_CLASS, wh_result.SystemType); Assert.NotEqual(WHEffect.None, wh_result.Effect); Assert.Equal(SOLAR_SYSTEM_WH_EFFECT, wh_result.Effect); } - [Fact,Priority(4)] + [Fact, Priority(4)] public async Task Test_BUG_207() { var result = await _whEveMapper.DefineEveSystemNodeModel(new WHSystem(DEFAULT_MAP_ID, 31001531, C4_NAME_BUG_207, -1.0f)); @@ -246,17 +244,15 @@ public async Task Test_BUG_207() public async Task Is_Route_Via_WH() { var src = new SystemEntity(SOLAR_SYSTEM_WH_ID, SOLAR_SYSTEM_WH_NAME, CONSTELLATION_WH_ID, -1.0f, new int[] { });//fake for test - var dst = new SystemEntity(SOLAR_SYSTEM_JITA_ID,SOLAR_SYSTEM_JITA_NAME, CONSTALLATION_JITA_ID, -1.0f, new int[] {50001248 });//fake for test + var dst = new SystemEntity(SOLAR_SYSTEM_JITA_ID, SOLAR_SYSTEM_JITA_NAME, CONSTALLATION_JITA_ID, -1.0f, new int[] { 50001248 });//fake for test var result = await _whEveMapper.IsRouteViaWH(src, dst); Assert.True(result); - var src2 = new SystemEntity(SOLAR_SYSTEM_JITA_ID, SOLAR_SYSTEM_JITA_NAME, CONSTALLATION_JITA_ID, -1.0f, new int[] { 50001248}); - var dst2 = new SystemEntity(30000140, "Maurasi", CONSTALLATION_JITA_ID, -1.0f, new int[] { 50000802}); + var src2 = new SystemEntity(SOLAR_SYSTEM_JITA_ID, SOLAR_SYSTEM_JITA_NAME, CONSTALLATION_JITA_ID, -1.0f, new int[] { 50001248 }); + var dst2 = new SystemEntity(30000140, "Maurasi", CONSTALLATION_JITA_ID, -1.0f, new int[] { 50000802 }); var result_wh = await _whEveMapper.IsRouteViaWH(src2, dst2); Assert.False(result_wh); } } - - diff --git a/src/WHMapper/Pages/Mapper/Add.cs b/src/WHMapper/Pages/Mapper/Add.cs index 2d842569..36c4b718 100644 --- a/src/WHMapper/Pages/Mapper/Add.cs +++ b/src/WHMapper/Pages/Mapper/Add.cs @@ -42,7 +42,7 @@ public partial class Add :ComponentBase private IEveMapperHelper MapperServices { get; set; } = null!; [Inject] - private IEveMapperEntity EveMapperEntity { get; set; } = null!; + private IEveMapperService EveMapperEntity { get; set; } = null!; [Inject] IWHSystemRepository DbWHSystems { get; set; } = null!; diff --git a/src/WHMapper/Pages/Mapper/LinkInfos/Overview.cs b/src/WHMapper/Pages/Mapper/LinkInfos/Overview.cs index 9f07569e..0d1fc154 100644 --- a/src/WHMapper/Pages/Mapper/LinkInfos/Overview.cs +++ b/src/WHMapper/Pages/Mapper/LinkInfos/Overview.cs @@ -25,7 +25,7 @@ public partial class Overview : ComponentBase private IWHColorHelper? WHColorHelper { get; set; } [Inject] - private IEveMapperEntity EveMapperEntity { get; set; } = null!; + private IEveMapperService EveMapperEntity { get; set; } = null!; [Parameter] public EveSystemLinkModel CurrentSystemLink {get;set;}= null!; diff --git a/src/WHMapper/Program.cs b/src/WHMapper/Program.cs index 4e3925c1..1cb9a663 100644 --- a/src/WHMapper/Program.cs +++ b/src/WHMapper/Program.cs @@ -212,7 +212,8 @@ private static void Main(string[] args) #endregion #region WH HELPER - builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/src/WHMapper/Repositories/IDefaultRepository.cs b/src/WHMapper/Repositories/IDefaultRepository.cs index 03dba532..d3c31b87 100644 --- a/src/WHMapper/Repositories/IDefaultRepository.cs +++ b/src/WHMapper/Repositories/IDefaultRepository.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace WHMapper.Repositories +namespace WHMapper.Repositories { public interface IDefaultRepository { diff --git a/src/WHMapper/Services/EveMapper/EveMapperAccessHelper.cs b/src/WHMapper/Services/EveMapper/EveMapperAccessHelper.cs index 0b9a5884..0c901ca1 100644 --- a/src/WHMapper/Services/EveMapper/EveMapperAccessHelper.cs +++ b/src/WHMapper/Services/EveMapper/EveMapperAccessHelper.cs @@ -22,19 +22,24 @@ public async Task IsEveMapperUserAccessAuthorized(int eveCharacterId) { var userAccesses = await _accessRepo.GetAll(); + //If there is no user access registered return true, this is the probably the first user using the tool. if (userAccesses?.Count() == 0) + { return true; + } else { var character = await _characterServices.GetCharacter(eveCharacterId); if (character == null) return false; - var res = userAccesses?.FirstOrDefault(x => (x.EveEntityId == eveCharacterId && x.EveEntity == WHAccessEntity.Character) || (x.EveEntityId == character.CorporationId && x.EveEntity == WHAccessEntity.Corporation) || (x.EveEntityId == character.AllianceId && x.EveEntity == WHAccessEntity.Alliance)); - - if (res == null) - return false;//todo check alliance and corpo and add db methodes + var result = userAccesses?.FirstOrDefault(x => + (x.EveEntityId == eveCharacterId && x.EveEntity == WHAccessEntity.Character) || + (x.EveEntityId == character.CorporationId && x.EveEntity == WHAccessEntity.Corporation) || + (x.EveEntityId == character.AllianceId && x.EveEntity == WHAccessEntity.Alliance)); + if (result == null) + return false; //TODO: check alliance and corpo and add db methodes else return true; } @@ -44,13 +49,16 @@ public async Task IsEveMapperAdminAccessAuthorized(int eveCharacterId) { var adminAccesses = await _adminRepo.GetAll(); + //If there is no user access registered return true, this is the probably the first user using the tool. if (adminAccesses?.Count() == 0) + { return true; + } else { - var res = adminAccesses?.FirstOrDefault(x => x.EveCharacterId == eveCharacterId); + var result = adminAccesses?.FirstOrDefault(x => x.EveCharacterId == eveCharacterId); - if (res == null) + if (result == null) return false; else return true; diff --git a/src/WHMapper/Services/EveMapper/EveMapperCacheService.cs b/src/WHMapper/Services/EveMapper/EveMapperCacheService.cs new file mode 100644 index 00000000..e53bf287 --- /dev/null +++ b/src/WHMapper/Services/EveMapper/EveMapperCacheService.cs @@ -0,0 +1,96 @@ +using WHMapper.Models.DTO.EveMapper.EveEntity; +using WHMapper.Services.Cache; + +namespace WHMapper.Services.EveMapper; + +public class EveMapperCacheService : IEveMapperCacheService +{ + private readonly ILogger _logger; + private readonly ICacheService _cacheService; + + public EveMapperCacheService(ILogger logger, ICacheService cacheService) + { + _logger = logger; + _cacheService = cacheService; + } + + public async Task ClearCacheAsync() + where TEntity : AEveEntity + { + try + { + string cacheKey = GetEntityCacheKey(); + return await _cacheService.Remove(cacheKey); + } + catch (Exception e) + { + _logger.LogError(e, "Error while cache"); + return false; + } + } + + public async Task GetAsync(int key) + where TEntity : AEveEntity + { + try + { + string cacheKey = GetEntityCacheKey(); + var result = await _cacheService.Get>(cacheKey); + return result?.Single(x => x.Id == key)!; + } + catch(InvalidOperationException e) + { + _logger.LogWarning(e, "Warning while getting entities {entity}", typeof(TEntity).Name); + } + catch (Exception e) + { + _logger.LogError(e, "Error while getting entities {entity}", typeof(TEntity).Name); + } + return null!; + } + + public async Task AddAsync(TEntity entity) + where TEntity : AEveEntity + { + try + { + string cacheKey = GetEntityCacheKey(); + var result = await _cacheService.Get>(cacheKey) ?? new List(); + + if (result.Contains(entity)) + { + _logger.LogInformation("{entityName} already in cache", typeof(TEntity).Name); + return true; + } + + result.Add(entity); + + return await _cacheService.Set(cacheKey, result); + } + catch (Exception e) + { + _logger.LogError(e, "Error while saving entity {entity}", typeof(TEntity).Name); + return false; + } + } + + private static string GetEntityCacheKey() + where T : AEveEntity + { + return typeof(T).Name switch + { + "AllianceEntity" => IEveMapperCacheService.REDIS_ALLIANCE_KEY, + "CorporationEntity" => IEveMapperCacheService.REDIS_COORPORATION_KEY, + "CharactereEntity" => IEveMapperCacheService.REDIS_CHARACTER_KEY, + "ShipEntity" => IEveMapperCacheService.REDIS_SHIP_KEY, + "SystemEntity" => IEveMapperCacheService.REDIS_SYSTEM_KEY, + "ConstellationEntity" => IEveMapperCacheService.REDIS_CONSTELLATION_KEY, + "RegionEntity" => IEveMapperCacheService.REDIS_REGION_KEY, + "StargateEntity" => IEveMapperCacheService.REDIS_STARTGATE_KEY, + "GroupEntity" => IEveMapperCacheService.REDIS_GROUP_KEY, + "WHEntity" => IEveMapperCacheService.REDIS_WORMHOLE_KEY, + "SunEntity" => IEveMapperCacheService.REDIS_SUN_KEY, + _ => throw new InvalidCastException("Invalid entity type"), + }; + } +} diff --git a/src/WHMapper/Services/EveMapper/EveMapperEntity.cs b/src/WHMapper/Services/EveMapper/EveMapperEntity.cs deleted file mode 100644 index 333c2fed..00000000 --- a/src/WHMapper/Services/EveMapper/EveMapperEntity.cs +++ /dev/null @@ -1,725 +0,0 @@ -using WHMapper.Models.DTO.EveAPI.Alliance; -using WHMapper.Models.DTO.EveAPI.Character; -using WHMapper.Models.DTO.EveAPI.Corporation; -using WHMapper.Models.DTO.EveAPI.Universe; -using WHMapper.Models.DTO.EveMapper.EveEntity; -using WHMapper.Services.Cache; -using WHMapper.Services.EveAPI; - -namespace WHMapper.Services.EveMapper; - -public class EveMapperEntity : IEveMapperEntity -{ - private readonly ILogger _logger; - private readonly ICacheService _cacheService; - private readonly IEveAPIServices _eveApiService; - - public EveMapperEntity(ILogger logger, ICacheService cacheService, IEveAPIServices eveApiService) - { - _logger = logger; - _cacheService = cacheService; - _eveApiService = eveApiService; - } - - private Task GetEntityCacheKey() where T : AEveEntity - { - switch (typeof(T).Name) - { - case "AllianceEntity": - return Task.FromResult(IEveMapperEntity.REDIS_ALLIANCE_KEY); - case "CorporationEntity": - return Task.FromResult(IEveMapperEntity.REDIS_COORPORATION_KEY); - case "CharactereEntity": - return Task.FromResult(IEveMapperEntity.REDIS_CHARACTER_KEY); - case "ShipEntity": - return Task.FromResult(IEveMapperEntity.REDIS_SHIP_KEY); - case "SystemEntity": - return Task.FromResult(IEveMapperEntity.REDIS_SYSTEM_KEY); - case "ConstellationEntity": - return Task.FromResult(IEveMapperEntity.REDIS_CONSTELLATION_KEY); - case "RegionEntity": - return Task.FromResult(IEveMapperEntity.REDIS_REGION_KEY); - case "StargateEntity": - return Task.FromResult(IEveMapperEntity.REDIS_STARTGATE_KEY); - case "GroupEntity": - return Task.FromResult(IEveMapperEntity.REDIS_GROUP_KEY); - case "WHEntity": - return Task.FromResult(IEveMapperEntity.REDIS_WORMHOLE_KEY); - case "SunEntity": - return Task.FromResult(IEveMapperEntity.REDIS_SUN_KEY); - default: - throw new InvalidCastException("Invalid entity type"); - } - } - - private async Task?> GetEntitiesFromCache() where T : AEveEntity - { - try - { - string redis_key = await GetEntityCacheKey(); - return await _cacheService.Get>(redis_key); - } - catch (Exception e) - { - _logger.LogError(e, "Error while getting entities {entity}", typeof(T).Name); - return null; - } - } - - private async Task SetEntityCahing(T entity) where T : AEveEntity - { - try - { - IEnumerable? results = await GetEntitiesFromCache(); - if (results == null) - { - results = new HashSet(); - } - - if (results.Contains(entity)) - { - _logger.LogInformation("{entityName} already in cache", typeof(T).Name); - return true; - } - - string redis_key = await GetEntityCacheKey(); - return await _cacheService.Set(redis_key, results.Append(entity)); - } - catch (Exception e) - { - _logger.LogError(e, "Error while saving entity {entity}", typeof(T).Name); - return false; - } - } - - - public async Task GetAlliance(int allianceId) - { - try - { - IEnumerable? results = await GetEntitiesFromCache(); - if (results != null) - { - AllianceEntity? entityItem = results.FirstOrDefault(x => x.Id == allianceId); - - if (entityItem != null) - { - _logger.LogInformation("{entityName} found in cache", entityItem.Name); - return entityItem; - } - } - - // Get alliance from API - Alliance? alliance = await _eveApiService.AllianceServices.GetAlliance(allianceId); - if (alliance == null) - { - _logger.LogWarning("Alliance {allianceId} not found", allianceId); - return null; - } - - //put on cache and return return entity - AllianceEntity entity = new AllianceEntity(allianceId, alliance); - if (await SetEntityCahing(entity)) - { - return entity; - } - else - { - _logger.LogError("Error while saving entity {entity} on cache", entity.Name); - return null; - } - - } - catch (Exception e) - { - _logger.LogError(e, "Error while getting alliance {allianceId}", allianceId); - return null; - } - } - - public async Task GetCharacter(int characterId) - { - try - { - IEnumerable? results = await GetEntitiesFromCache(); - if (results != null) - { - CharactereEntity? entityItem = results.FirstOrDefault(x => x.Id == characterId); - - if (entityItem != null) - { - _logger.LogInformation("{entityName} found in cache", entityItem.Name); - return entityItem; - } - } - - // Get character from API - Character? character = await _eveApiService.CharacterServices.GetCharacter(characterId); - if (character == null) - { - _logger.LogWarning("Character {characterId} not found", characterId); - return null; - } - - //put on cache and return return entity - CharactereEntity entity = new CharactereEntity(characterId, character); - if (await SetEntityCahing(entity)) - { - return entity; - } - else - { - _logger.LogError("Error while saving entity {entity} on cache", entity.Name); - return null; - } - } - catch (Exception e) - { - _logger.LogError(e, "Error while getting character {characterId}", characterId); - return null; - } - } - - public async Task GetCorporation(int corporationId) - { - try - { - IEnumerable? results = await GetEntitiesFromCache(); - if (results != null) - { - CorporationEntity? entityItem = results.FirstOrDefault(x => x.Id == corporationId); - - if (entityItem != null) - { - _logger.LogInformation("{entityName} found in cache", entityItem.Name); - return entityItem; - } - } - - // Get corporation from API - Corporation? corporation = await _eveApiService.CorporationServices.GetCorporation(corporationId); - if (corporation == null) - { - _logger.LogWarning("Corporation {corporationId} not found", corporationId); - return null; - } - - //put on cache and return return entity - CorporationEntity entity = new CorporationEntity(corporationId, corporation); - if (await SetEntityCahing(entity)) - { - return entity; - } - else - { - _logger.LogError("Error while saving entity {entity} on cache", entity.Name); - return null; - } - } - catch (Exception e) - { - _logger.LogError(e, "Error while getting corporation {corporationId}", corporationId); - return null; - } - } - - public async Task GetShip(int shipTypeId) - { - try - { - IEnumerable? results = await GetEntitiesFromCache(); - if (results != null) - { - ShipEntity? entityItem = results.FirstOrDefault(x => x.Id == shipTypeId); - - if (entityItem != null) - { - _logger.LogInformation("{entityName} found in cache", entityItem.Name); - return entityItem; - } - } - - // Get ship from API - Models.DTO.EveAPI.Universe.Type? ship = await _eveApiService.UniverseServices.GetType(shipTypeId); - if (ship == null) - { - _logger.LogWarning("Ship {shipTypeId} not found", shipTypeId); - return null; - } - - //put on cache and return return entity - ShipEntity entity = new ShipEntity(shipTypeId, ship); - if (await SetEntityCahing(entity)) - { - return entity; - } - else - { - _logger.LogError("Error while saving entity {entity} on cache", entity.Name); - return null; - } - } - catch (Exception e) - { - _logger.LogError(e, "Error while getting ship {shipTypeId}", shipTypeId); - return null; - } - } - - public async Task GetSystem(int systemId) - { - try - { - - IEnumerable? results = await GetEntitiesFromCache(); - if (results != null) - { - SystemEntity? entityItem = results.FirstOrDefault(x => x.Id == systemId); - - if (entityItem != null) - { - _logger.LogInformation("{entityName} found in cache", entityItem.Name); - return entityItem; - } - } - - // Get system from API - ESISolarSystem? system = await _eveApiService.UniverseServices.GetSystem(systemId); - if (system == null) - { - _logger.LogWarning("System {systemId} not found", systemId); - return null; - } - - //put on cache and return return entity - SystemEntity entity = new SystemEntity(systemId, system); - if (await SetEntityCahing(entity)) - { - return entity; - } - else - { - _logger.LogError("Error while saving entity {entity} on cache", entity.Name); - return null; - } - } - catch (Exception e) - { - _logger.LogError(e, "Error while getting system {systemId}", systemId); - return null; - } - } - - public async Task GetConstellation(int constellationId) - { - try - { - IEnumerable? results = await GetEntitiesFromCache(); - if (results != null) - { - ConstellationEntity? entityItem = results.FirstOrDefault(x => x.Id == constellationId); - - if (entityItem != null) - { - _logger.LogInformation("{entityName} found in cache", entityItem.Name); - return entityItem; - } - } - - // Get constellation from API - Constellation? constellation = await _eveApiService.UniverseServices.GetConstellation(constellationId); - if (constellation == null) - { - _logger.LogWarning("Constellation {constellationId} not found", constellationId); - return null; - } - - //put on cache and return return entity - ConstellationEntity entity = new ConstellationEntity(constellationId, constellation); - if (await SetEntityCahing(entity)) - { - return entity; - } - else - { - _logger.LogError("Error while saving entity {entity} on cache", entity.Name); - return null; - } - } - catch (Exception e) - { - _logger.LogError(e, "Error while getting constellation {constellationId}", constellationId); - return null; - } - } - - public async Task GetRegion(int regionId) - { - try - { - IEnumerable? results = await GetEntitiesFromCache(); - if (results != null) - { - RegionEntity? entityItem = results.FirstOrDefault(x => x.Id == regionId); - - if (entityItem != null) - { - _logger.LogInformation("{entityName} found in cache", entityItem.Name); - return entityItem; - } - } - - // Get region from API - Region? region = await _eveApiService.UniverseServices.GetRegion(regionId); - if (region == null) - { - _logger.LogWarning("Region {regionId} not found", regionId); - return null; - } - - //put on cache and return return entity - RegionEntity entity = new RegionEntity(regionId, region); - if (await SetEntityCahing(entity)) - { - return entity; - } - else - { - _logger.LogError("Error while saving entity {entity} on cache", entity.Name); - return null; - } - } - catch (Exception e) - { - _logger.LogError(e, "Error while getting region {regionId}", regionId); - return null; - } - } - - public async Task GetStargate(int stargateId) - { - try - { - IEnumerable? results = await GetEntitiesFromCache(); - if (results != null) - { - StargateEntity? entityItem = results.FirstOrDefault(x => x.Id == stargateId); - - if (entityItem != null) - { - _logger.LogInformation("{entityName} found in cache", entityItem.Name); - return entityItem; - } - } - - // Get stargate from API - Stargate? stargate = await _eveApiService.UniverseServices.GetStargate(stargateId); - if (stargate == null) - { - _logger.LogWarning("Stargate {stargateId} not found", stargateId); - return null; - } - - //put on cache and return return entity - StargateEntity entity = new StargateEntity(stargateId, stargate); - if (await SetEntityCahing(entity)) - { - return entity; - } - else - { - _logger.LogError("Error while saving entity {entity} on cache", entity.Name); - return null; - } - } - catch (Exception e) - { - _logger.LogError(e, "Error while getting stargate {stargateId}", stargateId); - return null; - } - } - - public async Task GetGroup(int groupId) - { - try - { - IEnumerable? results = await GetEntitiesFromCache(); - if (results != null) - { - GroupEntity? entityItem = results.FirstOrDefault(x => x.Id == groupId); - - if (entityItem != null) - { - _logger.LogInformation("{entityName} found in cache", entityItem.Name); - return entityItem; - } - } - - // Get group from API - Group? group = await _eveApiService.UniverseServices.GetGroup(groupId); - if (group == null) - { - _logger.LogWarning("Group {groupId} not found", groupId); - return null; - } - - //put on cache and return return entity - GroupEntity entity = new GroupEntity(groupId, group); - if (await SetEntityCahing(entity)) - { - return entity; - } - else - { - _logger.LogError("Error while saving entity {entity} on cache", entity.Name); - return null; - } - } - catch (Exception e) - { - _logger.LogError(e, "Error while getting group {groupId}", groupId); - return null; - } - } - - public async Task GetWormhole(int wormholeTypeId) - { - try - { - IEnumerable? results = await GetEntitiesFromCache(); - if (results != null) - { - WHEntity? entityItem = results.FirstOrDefault(x => x.Id == wormholeTypeId); - - if (entityItem != null) - { - _logger.LogInformation("{entityName} found in cache", entityItem.Name); - return entityItem; - } - } - - // Get wormhole from API - Models.DTO.EveAPI.Universe.Type? wormhole = await _eveApiService.UniverseServices.GetType(wormholeTypeId); - if (wormhole == null) - { - _logger.LogWarning("Wormhole {wormholeTypeId} not found", wormholeTypeId); - return null; - } - - //put on cache and return return entity - WHEntity entity = new WHEntity(wormholeTypeId, wormhole); - if (await SetEntityCahing(entity)) - { - return entity; - } - else - { - _logger.LogError("Error while saving entity {entity} on cache", entity.Name); - return null; - } - } - catch (Exception e) - { - _logger.LogError(e, "Error while getting wormhole {wormholeTypeId}", wormholeTypeId); - return null; - } - } - - public async Task GetSun(int sunTypeId) - { - try - { - IEnumerable? results = await GetEntitiesFromCache(); - if (results != null) - { - SunEntity? entityItem = results.FirstOrDefault(x => x.Id == sunTypeId); - - if (entityItem != null) - { - _logger.LogInformation("{entityName} found in cache", entityItem.Name); - return entityItem; - } - } - - // Get sun from API - Models.DTO.EveAPI.Universe.Type? sun = await _eveApiService.UniverseServices.GetType(sunTypeId); - if (sun == null) - { - _logger.LogWarning("Sun {sunTypeId} not found", sunTypeId); - return null; - } - - //put on cache and return return entity - SunEntity entity = new SunEntity(sunTypeId, sun); - if (await SetEntityCahing(entity)) - { - return entity; - } - else - { - _logger.LogError("Error while saving entity {entity} on cache", entity.Name); - return null; - } - } - catch (Exception e) - { - _logger.LogError(e, "Error while getting sun {sunTypeId}", sunTypeId); - return null; - } - - } - - public async Task ClearAllianceCache() - { - try - { - string redis_key = await GetEntityCacheKey(); - return await _cacheService.Remove(redis_key); - } - catch (Exception e) - { - _logger.LogError(e, "Error while clearing alliance cache"); - return false; - } - } - - public async Task ClearCharacterCache() - { - try - { - string redis_key = await GetEntityCacheKey(); - return await _cacheService.Remove(redis_key); - } - catch (Exception e) - { - _logger.LogError(e, "Error while clearing character cache"); - return false; - } - } - - public async Task ClearCorporationCache() - { - try - { - string redis_key = await GetEntityCacheKey(); - return await _cacheService.Remove(redis_key); - } - catch (Exception e) - { - _logger.LogError(e, "Error while clearing corporation cache"); - return false; - } - } - - public async Task ClearShipCache() - { - try - { - string redis_key = await GetEntityCacheKey(); - return await _cacheService.Remove(redis_key); - } - catch (Exception e) - { - _logger.LogError(e, "Error while clearing ship cache"); - return false; - } - } - - public async Task ClearSystemCache() - { - try - { - string redis_key = await GetEntityCacheKey(); - return await _cacheService.Remove(redis_key); - } - catch (Exception e) - { - _logger.LogError(e, "Error while clearing system cache"); - return false; - } - } - - public async Task ClearConstellationCache() - { - try - { - string redis_key = await GetEntityCacheKey(); - return await _cacheService.Remove(redis_key); - } - catch (Exception e) - { - _logger.LogError(e, "Error while clearing constellation cache"); - return false; - } - } - - public async Task ClearRegionCache() - { - try - { - string redis_key = await GetEntityCacheKey(); - return await _cacheService.Remove(redis_key); - } - catch (Exception e) - { - _logger.LogError(e, "Error while clearing region cache"); - return false; - } - } - - public async Task ClearStargateCache() - { - try - { - string redis_key = await GetEntityCacheKey(); - return await _cacheService.Remove(redis_key); - } - catch (Exception e) - { - _logger.LogError(e, "Error while clearing stargate cache"); - return false; - } - } - - public async Task ClearGroupCache() - { - try - { - string redis_key = await GetEntityCacheKey(); - return await _cacheService.Remove(redis_key); - } - catch (Exception e) - { - _logger.LogError(e, "Error while clearing group cache"); - return false; - } - } - - public Task ClearWormholeCache() - { - try - { - string redis_key = IEveMapperEntity.REDIS_WORMHOLE_KEY; - return _cacheService.Remove(redis_key); - } - catch (Exception e) - { - _logger.LogError(e, "Error while clearing wormhole cache"); - return Task.FromResult(false); - } - } - - public Task ClearSunCache() - { - try - { - string redis_key = IEveMapperEntity.REDIS_SUN_KEY; - return _cacheService.Remove(redis_key); - } - catch (Exception e) - { - _logger.LogError(e, "Error while clearing sun cache"); - return Task.FromResult(false); - } - } -} diff --git a/src/WHMapper/Services/EveMapper/EveMapperHelper.cs b/src/WHMapper/Services/EveMapper/EveMapperHelper.cs index b1f59d60..25cf839a 100644 --- a/src/WHMapper/Services/EveMapper/EveMapperHelper.cs +++ b/src/WHMapper/Services/EveMapper/EveMapperHelper.cs @@ -41,9 +41,9 @@ public class EveMapperHelper : IEveMapperHelper private readonly IAnoikServices _anoikServices; private readonly ISDEService _sdeServices; private readonly IWHNoteRepository _noteServices; - private readonly IEveMapperEntity _eveMapperEntity; + private readonly IEveMapperService _eveMapperEntity; - public EveMapperHelper(ILogger logger, IEveMapperEntity eveMapperEntity, ISDEService sdeServices, IAnoikServices anoikServices, IWHNoteRepository noteServices) + public EveMapperHelper(ILogger logger, IEveMapperService eveMapperEntity, ISDEService sdeServices, IAnoikServices anoikServices, IWHNoteRepository noteServices) { _logger = logger; diff --git a/src/WHMapper/Services/EveMapper/EveMapperService.cs b/src/WHMapper/Services/EveMapper/EveMapperService.cs new file mode 100644 index 00000000..8cba9ee7 --- /dev/null +++ b/src/WHMapper/Services/EveMapper/EveMapperService.cs @@ -0,0 +1,134 @@ +using WHMapper.Models.DTO.EveMapper.EveEntity; +using WHMapper.Services.EveAPI; + +namespace WHMapper.Services.EveMapper; + +public class EveMapperService : IEveMapperService +{ + private readonly ILogger _logger; + private readonly IEveMapperCacheService _cacheService; + private readonly IEveAPIServices _eveApiService; + + public EveMapperService(ILogger logger, IEveMapperCacheService cacheService, IEveAPIServices eveApiService) + { + _logger = logger; + _cacheService = cacheService; + _eveApiService = eveApiService; + } + + private async Task Get( + int key, + Func> getEveApiEntityAction, + Func entityMap + ) + where TEntity : AEveEntity + { + try + { + // Get from cache + var result = await _cacheService.GetAsync(key); + if (result != null) + { + return result; + } + + // Get from api if cache is empty + var apiResult = await getEveApiEntityAction.Invoke(_eveApiService); + if (apiResult == null) + { + _logger.LogWarning($"{nameof(TEntity)} with Id {key} not found"); + return null; + } + + // Add to cache (fire and forget) and return the entity + var entity = entityMap(apiResult); + await _cacheService.AddAsync(entity); + return entity; + } + catch (Exception e) + { + _logger.LogError(e, $"Error while getting {nameof(TEntity)} with Id {key}"); + } + + return null; + } + + public async Task GetAlliance(int allianceId) + { + return await Get(allianceId, + x => x.AllianceServices.GetAlliance(allianceId), + x => new AllianceEntity(allianceId, x) + ); + } + + public async Task GetCharacter(int characterId) + { + return await Get(characterId, + x => x.CharacterServices.GetCharacter(characterId), + x => new CharactereEntity(characterId, x) + ); + } + + public async Task GetCorporation(int corporationId) + { + return await Get(corporationId, + x => x.CorporationServices.GetCorporation(corporationId), + x => new CorporationEntity(corporationId, x)); + } + + public async Task GetShip(int shipTypeId) + { + return await Get(shipTypeId, + x => x.UniverseServices.GetType(shipTypeId), + x => new ShipEntity(shipTypeId, x)); + } + + public async Task GetSystem(int systemId) + { + return await Get(systemId, + x => x.UniverseServices.GetSystem(systemId), + x => new SystemEntity(systemId, x)); + } + + public async Task GetConstellation(int constellationId) + { + return await Get(constellationId, + x => x.UniverseServices.GetConstellation(constellationId), + x => new ConstellationEntity(constellationId, x)); + } + + public async Task GetRegion(int regionId) + { + return await Get(regionId, + x => x.UniverseServices.GetRegion(regionId), + x => new RegionEntity(regionId, x)); + } + + public async Task GetStargate(int stargateId) + { + return await Get(stargateId, + x => x.UniverseServices.GetStargate(stargateId), + x => new StargateEntity(stargateId, x)); + } + + public async Task GetGroup(int groupId) + { + return await Get(groupId, + x => x.UniverseServices.GetGroup(groupId), + x => new GroupEntity(groupId, x)); + } + + public async Task GetWormhole(int wormholeTypeId) + { + return await Get(wormholeTypeId, + x => x.UniverseServices.GetType(wormholeTypeId), + x => new WHEntity(wormholeTypeId, x)); + } + + public async Task GetSun(int sunTypeId) + { + return await Get(sunTypeId, + x => x.UniverseServices.GetType(sunTypeId), + x => new SunEntity(sunTypeId, x)); + } +} diff --git a/src/WHMapper/Services/EveMapper/EveMapperTracker.cs b/src/WHMapper/Services/EveMapper/EveMapperTracker.cs index 7557e07c..679526e5 100644 --- a/src/WHMapper/Services/EveMapper/EveMapperTracker.cs +++ b/src/WHMapper/Services/EveMapper/EveMapperTracker.cs @@ -14,7 +14,7 @@ public class EveMapperTracker : IEveMapperTracker, IAsyncDisposable private readonly AuthenticationStateProvider _authState; private readonly IEveAPIServices? _eveAPIServices; - private readonly IEveMapperEntity _eveMapperEntity; + private readonly IEveMapperService _eveMapperEntity; private System.Timers.Timer? _timer = null!; @@ -26,7 +26,7 @@ public class EveMapperTracker : IEveMapperTracker, IAsyncDisposable public event Func SystemChanged = null!; public event Func ShipChanged = null!; - public EveMapperTracker(ILogger logger, AuthenticationStateProvider authState, IEveAPIServices eveAPI, IEveMapperEntity eveMapperEntity) + public EveMapperTracker(ILogger logger, AuthenticationStateProvider authState, IEveAPIServices eveAPI, IEveMapperService eveMapperEntity) { _logger = logger; _authState = authState; diff --git a/src/WHMapper/Services/EveMapper/IEveMapperCacheService.cs b/src/WHMapper/Services/EveMapper/IEveMapperCacheService.cs new file mode 100644 index 00000000..9b826c60 --- /dev/null +++ b/src/WHMapper/Services/EveMapper/IEveMapperCacheService.cs @@ -0,0 +1,28 @@ +using WHMapper.Models.DTO.EveMapper.EveEntity; + +namespace WHMapper.Services.EveMapper +{ + public interface IEveMapperCacheService + { + const string REDIS_ALLIANCE_KEY = "alliance:list"; + const string REDIS_COORPORATION_KEY = "coorporation:list"; + const string REDIS_CHARACTER_KEY = "charactere:list"; + const string REDIS_SHIP_KEY = "ship:list"; + const string REDIS_SYSTEM_KEY = "system:list"; + const string REDIS_CONSTELLATION_KEY = "constellation:list"; + const string REDIS_REGION_KEY = "region:list"; + const string REDIS_STARTGATE_KEY = "stargate:list"; + const string REDIS_GROUP_KEY = "group:list"; + const string REDIS_WORMHOLE_KEY = "wormhole:list"; + const string REDIS_SUN_KEY = "sun:list"; + + Task GetAsync(int key) + where TEntity : AEveEntity; + + Task AddAsync(TEntity entity) + where TEntity : AEveEntity; + + Task ClearCacheAsync() + where TEntity : AEveEntity; + } +} diff --git a/src/WHMapper/Services/EveMapper/IEveMapperEntity.cs b/src/WHMapper/Services/EveMapper/IEveMapperEntity.cs deleted file mode 100644 index e7c4ed94..00000000 --- a/src/WHMapper/Services/EveMapper/IEveMapperEntity.cs +++ /dev/null @@ -1,40 +0,0 @@ -using WHMapper.Models.DTO.EveMapper.EveEntity; - -namespace WHMapper.Services.EveMapper; - -public interface IEveMapperEntity -{ - const string REDIS_ALLIANCE_KEY = "alliance:list"; - const string REDIS_COORPORATION_KEY = "coorporation:list"; - const string REDIS_CHARACTER_KEY = "charactere:list"; - const string REDIS_SHIP_KEY = "ship:list"; - const string REDIS_SYSTEM_KEY = "system:list"; - const string REDIS_CONSTELLATION_KEY = "constellation:list"; - const string REDIS_REGION_KEY = "region:list"; - const string REDIS_STARTGATE_KEY = "stargate:list"; - const string REDIS_GROUP_KEY = "group:list"; - const string REDIS_WORMHOLE_KEY = "wormhole:list"; - const string REDIS_SUN_KEY = "sun:list"; - Task GetCharacter(int characterId); - Task GetCorporation(int corporationId); - Task GetAlliance(int allianceId); - Task GetShip(int shipTypeId); - Task GetSystem(int systemId); - Task GetConstellation(int constellationId); - Task GetRegion(int regionId); - Task GetStargate(int stargateId); - Task GetGroup(int groupId); - Task GetWormhole(int wormholeTypeId); - Task GetSun(int sunTypeId); - Task ClearCharacterCache(); - Task ClearCorporationCache(); - Task ClearAllianceCache(); - Task ClearShipCache(); - Task ClearSystemCache(); - Task ClearConstellationCache(); - Task ClearRegionCache(); - Task ClearStargateCache(); - Task ClearGroupCache(); - Task ClearWormholeCache(); - Task ClearSunCache(); -} \ No newline at end of file diff --git a/src/WHMapper/Services/EveMapper/IEveMapperService.cs b/src/WHMapper/Services/EveMapper/IEveMapperService.cs new file mode 100644 index 00000000..e2e3d3cc --- /dev/null +++ b/src/WHMapper/Services/EveMapper/IEveMapperService.cs @@ -0,0 +1,18 @@ +using WHMapper.Models.DTO.EveMapper.EveEntity; + +namespace WHMapper.Services.EveMapper; + +public interface IEveMapperService +{ + Task GetCharacter(int characterId); + Task GetCorporation(int corporationId); + Task GetAlliance(int allianceId); + Task GetShip(int shipTypeId); + Task GetSystem(int systemId); + Task GetConstellation(int constellationId); + Task GetRegion(int regionId); + Task GetStargate(int stargateId); + Task GetGroup(int groupId); + Task GetWormhole(int wormholeTypeId); + Task GetSun(int sunTypeId); +} \ No newline at end of file diff --git a/src/WHMapper/WHMapper.csproj b/src/WHMapper/WHMapper.csproj index 0cfbacf7..75b6b54f 100644 --- a/src/WHMapper/WHMapper.csproj +++ b/src/WHMapper/WHMapper.csproj @@ -130,7 +130,6 @@ - From f2ac65ef5fea8175d9600fdaf030705c9b09fff7 Mon Sep 17 00:00:00 2001 From: pfh59 <109206285+pfh59@users.noreply.github.com> Date: Wed, 10 Jul 2024 21:55:13 +0200 Subject: [PATCH 2/2] Fix_sonarcloud_result_analyze (#286) * Fix : Use a comparison to 'default(TEveApiEntity)' instead or add a constraint to 'TEveApiEntity' so that it can't be a value type. * fix : Await CountAsync instead. --- src/WHMapper/Repositories/WHSignatures/WHSignatureRepository.cs | 2 +- src/WHMapper/Services/EveMapper/EveMapperService.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/WHMapper/Repositories/WHSignatures/WHSignatureRepository.cs b/src/WHMapper/Repositories/WHSignatures/WHSignatureRepository.cs index 2c3b531e..ecd4e409 100644 --- a/src/WHMapper/Repositories/WHSignatures/WHSignatureRepository.cs +++ b/src/WHMapper/Repositories/WHSignatures/WHSignatureRepository.cs @@ -127,7 +127,7 @@ protected override async Task ADeleteById(int id) { using (var context = await _contextFactory.CreateDbContextAsync()) { - if (context.DbWHSignatures.Count() == 0) + if (!await context.DbWHSignatures.AnyAsync()) return await context.DbWHSignatures.ToListAsync(); else { diff --git a/src/WHMapper/Services/EveMapper/EveMapperService.cs b/src/WHMapper/Services/EveMapper/EveMapperService.cs index 8cba9ee7..8c0b38a2 100644 --- a/src/WHMapper/Services/EveMapper/EveMapperService.cs +++ b/src/WHMapper/Services/EveMapper/EveMapperService.cs @@ -34,7 +34,7 @@ Func entityMap // Get from api if cache is empty var apiResult = await getEveApiEntityAction.Invoke(_eveApiService); - if (apiResult == null) + if (EqualityComparer.Default.Equals(apiResult, default(TEveApiEntity))) { _logger.LogWarning($"{nameof(TEntity)} with Id {key} not found"); return null;