Compare commits
2 Commits
feat/add-a
...
add-tests
| Author | SHA1 | Date | |
|---|---|---|---|
| 6ac0ab6125 | |||
|
|
fc6f5fd1de |
27
CampusWorkshops.Tests/CampusWorkshops.Tests.csproj
Normal file
27
CampusWorkshops.Tests/CampusWorkshops.Tests.csproj
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net9.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<IsPackable>false</IsPackable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="coverlet.collector" Version="6.0.2" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="9.10.0" />
|
||||||
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
|
||||||
|
<PackageReference Include="NSubstitute" Version="5.3.0" />
|
||||||
|
<PackageReference Include="xunit" Version="2.9.2" />
|
||||||
|
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Using Include="Xunit" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\Workshop10-API\Workshop10-API.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
|
||||||
|
// CampusWorkshops.Tests/Registration/RegistrationPolicyTests.cs
|
||||||
|
using System;
|
||||||
|
using CampusWorkshops.Api.Domain.Registration;
|
||||||
|
using CampusWorkshops.Api.Models; // Workshop do seu projeto
|
||||||
|
using Microsoft.Extensions.Time.Testing;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace CampusWorkshops.Tests.Registration
|
||||||
|
{
|
||||||
|
public class RegistrationPolicyTests
|
||||||
|
{
|
||||||
|
private static (RegistrationPolicy Policy, FakeTimeProvider Time) BuildSut(DateTimeOffset nowUtc)
|
||||||
|
{
|
||||||
|
var time = new FakeTimeProvider(nowUtc.UtcDateTime);
|
||||||
|
var policy = new RegistrationPolicy(time);
|
||||||
|
return (policy, time);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Workshop W(int capacity, DateTimeOffset startAt)
|
||||||
|
=> new Workshop
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid(),
|
||||||
|
Title = "Qualquer título",
|
||||||
|
StartAt = startAt.UtcDateTime, // se seu StartAt for DateTimeOffset, use .StartAt = startAt
|
||||||
|
EndAt = startAt.UtcDateTime.AddHours(2),
|
||||||
|
Capacity = capacity,
|
||||||
|
IsOnline = true
|
||||||
|
};
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Rejects_When_Window_Closed_At_24h()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var now = DateTimeOffset.Parse("2025-03-01T12:00:00Z");
|
||||||
|
var (policy, _) = BuildSut(now);
|
||||||
|
var w = W(capacity: 10, startAt: now.AddHours(RegistrationPolicy.CloseWindowLeadHours));
|
||||||
|
var enrolled = 0;
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var decision = policy.Decide(w, enrolled);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.Equal(RegistrationOutcome.Rejected, decision.Outcome);
|
||||||
|
Assert.Contains("Registration window closed.", decision.Reasons);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Accepts_When_Seats_Available()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var now = DateTimeOffset.Parse("2025-03-01T12:00:00Z");
|
||||||
|
var (policy, _) = BuildSut(now);
|
||||||
|
var w = W(capacity: 10, startAt: now.AddHours(36));
|
||||||
|
var enrolled = 9;
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var decision = policy.Decide(w, enrolled);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.Equal(RegistrationOutcome.Accepted, decision.Outcome);
|
||||||
|
Assert.Contains("Accepted", decision.Reasons);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Rejects_When_Full()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var now = DateTimeOffset.Parse("2025-03-01T12:00:00Z");
|
||||||
|
var (policy, _) = BuildSut(now);
|
||||||
|
var w = W(capacity: 10, startAt: now.AddHours(36));
|
||||||
|
var enrolled = 10;
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var decision = policy.Decide(w, enrolled);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.Equal(RegistrationOutcome.Rejected, decision.Outcome);
|
||||||
|
Assert.Contains("No seats available.", decision.Reasons);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(30, RegistrationOutcome.Accepted)]
|
||||||
|
[InlineData(24, RegistrationOutcome.Rejected)]
|
||||||
|
[InlineData(10, RegistrationOutcome.Rejected)]
|
||||||
|
public void Window_Rules(int hoursToStart, RegistrationOutcome expected)
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var now = DateTimeOffset.Parse("2025-03-01T12:00:00Z");
|
||||||
|
var (policy, _) = BuildSut(now);
|
||||||
|
var w = W(capacity: 5, startAt: now.AddHours(hoursToStart));
|
||||||
|
var enrolled = 0;
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var decision = policy.Decide(w, enrolled);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.Equal(expected, decision.Outcome);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
10
CampusWorkshops.Tests/UnitTest1.cs
Normal file
10
CampusWorkshops.Tests/UnitTest1.cs
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
namespace CampusWorkshops.Tests;
|
||||||
|
|
||||||
|
public class UnitTest1
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void Test1()
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,19 +1,46 @@
|
|||||||
|
|
||||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||||
# Visual Studio Version 17
|
# Visual Studio Version 17
|
||||||
VisualStudioVersion = 17.5.2.0
|
VisualStudioVersion = 17.5.2.0
|
||||||
MinimumVisualStudioVersion = 10.0.40219.1
|
MinimumVisualStudioVersion = 10.0.40219.1
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Workshop10-API", "Workshop10-API.csproj", "{5106011C-9EE5-2CD0-05A5-164233706862}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Workshop10-API", "Workshop10-API\Workshop10-API.csproj", "{A51E3052-20C8-4154-905F-4AE95A131FB1}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CampusWorkshops.Tests", "CampusWorkshops.Tests\CampusWorkshops.Tests.csproj", "{3327A641-9CFC-40DA-9E4E-0E6BD3390068}"
|
||||||
EndProject
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
Debug|Any CPU = Debug|Any CPU
|
||||||
|
Debug|x64 = Debug|x64
|
||||||
|
Debug|x86 = Debug|x86
|
||||||
Release|Any CPU = Release|Any CPU
|
Release|Any CPU = Release|Any CPU
|
||||||
|
Release|x64 = Release|x64
|
||||||
|
Release|x86 = Release|x86
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||||
{5106011C-9EE5-2CD0-05A5-164233706862}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
{5106011C-9EE5-2CD0-05A5-164233706862}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{5106011C-9EE5-2CD0-05A5-164233706862}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
{5106011C-9EE5-2CD0-05A5-164233706862}.Release|Any CPU.Build.0 = Release|Any CPU
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Release|x86.Build.0 = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
|
|||||||
59
Workshop10-API/Controllers/DiDemoController.cs
Normal file
59
Workshop10-API/Controllers/DiDemoController.cs
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using CampusWorkshops.Api.Services;
|
||||||
|
|
||||||
|
namespace CampusWorkshops.Api.Controllers;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[AllowAnonymous] // Deixe aberto para facilitar o teste
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class DiDemoController : ControllerBase
|
||||||
|
{
|
||||||
|
// Visualiza os IDs por lifetime
|
||||||
|
[HttpGet("lifetimes")]
|
||||||
|
public IActionResult Lifetimes(
|
||||||
|
[FromServices] IRequestIdTransient t1,
|
||||||
|
[FromServices] IRequestIdTransient t2,
|
||||||
|
[FromServices] IRequestIdScoped s1,
|
||||||
|
[FromServices] IRequestIdScoped s2,
|
||||||
|
[FromServices] IRequestIdSingleton g1,
|
||||||
|
[FromServices] IRequestIdSingleton g2)
|
||||||
|
{
|
||||||
|
return Ok(new {
|
||||||
|
transient1 = t1.Id, transient2 = t2.Id, // normalmente diferentes NA MESMA chamada
|
||||||
|
scoped1 = s1.Id, scoped2 = s2.Id, // iguais NA MESMA chamada; mudam entre chamadas
|
||||||
|
singleton1 = g1.Id, singleton2 = g2.Id // sempre iguais
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Demonstra o "cativeiro" do transient dentro de um singleton
|
||||||
|
[HttpGet("captive-transient")]
|
||||||
|
public IActionResult Captive(
|
||||||
|
[FromServices] ReportingSingleton singleton,
|
||||||
|
[FromServices] IPerRequestClock clockTransient)
|
||||||
|
{
|
||||||
|
// clockTransient é Transient: CreatedAt muda entre requisições
|
||||||
|
var transientCreatedAtNow = clockTransient.CreatedAt;
|
||||||
|
|
||||||
|
// GetClockCreatedAt (TODO) deveria retornar o CreatedAt visto pelo singleton
|
||||||
|
DateTimeOffset? singletonClockCreatedAt = null;
|
||||||
|
string? error = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
singletonClockCreatedAt = singleton.GetClockCreatedAt();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
error = $"{ex.GetType().Name}: {ex.Message}";
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(new {
|
||||||
|
transientCreatedAtNow,
|
||||||
|
singletonClockCreatedAt,
|
||||||
|
esperado = "Valores DIFERENTES por requisição",
|
||||||
|
observacao = "Mas como o transient foi resolvido DENTRO do singleton, ele congelou e não muda",
|
||||||
|
todoImplementado = error is null,
|
||||||
|
errorAoChamarSingleton = error
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using CampusWorkshops.Api.Models; // <-- Workshop do seu projeto
|
||||||
|
|
||||||
|
namespace CampusWorkshops.Api.Domain.Registration
|
||||||
|
{
|
||||||
|
public enum RegistrationOutcome { Accepted, Rejected }
|
||||||
|
|
||||||
|
public sealed record RegistrationDecision(RegistrationOutcome Outcome, IReadOnlyList<string> Reasons);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Regra simples de registro para Workshop.
|
||||||
|
/// Regras:
|
||||||
|
/// - Janela fecha quando faltar <= 24h para o StartAt.
|
||||||
|
/// - Se há assentos (Capacity - enrolled > 0) → Accepted; senão → Rejected.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class RegistrationPolicy
|
||||||
|
{
|
||||||
|
public const int CloseWindowLeadHours = 24;
|
||||||
|
|
||||||
|
private readonly TimeProvider _time;
|
||||||
|
|
||||||
|
public RegistrationPolicy(TimeProvider time)
|
||||||
|
{
|
||||||
|
_time = time ?? throw new ArgumentNullException(nameof(time));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Decide usando apenas o Workshop e o número ATUAL de inscritos (enrolled).
|
||||||
|
/// </summary>
|
||||||
|
public RegistrationDecision Decide(Workshop w, int enrolled)
|
||||||
|
{
|
||||||
|
if (w is null) throw new ArgumentNullException(nameof(w));
|
||||||
|
var reasons = new List<string>();
|
||||||
|
|
||||||
|
// (1) Janela de inscrição
|
||||||
|
var now = _time.GetUtcNow();
|
||||||
|
// Se StartAt for DateTime (não Offset) no seu modelo, troque por:
|
||||||
|
// var startAtUtc = DateTime.SpecifyKind(w.StartAt, DateTimeKind.Utc);
|
||||||
|
// if (startAtUtc - now <= TimeSpan.FromHours(CloseWindowLeadHours)) { ... }
|
||||||
|
if (w.StartAt - now <= TimeSpan.FromHours(CloseWindowLeadHours))
|
||||||
|
{
|
||||||
|
reasons.Add("Registration window closed.");
|
||||||
|
return new RegistrationDecision(RegistrationOutcome.Rejected, reasons);
|
||||||
|
}
|
||||||
|
|
||||||
|
// (2) Capacidade
|
||||||
|
var seatsLeft = w.Capacity - enrolled;
|
||||||
|
if (seatsLeft > 0)
|
||||||
|
{
|
||||||
|
reasons.Add("Accepted");
|
||||||
|
return new RegistrationDecision(RegistrationOutcome.Accepted, reasons);
|
||||||
|
}
|
||||||
|
|
||||||
|
reasons.Add("No seats available.");
|
||||||
|
return new RegistrationDecision(RegistrationOutcome.Rejected, reasons);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -8,6 +8,10 @@ using System.Text;
|
|||||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||||
using Microsoft.IdentityModel.Tokens;
|
using Microsoft.IdentityModel.Tokens;
|
||||||
using Microsoft.OpenApi.Models;
|
using Microsoft.OpenApi.Models;
|
||||||
|
using CampusWorkshops.Api.Services;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using Microsoft.Extensions.Caching.Memory;
|
||||||
|
using CampusWorkshops.Api.Domain.Registration;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
@@ -44,7 +48,37 @@ builder.Services.AddAuthorization(options =>
|
|||||||
builder.Services.AddDbContext<WorkshopsDbContext>(options =>
|
builder.Services.AddDbContext<WorkshopsDbContext>(options =>
|
||||||
options.UseSqlite(builder.Configuration.GetConnectionString("WorkshopsDb")));
|
options.UseSqlite(builder.Configuration.GetConnectionString("WorkshopsDb")));
|
||||||
|
|
||||||
builder.Services.AddScoped<IWorkshopRepository, EfWorkshopRepository>();
|
builder.Services.AddMemoryCache();
|
||||||
|
builder.Services.Configure<CacheSettings>(builder.Configuration.GetSection("Cache"));
|
||||||
|
|
||||||
|
|
||||||
|
// Primeiro registramos a implementação EF concreta
|
||||||
|
builder.Services.AddScoped<EfWorkshopRepository>();
|
||||||
|
|
||||||
|
// tempo do sistema para produção:
|
||||||
|
builder.Services.AddSingleton<TimeProvider>(TimeProvider.System);
|
||||||
|
// regra de domínio (stateless); pode ser Singleton
|
||||||
|
builder.Services.AddSingleton<RegistrationPolicy>();
|
||||||
|
|
||||||
|
// Depois expomos IWorkshopRepository como o "EF envelopado por cache"
|
||||||
|
builder.Services.AddScoped<IWorkshopRepository>(sp =>
|
||||||
|
new CachedWorkshopRepository(
|
||||||
|
sp.GetRequiredService<EfWorkshopRepository>(),
|
||||||
|
sp.GetRequiredService<IMemoryCache>(),
|
||||||
|
sp.GetRequiredService<IOptionsSnapshot<CacheSettings>>()));
|
||||||
|
|
||||||
|
// Lifetimes de exemplo
|
||||||
|
builder.Services.AddTransient<IRequestIdTransient, RequestIdTransient>();
|
||||||
|
builder.Services.AddScoped<IRequestIdScoped, RequestIdScoped>();
|
||||||
|
builder.Services.AddSingleton<IRequestIdSingleton, RequestIdSingleton>();
|
||||||
|
|
||||||
|
// Exemplo de "captive dependency"
|
||||||
|
builder.Services.AddTransient<IPerRequestClock, PerRequestClock>(); // Transient
|
||||||
|
builder.Services.AddSingleton<ReportingSingleton>();
|
||||||
|
|
||||||
|
|
||||||
|
// Removendo para ativar o cached repository
|
||||||
|
// builder.Services.AddScoped<IWorkshopRepository, EfWorkshopRepository>();
|
||||||
builder.Services.AddControllers();
|
builder.Services.AddControllers();
|
||||||
builder.Services.AddEndpointsApiExplorer();
|
builder.Services.AddEndpointsApiExplorer();
|
||||||
builder.Services.AddSwaggerGen(o =>
|
builder.Services.AddSwaggerGen(o =>
|
||||||
82
Workshop10-API/Repositories/CachedWorkshopRepository.cs
Normal file
82
Workshop10-API/Repositories/CachedWorkshopRepository.cs
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
using CampusWorkshops.Api.Models;
|
||||||
|
using Microsoft.Extensions.Caching.Memory;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
namespace CampusWorkshops.Api.Repositories;
|
||||||
|
|
||||||
|
public sealed class CachedWorkshopRepository : IWorkshopRepository
|
||||||
|
{
|
||||||
|
private readonly IWorkshopRepository _inner;
|
||||||
|
private readonly IMemoryCache _cache;
|
||||||
|
private readonly TimeSpan _ttl;
|
||||||
|
|
||||||
|
public CachedWorkshopRepository(
|
||||||
|
IWorkshopRepository inner,
|
||||||
|
IMemoryCache cache,
|
||||||
|
IOptionsSnapshot<CampusWorkshops.Api.Services.CacheSettings> opts)
|
||||||
|
{
|
||||||
|
_inner = inner;
|
||||||
|
_cache = cache;
|
||||||
|
_ttl = TimeSpan.FromSeconds(opts.Value.DefaultTtlSeconds);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string KeyById(Guid id) => $"workshops:byId:{id}";
|
||||||
|
private static string KeyList(DateTimeOffset? from, DateTimeOffset? to, string? q)
|
||||||
|
=> $"workshops:list:{from?.ToUnixTimeSeconds()}:{to?.ToUnixTimeSeconds()}:{q?.Trim().ToLowerInvariant()}";
|
||||||
|
public async Task<IReadOnlyList<Workshop>> GetAllAsync(
|
||||||
|
DateTimeOffset? from, DateTimeOffset? to, string? q, CancellationToken ct)
|
||||||
|
{
|
||||||
|
// Implementação final
|
||||||
|
var key = KeyList(from, to, q);
|
||||||
|
if (_cache.TryGetValue(key, out IReadOnlyList<Workshop>? cached) && cached is not null)
|
||||||
|
return cached;
|
||||||
|
|
||||||
|
var data = await _inner.GetAllAsync(from, to, q, ct);
|
||||||
|
_cache.Set(key, data, _ttl);
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public async Task<Workshop?> GetByIdAsync(Guid id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var key = KeyById(id);
|
||||||
|
if (_cache.TryGetValue(key, out Workshop? cached) && cached is not null)
|
||||||
|
return cached;
|
||||||
|
|
||||||
|
var w = await _inner.GetByIdAsync(id, ct);
|
||||||
|
if (w is not null) _cache.Set(key, w, _ttl);
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ações de escrita: apenas encaminham e limpam entradas simples
|
||||||
|
public async Task<Workshop> AddAsync(Workshop workshop, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var w = await _inner.AddAsync(workshop, ct);
|
||||||
|
_cache.Remove(KeyById(w.Id));
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<Workshop?> UpdateAsync(Workshop workshop, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var w = await _inner.UpdateAsync(workshop, ct);
|
||||||
|
if (w is not null) _cache.Remove(KeyById(w.Id));
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> DeleteAsync(Guid id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var ok = await _inner.DeleteAsync(id, ct);
|
||||||
|
if (ok) _cache.Remove(KeyById(id));
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<bool> ExistsAsync(Guid id, CancellationToken ct)
|
||||||
|
=> _inner.ExistsAsync(id, ct);
|
||||||
|
|
||||||
|
public async Task<Workshop?> UpdatePartialAsync(Guid id, Action<Workshop> updateAction, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var w = await _inner.UpdatePartialAsync(id, updateAction, ct);
|
||||||
|
if (w is not null) _cache.Remove(KeyById(w.Id));
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
}
|
||||||
6
Workshop10-API/Services/CacheSettings.cs
Normal file
6
Workshop10-API/Services/CacheSettings.cs
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
namespace CampusWorkshops.Api.Services;
|
||||||
|
|
||||||
|
public sealed class CacheSettings
|
||||||
|
{
|
||||||
|
public int DefaultTtlSeconds { get; set; } = 15;
|
||||||
|
}
|
||||||
12
Workshop10-API/Services/PerRequestClock.cs
Normal file
12
Workshop10-API/Services/PerRequestClock.cs
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
namespace CampusWorkshops.Api.Services;
|
||||||
|
|
||||||
|
public interface IPerRequestClock
|
||||||
|
{
|
||||||
|
// Carimbo criado no CONSTRUTOR (não muda depois)
|
||||||
|
DateTimeOffset CreatedAt { get; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class PerRequestClock : IPerRequestClock
|
||||||
|
{
|
||||||
|
public DateTimeOffset CreatedAt { get; } = DateTimeOffset.UtcNow;
|
||||||
|
}
|
||||||
23
Workshop10-API/Services/ReportingSingleton.cs
Normal file
23
Workshop10-API/Services/ReportingSingleton.cs
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace CampusWorkshops.Api.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Singleton que recebe um Transient (IPerRequestClock).
|
||||||
|
/// Na prática, o Transient é resolvido uma única vez, na construção do Singleton,
|
||||||
|
/// e "vira" efetivamente singleton dentro dele.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ReportingSingleton
|
||||||
|
{
|
||||||
|
private readonly IPerRequestClock _clock;
|
||||||
|
|
||||||
|
public ReportingSingleton(IPerRequestClock clock)
|
||||||
|
{
|
||||||
|
_clock = clock;
|
||||||
|
}
|
||||||
|
|
||||||
|
public DateTimeOffset GetClockCreatedAt()
|
||||||
|
{
|
||||||
|
return _clock.CreatedAt;
|
||||||
|
}
|
||||||
|
}
|
||||||
9
Workshop10-API/Services/RequestId.cs
Normal file
9
Workshop10-API/Services/RequestId.cs
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
namespace CampusWorkshops.Api.Services;
|
||||||
|
|
||||||
|
public interface IRequestIdTransient { Guid Id { get; } }
|
||||||
|
public interface IRequestIdScoped { Guid Id { get; } }
|
||||||
|
public interface IRequestIdSingleton { Guid Id { get; } }
|
||||||
|
|
||||||
|
internal sealed class RequestIdTransient : IRequestIdTransient { public Guid Id { get; } = Guid.NewGuid(); }
|
||||||
|
internal sealed class RequestIdScoped : IRequestIdScoped { public Guid Id { get; } = Guid.NewGuid(); }
|
||||||
|
internal sealed class RequestIdSingleton : IRequestIdSingleton { public Guid Id { get; } = Guid.NewGuid(); }
|
||||||
@@ -8,7 +8,8 @@
|
|||||||
"Jwt": {
|
"Jwt": {
|
||||||
"Issuer": "CampusWorkshops",
|
"Issuer": "CampusWorkshops",
|
||||||
"Audience": "CampusWorkshops.Api",
|
"Audience": "CampusWorkshops.Api",
|
||||||
"Key": "some-key"
|
"Key": "some-key-that-is-super-secret-always-secured"
|
||||||
},
|
},
|
||||||
|
"Cache": { "DefaultTtlSeconds": 15 },
|
||||||
"AllowedHosts": "*"
|
"AllowedHosts": "*"
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user