Skip to content

Commit

Permalink
Merge pull request #178 from code4romania/feature/remove-cache
Browse files Browse the repository at this point in the history
Remove api cache
  • Loading branch information
gheorghelupu17 authored Jun 9, 2024
2 parents 382c97e + e0c6355 commit a158be5
Show file tree
Hide file tree
Showing 10 changed files with 32 additions and 139 deletions.
18 changes: 3 additions & 15 deletions src/ElectionResults.API/Controllers/BallotsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
using ElectionResults.Core.Endpoints.Response;
using ElectionResults.Core.Infrastructure;
using ElectionResults.Core.Repositories;
using LazyCache;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

Expand All @@ -19,27 +18,22 @@ namespace ElectionResults.API.Controllers
public class BallotsController : ControllerBase
{
private readonly IResultsAggregator _resultsAggregator;
private readonly IAppCache _appCache;
private readonly ITerritoryRepository _territoryRepository;
private readonly MemoryCacheSettings _cacheSettings;

public BallotsController(IResultsAggregator resultsAggregator,
IAppCache appCache,
ITerritoryRepository territoryRepository,
IOptions<MemoryCacheSettings> cacheSettings)
{
_resultsAggregator = resultsAggregator;
_appCache = appCache;
_territoryRepository = territoryRepository;
_cacheSettings = cacheSettings.Value;
}

[HttpGet("ballots")]
public async Task<ActionResult<List<ElectionMeta>>> GetBallots()
{
var result = await _appCache.GetOrAddAsync(
"ballots", () => _resultsAggregator.GetAllBallots(),
DateTimeOffset.Now.AddMinutes(120));
var result = await _resultsAggregator.GetAllBallots();

if (result.IsSuccess)
{
Expand Down Expand Up @@ -71,15 +65,12 @@ public async Task<ActionResult<List<PartyList>>> GetCandidatesForBallot([FromQue
query.Round = null;
}

var result = await _appCache.GetOrAddAsync(
query.GetCacheKey(), () => _resultsAggregator.GetBallotCandidates(query),
DateTimeOffset.Now.AddMinutes(query.GetCacheDurationInMinutes()));
var result = await _resultsAggregator.GetBallotCandidates(query);

return result.Value;
}
catch (Exception e)
{
_appCache.Remove(query.GetCacheKey());
Log.LogError(e, "Exception encountered while retrieving voter turnout stats");
return StatusCode(500, e.StackTrace);
}
Expand Down Expand Up @@ -107,9 +98,7 @@ public async Task<ActionResult<ElectionResponse>> GetBallot([FromQuery] Election

var expiration = GetExpirationDate(query);

var result = await _appCache.GetOrAddAsync(
query.GetCacheKey(), () => _resultsAggregator.GetBallotResults(query),
expiration);
var result = await _resultsAggregator.GetBallotResults(query);

var newsFeed = await _resultsAggregator.GetNewsFeed(query, result.Value.Meta.ElectionId);
result.Value.ElectionNews = newsFeed;
Expand All @@ -118,7 +107,6 @@ public async Task<ActionResult<ElectionResponse>> GetBallot([FromQuery] Election
}
catch (Exception e)
{
_appCache.Remove(query.GetCacheKey());
Log.LogError(e, "Exception encountered while retrieving voter turnout stats");
return StatusCode(500, e.StackTrace);
}
Expand Down
7 changes: 6 additions & 1 deletion src/ElectionResults.API/ElectionResults.API.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,12 @@
<None Include="wwwroot\*" />
</ItemGroup>
<ItemGroup>
<Folder Include="Import\" />
<Compile Remove="Import\**" />
<Content Remove="Import\**" />
<EmbeddedResource Remove="Import\**" />
<None Remove="Import\**" />
</ItemGroup>
<ItemGroup>
<Folder Include="Options\" />
<Folder Include="wwwroot\lib\" />
<Folder Include="wwwroot\upload\" />
Expand Down
2 changes: 0 additions & 2 deletions src/ElectionResults.API/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ public void ConfigureServices(IServiceCollection services)
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(new SnakeCaseNamingPolicy()));
});
services.AddLazyCache();
RegisterDependencies(services, Configuration);
services.AddSwaggerGen(c =>
{
Expand All @@ -65,7 +64,6 @@ public void ConfigureServices(IServiceCollection services)
options.UseMySQL(connectionString);
});

services.AddLazyCache();
services.AddCors(options =>
{
options.AddPolicy("origins",
Expand Down
2 changes: 0 additions & 2 deletions src/ElectionResults.Core/ElectionResults.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
<PackageReference Include="CSharpFunctionalExtensions" Version="2.42.0" />
<PackageReference Include="CsvHelper" Version="32.0.3" />
<PackageReference Include="Diacritics" Version="3.3.29" />
<PackageReference Include="LazyCache" Version="2.4.0" />
<PackageReference Include="LazyCache.AspNetCore" Version="2.4.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.6">
Expand Down
18 changes: 3 additions & 15 deletions src/ElectionResults.Core/Elections/WinnersAggregator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
using ElectionResults.Core.Extensions;
using ElectionResults.Core.Infrastructure;
using ElectionResults.Core.Repositories;
using LazyCache;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.Extensions.DependencyInjection;
Expand All @@ -18,19 +17,16 @@ namespace ElectionResults.Core.Elections
public class WinnersAggregator : IWinnersAggregator
{
private readonly ApplicationDbContext _dbContext;
private readonly IAppCache _appCache;
private readonly IServiceProvider _serviceProvider;
private readonly IPartiesRepository _partiesRepository;
private readonly ITerritoryRepository _territoryRepository;

public WinnersAggregator(ApplicationDbContext dbContext,
IAppCache appCache,
IServiceProvider serviceProvider,
IPartiesRepository partiesRepository,
ITerritoryRepository territoryRepository)
{
_dbContext = dbContext;
_appCache = appCache;
_serviceProvider = serviceProvider;
_partiesRepository = partiesRepository;
_territoryRepository = territoryRepository;
Expand All @@ -45,8 +41,6 @@ public async Task<Result<List<Winner>>> GetLocalityCityHallWinnersByCounty(int b
return dbWinners;
}

_appCache.Remove(MemoryCache.CreateWinnersKey(ballotId, countyId, ElectionDivision.Locality));

var localities = await _dbContext
.Localities
.Where(l => l.CountyId == countyId).ToListAsync();
Expand Down Expand Up @@ -97,17 +91,12 @@ public async Task<Result<List<Winner>>> GetLocalityCityHallWinnersByCounty(int b

private async Task<List<Winner>> GetWinners(int ballotId, int? countyId, ElectionDivision division)
{
var query = CreateWinnersQuery()
var winners = await CreateWinnersQuery()
.Where(w => w.BallotId == ballotId
&& w.Division == division
&& w.CountyId == countyId)
.ToListAsync();

var winnersKey = MemoryCache.CreateWinnersKey(ballotId, countyId, division);

var winners = await _appCache
.GetOrAddAsync(winnersKey, () => query, DateTimeOffset.Now.AddMinutes(10));

return winners;
}

Expand Down Expand Up @@ -160,7 +149,7 @@ public async Task<Result<List<ElectionMapWinner>>> GetCountryWinners(int ballotI

if (dbWinners.Count > 0)
return dbWinners.Select(winner => WinnerToElectionMapWinner(winner, parties.ToList())).ToList();
_appCache.Remove(MemoryCache.CreateWinnersKey(ballotId, null, ElectionDivision.Diaspora_Country));

var winners = new List<ElectionMapWinner>();
var countries = await _territoryRepository.GetCountries(null);
if (countries.IsFailure)
Expand Down Expand Up @@ -250,7 +239,7 @@ public async Task<Result<List<ElectionMapWinner>>> GetCountyWinners(int ballotId
var dbWinners = await GetWinners(ballotId, null, ElectionDivision.County);
if (dbWinners.Count > 0)
return dbWinners.Select(winner => WinnerToElectionMapWinner(winner, parties)).ToList();
_appCache.Remove(MemoryCache.CreateWinnersKey(ballotId, null, ElectionDivision.Diaspora_Country));

var winners = await AggregateCountyWinners(ballotId, parties);
return Result.Success(winners.Select(winner => WinnerToElectionMapWinner(winner, parties)).ToList());
}
Expand Down Expand Up @@ -303,7 +292,6 @@ public async Task<Result<List<CandidateResult>>> GetWinningCandidatesByCounty(in
var dbWinners = await GetWinners(ballotId, null, ElectionDivision.County);
if (dbWinners.Count > 0)
return dbWinners.Select(w => w.Candidate).ToList();
_appCache.Remove(MemoryCache.CreateWinnersKey(ballotId, null, ElectionDivision.Diaspora_Country));
var winners = await AggregateCountyWinners(ballotId, parties);
return winners.Select(w => w.Candidate).ToList();
}
Expand Down
26 changes: 6 additions & 20 deletions src/ElectionResults.Core/Repositories/BallotsRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,44 +3,30 @@
using System.Linq;
using System.Threading.Tasks;
using ElectionResults.Core.Entities;
using LazyCache;
using Microsoft.EntityFrameworkCore;

namespace ElectionResults.Core.Repositories
{
public class BallotsRepository : IBallotsRepository
{
private readonly ApplicationDbContext _dbContext;
private readonly IAppCache _appCache;
private readonly CacheSettings _cacheSettings;

public BallotsRepository(ApplicationDbContext dbContext, IAppCache appCache)
public BallotsRepository(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
_appCache = appCache;
_cacheSettings = MemoryCache.Ballots;
}

public async Task<IEnumerable<Ballot>> GetAllBallots(bool includeElection = false)
{
return await _appCache.GetOrAddAsync(
_cacheSettings.Key, () =>
{
var query = CreateQueryable(includeElection);
return query.ToListAsync();
},
DateTimeOffset.Now.AddMinutes(_cacheSettings.Minutes));
return await CreateQueryable(includeElection).ToListAsync();
}

public async Task<Ballot> GetBallotById(int ballotId, bool includeElection = false)
{
var ballot = await _appCache.GetOrAddAsync(
_cacheSettings.Key, () =>
{
var query = CreateQueryable(includeElection);
return query.FirstOrDefaultAsync(b => b.BallotId == ballotId);
},
DateTimeOffset.Now.AddMinutes(_cacheSettings.Minutes));

var query = CreateQueryable(includeElection);
var ballot = await query.FirstOrDefaultAsync(b => b.BallotId == ballotId);

return ballot;
}

Expand Down
12 changes: 3 additions & 9 deletions src/ElectionResults.Core/Repositories/ElectionsRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,23 @@
using CSharpFunctionalExtensions;
using ElectionResults.Core.Endpoints.Response;
using ElectionResults.Core.Entities;
using LazyCache;
using Microsoft.EntityFrameworkCore;

namespace ElectionResults.Core.Repositories
{
public class ElectionsRepository : IElectionsRepository
{
private readonly ApplicationDbContext _dbContext;
private readonly IAppCache _appCache;
private readonly CacheSettings _cacheSettings;

public ElectionsRepository(ApplicationDbContext dbContext, IAppCache appCache)
public ElectionsRepository(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
_appCache = appCache;
_cacheSettings = MemoryCache.Elections;
}

public async Task<Result<List<Election>>> GetAllElections(bool includeBallots = false)
{
var elections = await _appCache.GetOrAddAsync(
_cacheSettings.Key, () => CreateQueryable(includeBallots).ToListAsync(),
DateTimeOffset.Now.AddMinutes(_cacheSettings.Minutes));
var elections = await CreateQueryable(includeBallots).ToListAsync();

return Result.Success(elections);
}

Expand Down
44 changes: 0 additions & 44 deletions src/ElectionResults.Core/Repositories/MemoryCache.cs

This file was deleted.

11 changes: 2 additions & 9 deletions src/ElectionResults.Core/Repositories/PartiesRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,22 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using ElectionResults.Core.Entities;
using LazyCache;
using Microsoft.EntityFrameworkCore;

namespace ElectionResults.Core.Repositories
{
public class PartiesRepository : IPartiesRepository
{
private readonly ApplicationDbContext _dbContext;
private readonly IAppCache _appCache;
private readonly CacheSettings _cacheSettings;

public PartiesRepository(ApplicationDbContext dbContext, IAppCache appCache)
public PartiesRepository(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
_appCache = appCache;
_cacheSettings = MemoryCache.Parties;
}

public async Task<IEnumerable<Party>> GetAllParties()
{
return await _appCache.GetOrAddAsync(
_cacheSettings.Key, () => _dbContext.Parties.ToListAsync(),
DateTimeOffset.Now.AddMinutes(_cacheSettings.Minutes));
return await _dbContext.Parties.ToListAsync();
}
}
}
Loading

0 comments on commit a158be5

Please sign in to comment.