Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
<PackageVersion Include="Microsoft.Extensions.ServiceDiscovery.Yarp" Version="10.10.0" />
<PackageVersion Include="WolverineFx" Version="6.41.0" />
<PackageVersion Include="WolverineFx.RabbitMQ" Version="6.41.0" />
<!-- Compilateur Roslyn utilisé par Wolverine pour générer le code des handlers au démarrage (mode Dynamic) -->
<PackageVersion Include="WolverineFx.RuntimeCompilation" Version="6.41.0" />
<PackageVersion Include="WolverineFx.EntityFrameworkCore" Version="6.41.0" />
<PackageVersion Include="WolverineFx.Postgresql" Version="6.41.0" />
</ItemGroup>
Expand All @@ -41,6 +43,8 @@
<ItemGroup Label="Persistance">
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="10.0.12" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.12" />
<!-- Épinglé : Npgsql tire la 10.0.11, EF Design la 10.0.12 -> une seule version pour toute la solution -->
<PackageVersion Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.12" />
</ItemGroup>

<ItemGroup Label="Tests">
Expand Down
8 changes: 8 additions & 0 deletions TaskFlow.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
<Project Path="src/AppHost/TaskFlow.AppHost/TaskFlow.AppHost.csproj" />
</Folder>
<Folder Name="/src/BuildingBlocks/">
<Project Path="src/BuildingBlocks/TaskFlow.Api.Common/TaskFlow.Api.Common.csproj" />
<Project Path="src/BuildingBlocks/TaskFlow.ServiceDefaults/TaskFlow.ServiceDefaults.csproj" />
<Project Path="src/BuildingBlocks/TaskFlow.SharedKernel/TaskFlow.SharedKernel.csproj" />
</Folder>
Expand All @@ -18,8 +19,15 @@
<Project Path="src/Services/Projects/TaskFlow.Projects.Domain/TaskFlow.Projects.Domain.csproj" />
<Project Path="src/Services/Projects/TaskFlow.Projects.Infrastructure/TaskFlow.Projects.Infrastructure.csproj" />
</Folder>
<Folder Name="/src/Services/Tasks/">
<Project Path="src/Services/Tasks/TaskFlow.Tasks.Api/TaskFlow.Tasks.Api.csproj" />
<Project Path="src/Services/Tasks/TaskFlow.Tasks.Application/TaskFlow.Tasks.Application.csproj" />
<Project Path="src/Services/Tasks/TaskFlow.Tasks.Domain/TaskFlow.Tasks.Domain.csproj" />
<Project Path="src/Services/Tasks/TaskFlow.Tasks.Infrastructure/TaskFlow.Tasks.Infrastructure.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/TaskFlow.ArchitectureTests/TaskFlow.ArchitectureTests.csproj" />
<Project Path="tests/TaskFlow.Projects.UnitTests/TaskFlow.Projects.UnitTests.csproj" />
<Project Path="tests/TaskFlow.Tasks.UnitTests/TaskFlow.Tasks.UnitTests.csproj" />
</Folder>
</Solution>
13 changes: 13 additions & 0 deletions dotnet-tools.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "10.0.12",
"commands": [
"dotnet-ef"
],
"rollForward": false
}
}
}
11 changes: 11 additions & 0 deletions src/AppHost/TaskFlow.AppHost/AppHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

// Une base par service : aucun service ne lit la base d'un autre.
var projectsDb = postgres.AddDatabase("projectsdb");
var tasksDb = postgres.AddDatabase("tasksdb");

// Broker de messages. Le plugin "management" ajoute l'interface web (files, débits, messages en attente).
var rabbitmq = builder.AddRabbitMQ("rabbitmq")
Expand All @@ -24,11 +25,21 @@
.WaitFor(rabbitmq)
.WithHttpHealthCheck("/health");

// Tasks écoute les événements de Projects via RabbitMQ : aucune référence directe entre les deux services.
var tasksApi = builder.AddProject<Projects.TaskFlow_Tasks_Api>("tasks-api")
.WithReference(tasksDb)
.WithReference(rabbitmq)
.WaitFor(tasksDb)
.WaitFor(rabbitmq)
.WithHttpHealthCheck("/health");

// ── Gateway : seul point d'entrée du front ──

var gateway = builder.AddProject<Projects.TaskFlow_Gateway>("gateway")
.WithReference(projectsApi)
.WithReference(tasksApi)
.WaitFor(projectsApi)
.WaitFor(tasksApi)
.WithHttpHealthCheck("/health");

// ── Front Angular : ne connaît que la Gateway ──
Expand Down
1 change: 1 addition & 0 deletions src/AppHost/TaskFlow.AppHost/TaskFlow.AppHost.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
<ItemGroup>
<ProjectReference Include="..\..\Gateway\TaskFlow.Gateway\TaskFlow.Gateway.csproj" />
<ProjectReference Include="..\..\Services\Projects\TaskFlow.Projects.Api\TaskFlow.Projects.Api.csproj" />
<ProjectReference Include="..\..\Services\Tasks\TaskFlow.Tasks.Api\TaskFlow.Tasks.Api.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -1,17 +1,30 @@
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace TaskFlow.Projects.Api.Infrastructure;
namespace TaskFlow.Api.Common;

/// <summary>
/// Filet de sécurité pour les exceptions non prévues : log complet côté serveur,
/// réponse 500 générique côté client (aucun détail technique exposé).
/// </summary>
internal sealed partial class GlobalExceptionHandler(
public sealed partial class GlobalExceptionHandler(
IProblemDetailsService problemDetailsService,
ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
// Requête mal formée (JSON invalide, corps illisible...) : c'est une erreur du CLIENT -> 400, pas 500.
if (exception is BadHttpRequestException badRequest)
{
httpContext.Response.StatusCode = badRequest.StatusCode;
return await problemDetailsService.TryWriteAsync(new ProblemDetailsContext
{
HttpContext = httpContext,
ProblemDetails = { Title = "Requête invalide.", Status = badRequest.StatusCode },
});
}

LogUnhandledException(logger, httpContext.Request.Path, exception);

httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Microsoft.AspNetCore.Http;
using TaskFlow.SharedKernel;

namespace TaskFlow.Projects.Api.Infrastructure;
namespace TaskFlow.Api.Common;

/// <summary>
/// Traduit un <see cref="Result"/> en échec vers une réponse HTTP ProblemDetails.
Expand Down
13 changes: 13 additions & 0 deletions src/BuildingBlocks/TaskFlow.Api.Common/TaskFlow.Api.Common.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">

<!-- Briques HTTP communes à tous les microservices : erreurs ProblemDetails, Result -> HTTP, validation. -->
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\TaskFlow.SharedKernel\TaskFlow.SharedKernel.csproj" />
</ItemGroup>

</Project>
17 changes: 17 additions & 0 deletions src/BuildingBlocks/TaskFlow.Api.Common/ValidationExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using FluentValidation;
using Microsoft.AspNetCore.Http;

namespace TaskFlow.Api.Common;

public static class ValidationExtensions
{
/// <summary>
/// Valide une requête avec son validator FluentValidation.
/// Renvoie <c>null</c> si elle est valide, sinon une réponse 400 ValidationProblem listant les erreurs par champ.
/// </summary>
public static async Task<IResult?> ValidateRequestAsync<T>(this IValidator<T> validator, T request, CancellationToken ct)
{
var result = await validator.ValidateAsync(request, ct);
return result.IsValid ? null : TypedResults.ValidationProblem(result.ToDictionary());
}
}
13 changes: 13 additions & 0 deletions src/Gateway/TaskFlow.Gateway/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,26 @@
"projects": {
"ClusterId": "projects",
"Match": { "Path": "/api/projects/{**catch-all}" }
},
"projects-root": {
"ClusterId": "projects",
"Match": { "Path": "/api/projects" }
},
"tasks": {
"ClusterId": "tasks",
"Match": { "Path": "/api/tasks/{**catch-all}" }
}
},
"Clusters": {
"projects": {
"Destinations": {
"projects-api": { "Address": "https+http://projects-api" }
}
},
"tasks": {
"Destinations": {
"tasks-api": { "Address": "https+http://tasks-api" }
}
}
}
}
Expand Down
29 changes: 26 additions & 3 deletions src/Services/Projects/TaskFlow.Projects.Api/Program.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,34 @@
using Scalar.AspNetCore;
using TaskFlow.Api.Common;
using TaskFlow.Projects.Api.Infrastructure;
using TaskFlow.Projects.Contracts;
using TaskFlow.Projects.Infrastructure;
using Wolverine;
using Wolverine.RabbitMQ;

var builder = WebApplication.CreateBuilder(args);

// Aspire : OpenTelemetry, health checks, service discovery, résilience HTTP.
builder.AddServiceDefaults();

// Connexion RabbitMQ injectée par l'AppHost : ajoute health check et traces.
// (À l'étape 2, Wolverine utilisera cette même connexion pour publier les événements.)
// Client RabbitMQ Aspire : health check "RabbitMQ" visible dans /health.
builder.AddRabbitMQClient("rabbitmq");

// Wolverine : bus de messages. Ce service PUBLIE, il n'écoute aucune queue pour l'instant.
builder.Host.UseWolverine(opts =>
{
var rabbitMq = builder.Configuration.GetConnectionString("rabbitmq")
?? throw new InvalidOperationException("Chaîne de connexion 'rabbitmq' absente : lancer via l'AppHost Aspire.");

opts.UseRabbitMq(new Uri(rabbitMq))
// Crée les exchanges/queues déclarés s'ils n'existent pas encore.
.AutoProvision()
// Fanout : chaque service abonné reçoit sa propre copie de l'événement.
.DeclareExchange(ProjectsExchanges.ProjectCreated, exchange => exchange.ExchangeType = ExchangeType.Fanout);

opts.PublishMessage<ProjectCreated>().ToRabbitExchange(ProjectsExchanges.ProjectCreated);
});

// Erreurs au format standard ProblemDetails (RFC 9457).
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
Expand All @@ -21,6 +39,11 @@

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
await app.Services.MigrateProjectsDatabaseAsync();
}

app.UseExceptionHandler();
app.UseStatusCodePages();

Expand All @@ -36,4 +59,4 @@
app.MapInfoEndpoint();
app.MapProjectsModule();

app.Run();
await app.RunAsync();
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,14 @@
<ItemGroup>
<PackageReference Include="Aspire.RabbitMQ.Client" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Scalar.AspNetCore" />
<PackageReference Include="WolverineFx.RabbitMQ" />
<PackageReference Include="WolverineFx.RuntimeCompilation" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\BuildingBlocks\TaskFlow.ServiceDefaults\TaskFlow.ServiceDefaults.csproj" />
<ProjectReference Include="..\..\..\BuildingBlocks\TaskFlow.Api.Common\TaskFlow.Api.Common.csproj" />
<ProjectReference Include="..\TaskFlow.Projects.Infrastructure\TaskFlow.Projects.Infrastructure.csproj" />
<ProjectReference Include="..\TaskFlow.Projects.Contracts\TaskFlow.Projects.Contracts.csproj" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using TaskFlow.Projects.Domain;

namespace TaskFlow.Projects.Application.Abstractions;

/// <summary>
/// Port de persistance défini par l'Application, implémenté par l'Infrastructure (EF Core).
/// L'Application ne connaît donc ni EF Core ni Postgres.
/// </summary>
public interface IProjectRepository
{
void Add(Project project);

Task<IReadOnlyList<Project>> ListAsync(CancellationToken ct);

Task SaveChangesAsync(CancellationToken ct);
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using FluentValidation;
using Microsoft.Extensions.DependencyInjection;
using TaskFlow.Projects.Application.Features;

namespace TaskFlow.Projects.Application;

Expand All @@ -10,8 +11,9 @@ public static IServiceCollection AddProjectsApplication(this IServiceCollection
// Enregistre automatiquement tous les AbstractValidator<T> du module.
services.AddValidatorsFromAssembly(typeof(DependencyInjection).Assembly, includeInternalTypes: true);

// TODO (toi) : enregistrer ici les handlers de tes features, ex.
// services.AddScoped<CreateProject.Handler>();
// Un handler par feature qui modifie l'état.
services.AddScoped<CreateProject.Handler>();

return services;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
using FluentValidation;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using TaskFlow.Api.Common;
using TaskFlow.Projects.Application.Abstractions;
using TaskFlow.Projects.Contracts;
using TaskFlow.Projects.Domain;
using TaskFlow.SharedKernel;
using Wolverine;

namespace TaskFlow.Projects.Application.Features;

/// <summary>
/// Vertical slice « créer un projet » : requête, validation, traitement et endpoint au même endroit.
/// POST /api/projects { "name": "Refonte du site" }
/// </summary>
public static class CreateProject
{
public sealed record Command(string Name);

public sealed record Response(Guid Id, string Name, DateTimeOffset CreatedAt);

/// <summary>Validation de FORME (champ présent, longueur). Les règles MÉTIER restent dans l'agrégat.</summary>
public sealed class Validator : AbstractValidator<Command>
{
public Validator()
{
RuleFor(c => c.Name).NotEmpty().MaximumLength(Project.NameMaxLength);
}
}

public sealed class Handler(IProjectRepository projects, IMessageBus bus, TimeProvider clock)
{
public async Task<Result<Response>> Handle(Command command, CancellationToken ct)
{
var created = Project.Create(command.Name, clock.GetUtcNow());
if (created.IsFailure)
{
return created.Error;
}

var project = created.Value;
projects.Add(project);
await projects.SaveChangesAsync(ct);

// Informe les autres services (Tasks créera le board du projet).
// ⚠ Sans outbox, un crash entre SaveChanges et PublishAsync perdrait l'événement :
// c'est exactement ce que l'étape 3 corrige (outbox Wolverine, même transaction).
await bus.PublishAsync(new ProjectCreated(project.Id.Value, project.Name, project.CreatedAt));

return new Response(project.Id.Value, project.Name, project.CreatedAt);
}
}

public static void Map(RouteGroupBuilder group) =>
group.MapPost("/", async Task<IResult> (Command command, IValidator<Command> validator, Handler handler, CancellationToken ct) =>
{
if (await validator.ValidateRequestAsync(command, ct) is { } invalid)
{
return invalid;
}

var result = await handler.Handle(command, ct);
return result.IsSuccess
? TypedResults.Created($"/api/projects/{result.Value.Id}", result.Value)
: result.ToProblem();
})
.WithName("CreateProject")
.WithSummary("Crée un projet et publie l'événement ProjectCreated sur RabbitMQ.");
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using TaskFlow.Projects.Application.Abstractions;

namespace TaskFlow.Projects.Application.Features;

/// <summary>GET /api/projects : liste des projets (du plus récent au plus ancien).</summary>
public static class GetProjects
{
public sealed record Item(Guid Id, string Name, DateTimeOffset CreatedAt);

public static void Map(RouteGroupBuilder group) =>
group.MapGet("/", async (IProjectRepository projects, CancellationToken ct) =>
{
var list = await projects.ListAsync(ct);
return TypedResults.Ok(list.Select(p => new Item(p.Id.Value, p.Name, p.CreatedAt)).ToList());
})
.WithName("GetProjects");
}
Loading
Loading