From 13c3b068929a24325e3719b46698645d9f647482 Mon Sep 17 00:00:00 2001 From: Anas ABBASSI Date: Tue, 29 Sep 2026 15:55:59 +0200 Subject: [PATCH] =?UTF-8?q?feat:=20=C3=A9tape=201=20microservices=20(Gatew?= =?UTF-8?q?ay=20YARP,=20RabbitMQ,=20service=20Projects)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Restructuration : src/AppHost, src/BuildingBlocks, src/Gateway, src/Services/Projects - Gateway YARP avec service discovery Aspire : /api/projects/* -> projects-api - RabbitMQ 4 (plugin management) dans l'AppHost, connexion et health check dans Projects - Base dédiée projectsdb, projet TaskFlow.Projects.Contracts pour les événements publics - Tests d'architecture : frontières entre microservices - Front Angular : proxy vers la Gateway - Mémo technique v2 (microservices, RabbitMQ, Wolverine) - Http.Resilience et ServiceDiscovery 10.10 --- .vscode/launch.json | 4 +- .vscode/tasks.json | 2 +- Directory.Packages.props | 15 +- README.md | 54 ++-- TaskFlow.slnx | 27 +- docs/TaskFlow_Memo_Technique_v2.html | 253 ++++++++++++++++++ src/AppHost/TaskFlow.AppHost/AppHost.cs | 42 +++ .../Properties/launchSettings.json | 0 .../TaskFlow.AppHost/TaskFlow.AppHost.csproj | 4 +- .../appsettings.Development.json | 0 .../TaskFlow.AppHost/appsettings.json | 0 .../TaskFlow.AppHost/aspire.config.json | 0 .../TaskFlow.ServiceDefaults/Extensions.cs | 0 .../TaskFlow.ServiceDefaults.csproj | 0 .../TaskFlow.SharedKernel/AggregateRoot.cs | 0 .../TaskFlow.SharedKernel/Entity.cs | 0 .../TaskFlow.SharedKernel/Error.cs | 0 .../TaskFlow.SharedKernel/IDomainEvent.cs | 0 .../TaskFlow.SharedKernel/Result.cs | 0 .../TaskFlow.SharedKernel.csproj | 0 src/Gateway/TaskFlow.Gateway/Program.cs | 30 +++ .../Properties/launchSettings.json | 23 ++ .../TaskFlow.Gateway/TaskFlow.Gateway.csproj | 13 + .../appsettings.Development.json | 0 src/Gateway/TaskFlow.Gateway/appsettings.json | 25 ++ .../Infrastructure/GlobalExceptionHandler.cs | 2 +- .../Infrastructure/InfoEndpoint.cs | 22 ++ .../Infrastructure/ResultExtensions.cs | 2 +- .../TaskFlow.Projects.Api}/Program.cs | 7 +- .../Properties/launchSettings.json | 0 .../TaskFlow.Projects.Api.csproj} | 8 +- .../TaskFlow.Projects.Api.http} | 0 .../appsettings.Development.json | 8 + .../TaskFlow.Projects.Api}/appsettings.json | 0 .../DependencyInjection.cs | 0 .../ProjectsEndpoints.cs | 0 .../TaskFlow.Projects.Application.csproj | 0 .../TaskFlow.Projects.Contracts.csproj | 10 + .../TaskFlow.Projects.Domain.csproj | 2 +- .../Persistence/ProjectsDbContext.cs | 0 .../ProjectsModule.cs | 4 +- .../TaskFlow.Projects.Infrastructure.csproj | 0 .../Infrastructure/InfoEndpoint.cs | 22 -- src/TaskFlow.AppHost/AppHost.cs | 23 -- .../LayerDependencyTests.cs | 10 +- .../MicroserviceBoundaryTests.cs | 36 +++ .../TaskFlow.ArchitectureTests.csproj | 3 +- .../TaskFlow.Projects.UnitTests.csproj | 2 +- web/taskflow-ui/proxy.conf.mjs | 20 +- 49 files changed, 567 insertions(+), 106 deletions(-) create mode 100644 docs/TaskFlow_Memo_Technique_v2.html create mode 100644 src/AppHost/TaskFlow.AppHost/AppHost.cs rename src/{ => AppHost}/TaskFlow.AppHost/Properties/launchSettings.json (100%) rename src/{ => AppHost}/TaskFlow.AppHost/TaskFlow.AppHost.csproj (62%) rename src/{TaskFlow.Api => AppHost/TaskFlow.AppHost}/appsettings.Development.json (100%) rename src/{ => AppHost}/TaskFlow.AppHost/appsettings.json (100%) rename src/{ => AppHost}/TaskFlow.AppHost/aspire.config.json (100%) rename src/{ => BuildingBlocks}/TaskFlow.ServiceDefaults/Extensions.cs (100%) rename src/{ => BuildingBlocks}/TaskFlow.ServiceDefaults/TaskFlow.ServiceDefaults.csproj (100%) rename src/{ => BuildingBlocks}/TaskFlow.SharedKernel/AggregateRoot.cs (100%) rename src/{ => BuildingBlocks}/TaskFlow.SharedKernel/Entity.cs (100%) rename src/{ => BuildingBlocks}/TaskFlow.SharedKernel/Error.cs (100%) rename src/{ => BuildingBlocks}/TaskFlow.SharedKernel/IDomainEvent.cs (100%) rename src/{ => BuildingBlocks}/TaskFlow.SharedKernel/Result.cs (100%) rename src/{ => BuildingBlocks}/TaskFlow.SharedKernel/TaskFlow.SharedKernel.csproj (100%) create mode 100644 src/Gateway/TaskFlow.Gateway/Program.cs create mode 100644 src/Gateway/TaskFlow.Gateway/Properties/launchSettings.json create mode 100644 src/Gateway/TaskFlow.Gateway/TaskFlow.Gateway.csproj rename src/{TaskFlow.AppHost => Gateway/TaskFlow.Gateway}/appsettings.Development.json (100%) create mode 100644 src/Gateway/TaskFlow.Gateway/appsettings.json rename src/{TaskFlow.Api => Services/Projects/TaskFlow.Projects.Api}/Infrastructure/GlobalExceptionHandler.cs (96%) create mode 100644 src/Services/Projects/TaskFlow.Projects.Api/Infrastructure/InfoEndpoint.cs rename src/{TaskFlow.Api => Services/Projects/TaskFlow.Projects.Api}/Infrastructure/ResultExtensions.cs (96%) rename src/{TaskFlow.Api => Services/Projects/TaskFlow.Projects.Api}/Program.cs (75%) rename src/{TaskFlow.Api => Services/Projects/TaskFlow.Projects.Api}/Properties/launchSettings.json (100%) rename src/{TaskFlow.Api/TaskFlow.Api.csproj => Services/Projects/TaskFlow.Projects.Api/TaskFlow.Projects.Api.csproj} (55%) rename src/{TaskFlow.Api/TaskFlow.Api.http => Services/Projects/TaskFlow.Projects.Api/TaskFlow.Projects.Api.http} (100%) create mode 100644 src/Services/Projects/TaskFlow.Projects.Api/appsettings.Development.json rename src/{TaskFlow.Api => Services/Projects/TaskFlow.Projects.Api}/appsettings.json (100%) rename src/{Modules => Services}/Projects/TaskFlow.Projects.Application/DependencyInjection.cs (100%) rename src/{Modules => Services}/Projects/TaskFlow.Projects.Application/ProjectsEndpoints.cs (100%) rename src/{Modules => Services}/Projects/TaskFlow.Projects.Application/TaskFlow.Projects.Application.csproj (100%) create mode 100644 src/Services/Projects/TaskFlow.Projects.Contracts/TaskFlow.Projects.Contracts.csproj rename src/{Modules => Services}/Projects/TaskFlow.Projects.Domain/TaskFlow.Projects.Domain.csproj (58%) rename src/{Modules => Services}/Projects/TaskFlow.Projects.Infrastructure/Persistence/ProjectsDbContext.cs (100%) rename src/{Modules => Services}/Projects/TaskFlow.Projects.Infrastructure/ProjectsModule.cs (83%) rename src/{Modules => Services}/Projects/TaskFlow.Projects.Infrastructure/TaskFlow.Projects.Infrastructure.csproj (100%) delete mode 100644 src/TaskFlow.Api/Infrastructure/InfoEndpoint.cs delete mode 100644 src/TaskFlow.AppHost/AppHost.cs create mode 100644 tests/TaskFlow.ArchitectureTests/MicroserviceBoundaryTests.cs diff --git a/.vscode/launch.json b/.vscode/launch.json index 1a16329..531a864 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,12 +1,12 @@ { - // F5 : lance toute l'application (Postgres + API + front) avec le débogueur attaché. + // F5 : lance toute l'application (Postgres, RabbitMQ, services, Gateway, front) avec le débogueur attaché. "version": "0.2.0", "configurations": [ { "name": "TaskFlow (Aspire)", "type": "aspire", "request": "launch", - "program": "${workspaceFolder}/src/TaskFlow.AppHost/TaskFlow.AppHost.csproj" + "program": "${workspaceFolder}/src/AppHost/TaskFlow.AppHost/TaskFlow.AppHost.csproj" } ] } diff --git a/.vscode/tasks.json b/.vscode/tasks.json index e5e43cf..cc7a3fa 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -5,7 +5,7 @@ { "label": "TaskFlow : lancer (Aspire)", "type": "shell", - "command": "dotnet run --project src/TaskFlow.AppHost", + "command": "dotnet run --project src/AppHost/TaskFlow.AppHost", "isBackground": true, "problemMatcher": [] }, diff --git a/Directory.Packages.props b/Directory.Packages.props index 65120db..e889fae 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -9,11 +9,22 @@ + + + + + + + + + + + - - + + diff --git a/README.md b/README.md index ec1254e..6ade860 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,27 @@ # TaskFlow -Outil de gestion de projets (style Jira/Trello), projet de formation .NET 10 + Angular 22. -Voir le mémo technique : [docs/TaskFlow_Memo_Technique_v1.html](docs/TaskFlow_Memo_Technique_v1.html). +Outil de gestion de projets (style Jira/Trello) en **microservices**, projet de formation .NET 10 + Angular 22. + +- Mémo v1, les fondations : [docs/TaskFlow_Memo_Technique_v1.html](docs/TaskFlow_Memo_Technique_v1.html) +- Mémo v2, les microservices et RabbitMQ : [docs/TaskFlow_Memo_Technique_v2.html](docs/TaskFlow_Memo_Technique_v2.html) + +## Architecture + +``` +Angular ──► Gateway (YARP) ──► Projects API ──► projectsdb (Postgres) + │ + └────────► RabbitMQ 4 ◄── (Tasks, Notifications, Reports : à venir) +``` ## Stack | Couche | Technologies | |---|---| | Orchestration locale | Aspire 13 (AppHost, dashboard, OpenTelemetry) | -| API | ASP.NET Core 10 Minimal APIs, ProblemDetails, OpenAPI + Scalar | -| Architecture | Modular monolith, Clean Architecture + Vertical Slices | -| Données | PostgreSQL 18 (conteneur Podman), EF Core 10 | +| Gateway | YARP 2 + service discovery Aspire | +| Services | ASP.NET Core 10 Minimal APIs, Clean Architecture + Vertical Slices | +| Messagerie | RabbitMQ 4, Wolverine 6 (outbox, sagas) | +| Données | PostgreSQL 18, une base par service, EF Core 10 | | Front | Angular 22 zoneless, signals, `httpResource`, Vitest, ESLint | | Tests | xUnit v3, Shouldly, NetArchTest | | CI | GitHub Actions, Dependabot | @@ -19,17 +30,24 @@ Voir le mémo technique : [docs/TaskFlow_Memo_Technique_v1.html](docs/TaskFlow_M ``` src/ - TaskFlow.AppHost/ Orchestration Aspire (Postgres + API + front) - TaskFlow.ServiceDefaults/ OpenTelemetry, health checks, résilience - TaskFlow.Api/ Hôte HTTP : Program.cs, gestion d'erreurs - TaskFlow.SharedKernel/ Entity, AggregateRoot, Result, Error, DomainEvent - Modules/Projects/ Module Projects : Domain / Application / Infrastructure -web/taskflow-ui/ Application Angular (core / features / shared) -tests/ Tests d'architecture et unitaires + AppHost/TaskFlow.AppHost/ Orchestration Aspire (Postgres, RabbitMQ, services, gateway, front) + BuildingBlocks/ + TaskFlow.ServiceDefaults/ OpenTelemetry, health checks, résilience + TaskFlow.SharedKernel/ Entity, AggregateRoot, Result, Error, DomainEvent + Gateway/TaskFlow.Gateway/ YARP : /api/projects/* -> projects-api + Services/Projects/ + TaskFlow.Projects.Api/ Hôte HTTP du service + TaskFlow.Projects.Domain/ + TaskFlow.Projects.Application/ + TaskFlow.Projects.Infrastructure/ + TaskFlow.Projects.Contracts/ Événements d'intégration publics +web/taskflow-ui/ Application Angular (core / features / shared) +tests/ Tests d'architecture et unitaires ``` -Règle de dépendance, vérifiée par `tests/TaskFlow.ArchitectureTests` : -`Domain ← Application ← Infrastructure ← Api`. +Règles vérifiées par `tests/TaskFlow.ArchitectureTests` : +- dans un service : `Domain ← Application ← Infrastructure ← Api` ; +- entre services : on ne référence que le projet `*.Contracts` d'un autre service, et la Gateway n'en référence aucun. ## Prérequis @@ -41,11 +59,11 @@ Règle de dépendance, vérifiée par `tests/TaskFlow.ArchitectureTests` : ## Lancer l'application ```bash -dotnet run --project src/TaskFlow.AppHost +dotnet run --project src/AppHost/TaskFlow.AppHost ``` -Le lien du dashboard Aspire s'affiche dans la console. Il donne accès à Postgres, à l'API (`/scalar` pour tester les endpoints) -et au front Angular. +Ou **F5** dans VS Code. Le lien du dashboard Aspire s'affiche dans la console. Il donne accès à tous les services, +à l'interface d'administration de RabbitMQ et au front Angular. ## Tests @@ -67,6 +85,6 @@ npm test -- --watch=false ## Particularités du poste de travail -- **Podman** remplace Docker : `ASPIRE_CONTAINER_RUNTIME=podman` est défini dans `src/TaskFlow.AppHost/Properties/launchSettings.json`. +- **Podman** remplace Docker : `ASPIRE_CONTAINER_RUNTIME=podman` est défini dans `src/AppHost/TaskFlow.AppHost/Properties/launchSettings.json`. - **Pas de `.exe` pour les projets applicatifs** (`UseAppHost=false`, voir `Directory.Build.targets`) : ils sont lancés via `dotnet X.dll`. - **Proxy d'entreprise** : le registre npm doit être en `https://registry.npmjs.org/`. diff --git a/TaskFlow.slnx b/TaskFlow.slnx index 3b86d3c..32b160c 100644 --- a/TaskFlow.slnx +++ b/TaskFlow.slnx @@ -1,15 +1,22 @@ - - - - + + + - - - - - - + + + + + + + + + + + + + + diff --git a/docs/TaskFlow_Memo_Technique_v2.html b/docs/TaskFlow_Memo_Technique_v2.html new file mode 100644 index 0000000..0e606a7 --- /dev/null +++ b/docs/TaskFlow_Memo_Technique_v2.html @@ -0,0 +1,253 @@ + + + + + +TaskFlow Microservices + + + +
+

TaskFlow : passage aux microservices

+

Version 2 du mémo, du 29/09/2026. Elle complète la v1 (fondations .NET, Angular, DDD, CI) : ici, on découpe TaskFlow en services qui communiquent par RabbitMQ.

+ + + +
+

1. Pourquoi des microservices, et à quel prix

+

Un microservice est une application déployable seule, qui possède ses propres données et qui correspond à un bounded context du domaine, c'est-à-dire une partie du métier avec son propre vocabulaire.

+
+ + + + + +
Ce qu'on gagneCe que ça coûte
Déploiement indépendant de chaque servicePlus de pièces à faire tourner, surveiller et versionner
Scalabilité ciblée (Notifications peut tourner en 5 instances)Réseau non fiable : latence, pannes partielles
Isolation des pannes : si Notifications tombe, le board fonctionne encoreCohérence éventuelle : les données se synchronisent avec un léger décalage
Équipes autonomes par serviceDébogage distribué : il faut du traçage de bout en bout
+
Le piège n°1, le monolithe distribué. Si les services s'appellent tous en HTTP synchrone en chaîne, ou partagent une base, on cumule les inconvénients des deux mondes. La règle : chaque service doit pouvoir répondre même si les autres sont en panne, au moins en mode dégradé.
+
+ +
+

2. Architecture cible

+
                      ┌────────────────────┐
+  Angular 22  ──────► │ API Gateway (YARP) │  point d'entrée unique, auth, rate limiting
+                      └─────────┬──────────┘
+          ┌─────────────────────┼────────────────────┐
+          ▼                     ▼                    ▼
+   ┌──────────────┐     ┌──────────────┐     ┌────────────────────┐
+   │ Projects API │     │  Tasks API   │     │ Notifications      │
+   │  projectsdb  │     │   tasksdb    │     │ Worker + SignalR   │
+   └──────┬───────┘     └──────┬───────┘     └─────────┬──────────┘
+          │  publie            │  publie / écoute      │  écoute
+          └────────────► RabbitMQ 4 ◄──────────────────┘
+                     (événements d'intégration)
+
+ + + + + +
ServiceResponsabilitéPublieÉcoute
ProjectsWorkspaces, projets, membres, rôlesProjectCreated, ProjectArchived, MemberAdded, MemberRemoved—
TasksTâches, colonnes du board, commentairesTaskAssigned, TaskMoved, CommentAddedProjectCreated (crée le board), ProjectArchived, MemberRemoved (désassigne)
NotificationsE-mails simulés, notifications temps réel—Tous les événements utiles aux utilisateurs
GatewayRoutage, auth, CORS, rate limiting——
+
+ +
+

3. Stack (100 % gratuite)

+
+ + + + + + + + +
BesoinChoixÀ retenir
BrokerRabbitMQ 4, quorum queuesFiles répliquées (algorithme Raft) : le type recommandé aujourd'hui, les files « classic mirrored » ont été supprimées dans la v4.
Messagerie .NETWolverine 6 (WolverineFx.RabbitMQ, licence MIT)Handlers par convention, outbox et inbox transactionnels, retries, sagas, dead-letter. MassTransit v9 est payant.
Outbox persistanteWolverineFx.EntityFrameworkCore + WolverineFx.PostgresqlL'événement est écrit dans la même transaction que les données métier.
API GatewayYARP 2 + Microsoft.Extensions.ServiceDiscovery.YarpReverse proxy .NET de Microsoft. Les routes pointent vers https+http://projects-api, résolu par Aspire.
Orchestration localeAspire 13 : AddRabbitMQ().WithManagementPlugin()Un seul dotnet run lance tous les services, avec l'interface d'administration de RabbitMQ.
Contrat des événementsCloudEvents (enveloppe) + AsyncAPI (documentation)AsyncAPI est à RabbitMQ ce qu'OpenAPI est à REST.
TestsTestcontainers (Postgres, RabbitMQ)Les tests d'intégration tournent contre de vrais conteneurs.
+
Et Kafka ou NATS ? Kafka est un journal d'événements, qui sert à rejouer l'historique et à traiter de gros volumes. RabbitMQ est un routeur de messages, fait pour la logique métier et les files de travail. Pour TaskFlow, RabbitMQ est le bon outil. Tu pourras comparer avec les RabbitMQ Streams, qui ressemblent à Kafka, en bonus.
+
+ +
+

4. Synchrone ou asynchrone ?

+
+ + + + +
Synchrone (HTTP, gRPC)Asynchrone (RabbitMQ)
QuandL'appelant a besoin de la réponse tout de suite pour continuer (requête de lecture)On informe que quelque chose s'est passé, et les autres réagissent quand ils peuvent
CouplageFort : si la cible tombe, l'appelant échoueFaible : les messages attendent dans la file
Dans TaskFlowGateway → services ; Tasks qui vérifie « ce projet existe-t-il ? » (avec cache)Tout ce qui se déclenche en réaction à un événement
+

Commande ou événement ?

+
    +
  • Événement (ProjectCreated, au passé) : un fait accompli, publié à tous les abonnés. L'émetteur ne sait pas qui écoute.
  • +
  • Commande (SendWelcomeEmail, à l'impératif) : une demande envoyée à un destinataire précis.
  • +
+

Événement de domaine ou d'intégration ?

+
    +
  • Événement de domaine (v1, IDomainEvent) : interne au service, en mémoire, riche en types du domaine.
  • +
  • Événement d'intégration : public, sérialisé, versionné, et composé uniquement de types simples (Guid, string, dates). Il vit dans le projet *.Contracts du service émetteur. C'est un contrat : on ne supprime ni ne renomme jamais un champ, on en ajoute.
  • +
+
+ +
+

5. RabbitMQ : les notions à retenir

+
Producteur ──► Exchange ──(binding + routing key)──► Queue ──► Consommateur
+                 │
+                 ├─ fanout : copie à toutes les queues liées (publish/subscribe)
+                 ├─ direct : routing key exacte
+                 └─ topic  : motif, ex. "projects.*.created"
+
    +
  • Une queue par service consommateur (tasks.project-created), pas par événement partagé : chaque service reçoit sa propre copie.
  • +
  • Ack manuel : le message n'est retiré de la file qu'après un traitement réussi. En cas de crash, il est redistribué.
  • +
  • Prefetch : le nombre de messages envoyés d'avance à un consommateur. Il règle le compromis entre débit et équité.
  • +
  • Dead-letter exchange (DLX) : là où partent les messages qui échouent après N tentatives. On les inspecte et on les rejoue.
  • +
  • Quorum queues : durables et répliquées, à utiliser par défaut. Wolverine les déclare pour toi.
  • +
  • L'interface d'administration (plugin management) montre les files, les débits et les messages en attente : ton meilleur outil de débogage.
  • +
+
+ +
+

6. Fiabilité : les patterns indispensables

+

Transactional outbox

+
BEGIN;
+  INSERT INTO projects.projects ...;          -- données métier
+  INSERT INTO wolverine.outgoing ...;         -- l'événement, même transaction
+COMMIT;
+-- un agent Wolverine lit la table outgoing et publie sur RabbitMQ, avec retries
+

Sans outbox, un crash entre le COMMIT et le Publish perd l'événement, et les autres services ne sauront jamais que le projet existe.

+

Idempotence (inbox)

+

RabbitMQ garantit une livraison au moins une fois : un message peut arriver deux fois. Chaque handler doit donc produire le même résultat s'il est rejoué. Deux façons d'y parvenir : l'inbox durable de Wolverine (qui mémorise les identifiants des messages déjà traités), ou une logique naturellement idempotente (« créer le board s'il n'existe pas »).

+

Retries et erreurs

+
    +
  • Erreur transitoire (base momentanément indisponible) : on réessaie avec un délai croissant (1 s, 5 s, 30 s).
  • +
  • Erreur permanente (données invalides) : on ne réessaie pas, le message part directement en dead-letter.
  • +
+

Saga (processus sur plusieurs services)

+

Exemple : archiver un projet revient à archiver ses tâches, puis à notifier ses membres, puis à marquer le projet « archivé ». Il n'y a pas de transaction distribuée : chaque étape est locale, et en cas d'échec, on déclenche des actions de compensation. Wolverine gère l'état de la saga en base.

+
Résumé : outbox côté émetteur, idempotence côté consommateur, dead-letter pour ce qui ne passe pas. C'est le trio attendu en entretien.
+
+ +
+

7. Données : chaque service possède les siennes

+
    +
  • Une base par service (projectsdb, tasksdb) sur le même serveur Postgres en local. Aucune requête SQL ne traverse deux bases.
  • +
  • Si Tasks a besoin du nom d'un projet, il en garde une copie locale (une projection), mise à jour par les événements ProjectCreated et ProjectRenamed. Il n'appelle pas Projects à chaque affichage.
  • +
  • Cette copie peut avoir quelques millisecondes de retard : c'est la cohérence éventuelle, et l'interface doit l'accepter.
  • +
+
+ +
+

8. Observabilité distribuée

+
    +
  • OpenTelemetry propage un trace-id dans les en-têtes HTTP et dans les messages RabbitMQ (Wolverine le fait nativement).
  • +
  • Dans le dashboard Aspire, une seule trace montre : Angular → Gateway → Projects → Postgres → RabbitMQ → Tasks → Postgres.
  • +
  • Métriques à suivre : longueur des files, messages en dead-letter, durée des handlers.
  • +
  • Health checks : chaque service expose /health, et RabbitMQ et Postgres y sont vérifiés.
  • +
+
+ +
+

9. Tester des microservices

+
+ + + + + + + +
NiveauOutilCe qu'on vérifie
UnitairexUnit v3 + ShouldlyLe domaine et les handlers, sans broker
Intégration serviceWebApplicationFactory + Testcontainers (Postgres, RabbitMQ)Un endpoint écrit en base et publie l'événement attendu
MessagerieWolverine tracking (InvokeMessageAndWaitAsync, TrackActivity)Un message entrant produit les bons effets et les bons messages sortants
ContratTests de sérialisation (snapshot JSON)Un événement publié garde la même forme : pas de changement cassant
ArchitectureNetArchTestAucun service ne référence le Domain ou l'Infrastructure d'un autre, seulement ses Contracts
E2EPlaywright via la GatewayUn parcours complet
+
+ +
+

10. Structure du code

+
src/
+├─ AppHost/                      Aspire : Postgres, RabbitMQ, services, gateway, front
+├─ BuildingBlocks/
+│  ├─ TaskFlow.ServiceDefaults/  OpenTelemetry, health, résilience
+│  └─ TaskFlow.SharedKernel/     Entity, AggregateRoot, Result, Error
+├─ Gateway/TaskFlow.Gateway/     YARP
+└─ Services/
+   ├─ Projects/
+   │  ├─ TaskFlow.Projects.Api/             hôte HTTP + Wolverine
+   │  ├─ TaskFlow.Projects.Domain/
+   │  ├─ TaskFlow.Projects.Application/
+   │  ├─ TaskFlow.Projects.Infrastructure/
+   │  └─ TaskFlow.Projects.Contracts/       événements d'intégration publics
+   ├─ Tasks/          (même découpage)
+   └─ Notifications/  (worker)
+
Règle : un service ne peut référencer que le projet *.Contracts d'un autre service. Jamais son Domain, son Application ou son Infrastructure.
+
+ +
+

11. Roadmap microservices

+
+ + + + + + + + +
ÉtapeContenuCritère de réussite
1Restructuration en services, RabbitMQ et Gateway YARP dans AspireLe front passe par la Gateway, et RabbitMQ est visible dans le dashboard
2Service Tasks + premier événement ProjectCreated via WolverineCréer un projet crée automatiquement son board dans Tasks
3Outbox et inbox durables + tests TestcontainersOn coupe RabbitMQ, on crée un projet, on relance RabbitMQ : l'événement arrive
4Service Notifications + SignalRUn déplacement de tâche apparaît en direct chez les autres membres
5Saga d'archivage + dead-letter + documentation AsyncAPIUn message invalide finit en DLQ, visible et rejouable
6Keycloak + auth à la Gateway, propagation de l'utilisateurLes services reçoivent l'identité sans la revalider eux-mêmes
7CI par service + images conteneur + déploiementUn changement dans Tasks ne rebuild que Tasks
+
+ +
+

12. Pièges classiques (et questions d'entretien)

+
    +
  • Partager une base entre services, ou lire directement la table d'un autre service.
  • +
  • Publier un événement sans outbox, ce qui le perd au premier crash.
  • +
  • Des handlers non idempotents, qui créent des doublons à la redistribution.
  • +
  • Des chaînes d'appels HTTP synchrones : A appelle B qui appelle C, et la latence et les pannes s'additionnent.
  • +
  • Mettre des objets du domaine dans les événements d'intégration, ce qui couple les services.
  • +
  • Casser un contrat d'événement (renommer un champ) sans versionner.
  • +
  • Oublier le trace-id, et ne plus rien pouvoir déboguer.
  • +
  • Découper trop fin : un « microservice » par table. Il faut découper par capacité métier.
  • +
  • Question classique : « Comment garantir qu'un événement est publié exactement une fois ? » Réponse : on ne peut pas. On combine l'outbox (au moins une fois) et l'idempotence (effet unique), ce qui donne un effet « exactly-once » côté métier.
  • +
+
+
+ + diff --git a/src/AppHost/TaskFlow.AppHost/AppHost.cs b/src/AppHost/TaskFlow.AppHost/AppHost.cs new file mode 100644 index 0000000..30bad8f --- /dev/null +++ b/src/AppHost/TaskFlow.AppHost/AppHost.cs @@ -0,0 +1,42 @@ +var builder = DistributedApplication.CreateBuilder(args); + +// ── Infrastructure partagée (conteneurs Podman, données conservées entre deux lancements) ── + +var postgres = builder.AddPostgres("postgres") + .WithDataVolume("taskflow-postgres-data") + .WithLifetime(ContainerLifetime.Persistent); + +// Une base par service : aucun service ne lit la base d'un autre. +var projectsDb = postgres.AddDatabase("projectsdb"); + +// Broker de messages. Le plugin "management" ajoute l'interface web (files, débits, messages en attente). +var rabbitmq = builder.AddRabbitMQ("rabbitmq") + .WithManagementPlugin() + .WithDataVolume("taskflow-rabbitmq-data") + .WithLifetime(ContainerLifetime.Persistent); + +// ── Microservices ── + +var projectsApi = builder.AddProject("projects-api") + .WithReference(projectsDb) + .WithReference(rabbitmq) + .WaitFor(projectsDb) + .WaitFor(rabbitmq) + .WithHttpHealthCheck("/health"); + +// ── Gateway : seul point d'entrée du front ── + +var gateway = builder.AddProject("gateway") + .WithReference(projectsApi) + .WaitFor(projectsApi) + .WithHttpHealthCheck("/health"); + +// ── Front Angular : ne connaît que la Gateway ── + +builder.AddJavaScriptApp("web", "../../../web/taskflow-ui", "start") + .WithReference(gateway) + .WaitFor(gateway) + .WithHttpEndpoint(env: "PORT") + .WithExternalHttpEndpoints(); + +builder.Build().Run(); diff --git a/src/TaskFlow.AppHost/Properties/launchSettings.json b/src/AppHost/TaskFlow.AppHost/Properties/launchSettings.json similarity index 100% rename from src/TaskFlow.AppHost/Properties/launchSettings.json rename to src/AppHost/TaskFlow.AppHost/Properties/launchSettings.json diff --git a/src/TaskFlow.AppHost/TaskFlow.AppHost.csproj b/src/AppHost/TaskFlow.AppHost/TaskFlow.AppHost.csproj similarity index 62% rename from src/TaskFlow.AppHost/TaskFlow.AppHost.csproj rename to src/AppHost/TaskFlow.AppHost/TaskFlow.AppHost.csproj index 5708316..9151bcf 100644 --- a/src/TaskFlow.AppHost/TaskFlow.AppHost.csproj +++ b/src/AppHost/TaskFlow.AppHost/TaskFlow.AppHost.csproj @@ -8,11 +8,13 @@ + - + +
diff --git a/src/TaskFlow.Api/appsettings.Development.json b/src/AppHost/TaskFlow.AppHost/appsettings.Development.json similarity index 100% rename from src/TaskFlow.Api/appsettings.Development.json rename to src/AppHost/TaskFlow.AppHost/appsettings.Development.json diff --git a/src/TaskFlow.AppHost/appsettings.json b/src/AppHost/TaskFlow.AppHost/appsettings.json similarity index 100% rename from src/TaskFlow.AppHost/appsettings.json rename to src/AppHost/TaskFlow.AppHost/appsettings.json diff --git a/src/TaskFlow.AppHost/aspire.config.json b/src/AppHost/TaskFlow.AppHost/aspire.config.json similarity index 100% rename from src/TaskFlow.AppHost/aspire.config.json rename to src/AppHost/TaskFlow.AppHost/aspire.config.json diff --git a/src/TaskFlow.ServiceDefaults/Extensions.cs b/src/BuildingBlocks/TaskFlow.ServiceDefaults/Extensions.cs similarity index 100% rename from src/TaskFlow.ServiceDefaults/Extensions.cs rename to src/BuildingBlocks/TaskFlow.ServiceDefaults/Extensions.cs diff --git a/src/TaskFlow.ServiceDefaults/TaskFlow.ServiceDefaults.csproj b/src/BuildingBlocks/TaskFlow.ServiceDefaults/TaskFlow.ServiceDefaults.csproj similarity index 100% rename from src/TaskFlow.ServiceDefaults/TaskFlow.ServiceDefaults.csproj rename to src/BuildingBlocks/TaskFlow.ServiceDefaults/TaskFlow.ServiceDefaults.csproj diff --git a/src/TaskFlow.SharedKernel/AggregateRoot.cs b/src/BuildingBlocks/TaskFlow.SharedKernel/AggregateRoot.cs similarity index 100% rename from src/TaskFlow.SharedKernel/AggregateRoot.cs rename to src/BuildingBlocks/TaskFlow.SharedKernel/AggregateRoot.cs diff --git a/src/TaskFlow.SharedKernel/Entity.cs b/src/BuildingBlocks/TaskFlow.SharedKernel/Entity.cs similarity index 100% rename from src/TaskFlow.SharedKernel/Entity.cs rename to src/BuildingBlocks/TaskFlow.SharedKernel/Entity.cs diff --git a/src/TaskFlow.SharedKernel/Error.cs b/src/BuildingBlocks/TaskFlow.SharedKernel/Error.cs similarity index 100% rename from src/TaskFlow.SharedKernel/Error.cs rename to src/BuildingBlocks/TaskFlow.SharedKernel/Error.cs diff --git a/src/TaskFlow.SharedKernel/IDomainEvent.cs b/src/BuildingBlocks/TaskFlow.SharedKernel/IDomainEvent.cs similarity index 100% rename from src/TaskFlow.SharedKernel/IDomainEvent.cs rename to src/BuildingBlocks/TaskFlow.SharedKernel/IDomainEvent.cs diff --git a/src/TaskFlow.SharedKernel/Result.cs b/src/BuildingBlocks/TaskFlow.SharedKernel/Result.cs similarity index 100% rename from src/TaskFlow.SharedKernel/Result.cs rename to src/BuildingBlocks/TaskFlow.SharedKernel/Result.cs diff --git a/src/TaskFlow.SharedKernel/TaskFlow.SharedKernel.csproj b/src/BuildingBlocks/TaskFlow.SharedKernel/TaskFlow.SharedKernel.csproj similarity index 100% rename from src/TaskFlow.SharedKernel/TaskFlow.SharedKernel.csproj rename to src/BuildingBlocks/TaskFlow.SharedKernel/TaskFlow.SharedKernel.csproj diff --git a/src/Gateway/TaskFlow.Gateway/Program.cs b/src/Gateway/TaskFlow.Gateway/Program.cs new file mode 100644 index 0000000..ddc7bb3 --- /dev/null +++ b/src/Gateway/TaskFlow.Gateway/Program.cs @@ -0,0 +1,30 @@ +using System.Reflection; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +// YARP : les routes et les clusters sont décrits dans appsettings.json (section "ReverseProxy"). +// Les adresses du type "https+http://projects-api" sont résolues par le service discovery d'Aspire. +builder.Services.AddReverseProxy() + .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy")) + .AddServiceDiscoveryDestinationResolver(); + +var app = builder.Build(); + +app.UseHttpsRedirection(); + +app.MapDefaultEndpoints(); + +// Endpoint propre à la Gateway : le front l'utilise pour afficher "API connectée". +app.MapGet("/api/info", (IHostEnvironment env) => TypedResults.Ok(new +{ + Name = "TaskFlow Gateway", + Version = Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "0.0.0", + Environment = env.EnvironmentName, + ServerTime = DateTimeOffset.UtcNow, +})); + +app.MapReverseProxy(); + +app.Run(); diff --git a/src/Gateway/TaskFlow.Gateway/Properties/launchSettings.json b/src/Gateway/TaskFlow.Gateway/Properties/launchSettings.json new file mode 100644 index 0000000..41264f7 --- /dev/null +++ b/src/Gateway/TaskFlow.Gateway/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5161", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7288;http://localhost:5161", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/src/Gateway/TaskFlow.Gateway/TaskFlow.Gateway.csproj b/src/Gateway/TaskFlow.Gateway/TaskFlow.Gateway.csproj new file mode 100644 index 0000000..9e11c1b --- /dev/null +++ b/src/Gateway/TaskFlow.Gateway/TaskFlow.Gateway.csproj @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/src/TaskFlow.AppHost/appsettings.Development.json b/src/Gateway/TaskFlow.Gateway/appsettings.Development.json similarity index 100% rename from src/TaskFlow.AppHost/appsettings.Development.json rename to src/Gateway/TaskFlow.Gateway/appsettings.Development.json diff --git a/src/Gateway/TaskFlow.Gateway/appsettings.json b/src/Gateway/TaskFlow.Gateway/appsettings.json new file mode 100644 index 0000000..d640cc5 --- /dev/null +++ b/src/Gateway/TaskFlow.Gateway/appsettings.json @@ -0,0 +1,25 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Yarp": "Information" + } + }, + "AllowedHosts": "*", + "ReverseProxy": { + "Routes": { + "projects": { + "ClusterId": "projects", + "Match": { "Path": "/api/projects/{**catch-all}" } + } + }, + "Clusters": { + "projects": { + "Destinations": { + "projects-api": { "Address": "https+http://projects-api" } + } + } + } + } +} diff --git a/src/TaskFlow.Api/Infrastructure/GlobalExceptionHandler.cs b/src/Services/Projects/TaskFlow.Projects.Api/Infrastructure/GlobalExceptionHandler.cs similarity index 96% rename from src/TaskFlow.Api/Infrastructure/GlobalExceptionHandler.cs rename to src/Services/Projects/TaskFlow.Projects.Api/Infrastructure/GlobalExceptionHandler.cs index a72cde0..2d2d17f 100644 --- a/src/TaskFlow.Api/Infrastructure/GlobalExceptionHandler.cs +++ b/src/Services/Projects/TaskFlow.Projects.Api/Infrastructure/GlobalExceptionHandler.cs @@ -1,6 +1,6 @@ using Microsoft.AspNetCore.Diagnostics; -namespace TaskFlow.Api.Infrastructure; +namespace TaskFlow.Projects.Api.Infrastructure; /// /// Filet de sécurité pour les exceptions non prévues : log complet côté serveur, diff --git a/src/Services/Projects/TaskFlow.Projects.Api/Infrastructure/InfoEndpoint.cs b/src/Services/Projects/TaskFlow.Projects.Api/Infrastructure/InfoEndpoint.cs new file mode 100644 index 0000000..634ae1e --- /dev/null +++ b/src/Services/Projects/TaskFlow.Projects.Api/Infrastructure/InfoEndpoint.cs @@ -0,0 +1,22 @@ +using System.Reflection; + +namespace TaskFlow.Projects.Api.Infrastructure; + +/// Endpoint technique : identité et version du service Projects (exposé via la Gateway). +public static class InfoEndpoint +{ + public sealed record ServiceInfo(string Name, string Version, string Environment, DateTimeOffset ServerTime); + + public static IEndpointRouteBuilder MapInfoEndpoint(this IEndpointRouteBuilder app) + { + app.MapGet("/api/projects/info", (IHostEnvironment env) => TypedResults.Ok(new ServiceInfo( + Name: "TaskFlow Projects", + Version: Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "0.0.0", + Environment: env.EnvironmentName, + ServerTime: DateTimeOffset.UtcNow))) + .WithName("GetProjectsServiceInfo") + .WithTags("Info"); + + return app; + } +} diff --git a/src/TaskFlow.Api/Infrastructure/ResultExtensions.cs b/src/Services/Projects/TaskFlow.Projects.Api/Infrastructure/ResultExtensions.cs similarity index 96% rename from src/TaskFlow.Api/Infrastructure/ResultExtensions.cs rename to src/Services/Projects/TaskFlow.Projects.Api/Infrastructure/ResultExtensions.cs index d7e9c0d..b672245 100644 --- a/src/TaskFlow.Api/Infrastructure/ResultExtensions.cs +++ b/src/Services/Projects/TaskFlow.Projects.Api/Infrastructure/ResultExtensions.cs @@ -1,6 +1,6 @@ using TaskFlow.SharedKernel; -namespace TaskFlow.Api.Infrastructure; +namespace TaskFlow.Projects.Api.Infrastructure; /// /// Traduit un en échec vers une réponse HTTP ProblemDetails. diff --git a/src/TaskFlow.Api/Program.cs b/src/Services/Projects/TaskFlow.Projects.Api/Program.cs similarity index 75% rename from src/TaskFlow.Api/Program.cs rename to src/Services/Projects/TaskFlow.Projects.Api/Program.cs index a7e7d88..0fdfcd2 100644 --- a/src/TaskFlow.Api/Program.cs +++ b/src/Services/Projects/TaskFlow.Projects.Api/Program.cs @@ -1,5 +1,5 @@ using Scalar.AspNetCore; -using TaskFlow.Api.Infrastructure; +using TaskFlow.Projects.Api.Infrastructure; using TaskFlow.Projects.Infrastructure; var builder = WebApplication.CreateBuilder(args); @@ -7,13 +7,16 @@ // 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.) +builder.AddRabbitMQClient("rabbitmq"); + // Erreurs au format standard ProblemDetails (RFC 9457). builder.Services.AddProblemDetails(); builder.Services.AddExceptionHandler(); builder.Services.AddOpenApi(); -// Modules métier (un appel par module). builder.AddProjectsModule(); var app = builder.Build(); diff --git a/src/TaskFlow.Api/Properties/launchSettings.json b/src/Services/Projects/TaskFlow.Projects.Api/Properties/launchSettings.json similarity index 100% rename from src/TaskFlow.Api/Properties/launchSettings.json rename to src/Services/Projects/TaskFlow.Projects.Api/Properties/launchSettings.json diff --git a/src/TaskFlow.Api/TaskFlow.Api.csproj b/src/Services/Projects/TaskFlow.Projects.Api/TaskFlow.Projects.Api.csproj similarity index 55% rename from src/TaskFlow.Api/TaskFlow.Api.csproj rename to src/Services/Projects/TaskFlow.Projects.Api/TaskFlow.Projects.Api.csproj index b929e2f..7c4dddc 100644 --- a/src/TaskFlow.Api/TaskFlow.Api.csproj +++ b/src/Services/Projects/TaskFlow.Projects.Api/TaskFlow.Projects.Api.csproj @@ -1,6 +1,7 @@ + all @@ -10,13 +11,14 @@ - - + + + - + diff --git a/src/TaskFlow.Api/TaskFlow.Api.http b/src/Services/Projects/TaskFlow.Projects.Api/TaskFlow.Projects.Api.http similarity index 100% rename from src/TaskFlow.Api/TaskFlow.Api.http rename to src/Services/Projects/TaskFlow.Projects.Api/TaskFlow.Projects.Api.http diff --git a/src/Services/Projects/TaskFlow.Projects.Api/appsettings.Development.json b/src/Services/Projects/TaskFlow.Projects.Api/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/src/Services/Projects/TaskFlow.Projects.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/src/TaskFlow.Api/appsettings.json b/src/Services/Projects/TaskFlow.Projects.Api/appsettings.json similarity index 100% rename from src/TaskFlow.Api/appsettings.json rename to src/Services/Projects/TaskFlow.Projects.Api/appsettings.json diff --git a/src/Modules/Projects/TaskFlow.Projects.Application/DependencyInjection.cs b/src/Services/Projects/TaskFlow.Projects.Application/DependencyInjection.cs similarity index 100% rename from src/Modules/Projects/TaskFlow.Projects.Application/DependencyInjection.cs rename to src/Services/Projects/TaskFlow.Projects.Application/DependencyInjection.cs diff --git a/src/Modules/Projects/TaskFlow.Projects.Application/ProjectsEndpoints.cs b/src/Services/Projects/TaskFlow.Projects.Application/ProjectsEndpoints.cs similarity index 100% rename from src/Modules/Projects/TaskFlow.Projects.Application/ProjectsEndpoints.cs rename to src/Services/Projects/TaskFlow.Projects.Application/ProjectsEndpoints.cs diff --git a/src/Modules/Projects/TaskFlow.Projects.Application/TaskFlow.Projects.Application.csproj b/src/Services/Projects/TaskFlow.Projects.Application/TaskFlow.Projects.Application.csproj similarity index 100% rename from src/Modules/Projects/TaskFlow.Projects.Application/TaskFlow.Projects.Application.csproj rename to src/Services/Projects/TaskFlow.Projects.Application/TaskFlow.Projects.Application.csproj diff --git a/src/Services/Projects/TaskFlow.Projects.Contracts/TaskFlow.Projects.Contracts.csproj b/src/Services/Projects/TaskFlow.Projects.Contracts/TaskFlow.Projects.Contracts.csproj new file mode 100644 index 0000000..d284322 --- /dev/null +++ b/src/Services/Projects/TaskFlow.Projects.Contracts/TaskFlow.Projects.Contracts.csproj @@ -0,0 +1,10 @@ + + + + + diff --git a/src/Modules/Projects/TaskFlow.Projects.Domain/TaskFlow.Projects.Domain.csproj b/src/Services/Projects/TaskFlow.Projects.Domain/TaskFlow.Projects.Domain.csproj similarity index 58% rename from src/Modules/Projects/TaskFlow.Projects.Domain/TaskFlow.Projects.Domain.csproj rename to src/Services/Projects/TaskFlow.Projects.Domain/TaskFlow.Projects.Domain.csproj index 790aaf6..dfb30cf 100644 --- a/src/Modules/Projects/TaskFlow.Projects.Domain/TaskFlow.Projects.Domain.csproj +++ b/src/Services/Projects/TaskFlow.Projects.Domain/TaskFlow.Projects.Domain.csproj @@ -2,7 +2,7 @@ - + diff --git a/src/Modules/Projects/TaskFlow.Projects.Infrastructure/Persistence/ProjectsDbContext.cs b/src/Services/Projects/TaskFlow.Projects.Infrastructure/Persistence/ProjectsDbContext.cs similarity index 100% rename from src/Modules/Projects/TaskFlow.Projects.Infrastructure/Persistence/ProjectsDbContext.cs rename to src/Services/Projects/TaskFlow.Projects.Infrastructure/Persistence/ProjectsDbContext.cs diff --git a/src/Modules/Projects/TaskFlow.Projects.Infrastructure/ProjectsModule.cs b/src/Services/Projects/TaskFlow.Projects.Infrastructure/ProjectsModule.cs similarity index 83% rename from src/Modules/Projects/TaskFlow.Projects.Infrastructure/ProjectsModule.cs rename to src/Services/Projects/TaskFlow.Projects.Infrastructure/ProjectsModule.cs index ab685f3..ac027e7 100644 --- a/src/Modules/Projects/TaskFlow.Projects.Infrastructure/ProjectsModule.cs +++ b/src/Services/Projects/TaskFlow.Projects.Infrastructure/ProjectsModule.cs @@ -8,8 +8,8 @@ namespace TaskFlow.Projects.Infrastructure; /// Composition du module : l'API n'appelle que ces deux méthodes. public static class ProjectsModule { - /// Nom de la base déclarée dans l'AppHost Aspire (AddDatabase("taskflowdb")). - public const string DatabaseName = "taskflowdb"; + /// Base propre au service Projects, déclarée dans l'AppHost (AddDatabase("projectsdb")). + public const string DatabaseName = "projectsdb"; public static IHostApplicationBuilder AddProjectsModule(this IHostApplicationBuilder builder) { diff --git a/src/Modules/Projects/TaskFlow.Projects.Infrastructure/TaskFlow.Projects.Infrastructure.csproj b/src/Services/Projects/TaskFlow.Projects.Infrastructure/TaskFlow.Projects.Infrastructure.csproj similarity index 100% rename from src/Modules/Projects/TaskFlow.Projects.Infrastructure/TaskFlow.Projects.Infrastructure.csproj rename to src/Services/Projects/TaskFlow.Projects.Infrastructure/TaskFlow.Projects.Infrastructure.csproj diff --git a/src/TaskFlow.Api/Infrastructure/InfoEndpoint.cs b/src/TaskFlow.Api/Infrastructure/InfoEndpoint.cs deleted file mode 100644 index a0307e0..0000000 --- a/src/TaskFlow.Api/Infrastructure/InfoEndpoint.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Reflection; - -namespace TaskFlow.Api.Infrastructure; - -/// Endpoint technique utilisé par le front pour vérifier que l'API répond. -public static class InfoEndpoint -{ - public sealed record ApiInfo(string Name, string Version, string Environment, DateTimeOffset ServerTime); - - public static IEndpointRouteBuilder MapInfoEndpoint(this IEndpointRouteBuilder app) - { - app.MapGet("/api/info", (IHostEnvironment env) => TypedResults.Ok(new ApiInfo( - Name: "TaskFlow API", - Version: Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "0.0.0", - Environment: env.EnvironmentName, - ServerTime: DateTimeOffset.UtcNow))) - .WithName("GetApiInfo") - .WithTags("Info"); - - return app; - } -} diff --git a/src/TaskFlow.AppHost/AppHost.cs b/src/TaskFlow.AppHost/AppHost.cs deleted file mode 100644 index 80d15a4..0000000 --- a/src/TaskFlow.AppHost/AppHost.cs +++ /dev/null @@ -1,23 +0,0 @@ -var builder = DistributedApplication.CreateBuilder(args); - -// Base Postgres dans un conteneur (Podman). Le volume garde les données entre deux lancements. -var postgres = builder.AddPostgres("postgres") - .WithDataVolume("taskflow-postgres-data") - .WithLifetime(ContainerLifetime.Persistent); - -var database = postgres.AddDatabase("taskflowdb"); - -// API .NET : reçoit la chaîne de connexion de "taskflowdb" automatiquement. -var api = builder.AddProject("api") - .WithReference(database) - .WaitFor(database) - .WithHttpHealthCheck("/health"); - -// Front Angular : lancé avec "npm run start", l'URL de l'API lui est injectée en variable d'environnement. -builder.AddJavaScriptApp("web", "../../web/taskflow-ui", "start") - .WithReference(api) - .WaitFor(api) - .WithHttpEndpoint(env: "PORT") - .WithExternalHttpEndpoints(); - -builder.Build().Run(); diff --git a/tests/TaskFlow.ArchitectureTests/LayerDependencyTests.cs b/tests/TaskFlow.ArchitectureTests/LayerDependencyTests.cs index bf69282..1b9a3f3 100644 --- a/tests/TaskFlow.ArchitectureTests/LayerDependencyTests.cs +++ b/tests/TaskFlow.ArchitectureTests/LayerDependencyTests.cs @@ -5,7 +5,7 @@ namespace TaskFlow.ArchitectureTests; /// -/// Vérifie la règle de dépendance de la Clean Architecture : +/// Vérifie la règle de dépendance de la Clean Architecture à l'intérieur du service Projects : /// Domain ← Application ← Infrastructure ← Api. Un test rouge = une couche qui en référence une autre à tort. /// public class LayerDependencyTests @@ -34,7 +34,7 @@ public void Domain_ne_depend_ni_d_EF_Core_ni_d_ASP_NET_ni_des_couches_superieure "Microsoft.AspNetCore", "TaskFlow.Projects.Application", "TaskFlow.Projects.Infrastructure", - "TaskFlow.Api") + "TaskFlow.Projects.Api") .GetResult(); result.IsSuccessful.ShouldBeTrue(Describe(result)); @@ -47,7 +47,7 @@ public void Application_ne_depend_pas_de_l_Infrastructure_ni_d_EF_Core() .ShouldNot().HaveDependencyOnAny( "Microsoft.EntityFrameworkCore", "TaskFlow.Projects.Infrastructure", - "TaskFlow.Api") + "TaskFlow.Projects.Api") .GetResult(); result.IsSuccessful.ShouldBeTrue(Describe(result)); @@ -57,7 +57,7 @@ public void Application_ne_depend_pas_de_l_Infrastructure_ni_d_EF_Core() public void Infrastructure_ne_depend_pas_de_l_Api() { var result = Types.InAssembly(ProjectsInfrastructure) - .ShouldNot().HaveDependencyOn("TaskFlow.Api") + .ShouldNot().HaveDependencyOn("TaskFlow.Projects.Api") .GetResult(); result.IsSuccessful.ShouldBeTrue(Describe(result)); @@ -74,6 +74,6 @@ public void Les_entites_du_domaine_sont_sealed() result.IsSuccessful.ShouldBeTrue(Describe(result)); } - private static string Describe(NetArchTest.Rules.TestResult result) => + internal static string Describe(NetArchTest.Rules.TestResult result) => "Types en infraction : " + string.Join(", ", result.FailingTypeNames ?? []); } diff --git a/tests/TaskFlow.ArchitectureTests/MicroserviceBoundaryTests.cs b/tests/TaskFlow.ArchitectureTests/MicroserviceBoundaryTests.cs new file mode 100644 index 0000000..df36710 --- /dev/null +++ b/tests/TaskFlow.ArchitectureTests/MicroserviceBoundaryTests.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using Shouldly; + +namespace TaskFlow.ArchitectureTests; + +/// +/// Frontières entre microservices : un service ne connaît des autres que leur projet *.Contracts. +/// On vérifie les références d'assemblies (ce que le compilateur a réellement lié). +/// +public class MicroserviceBoundaryTests +{ + private static readonly Assembly Gateway = Assembly.Load("TaskFlow.Gateway"); + private static readonly Assembly ProjectsContracts = Assembly.Load("TaskFlow.Projects.Contracts"); + + private static IEnumerable TaskFlowReferences(Assembly assembly) => + assembly.GetReferencedAssemblies() + .Select(a => a.Name!) + .Where(name => name.StartsWith("TaskFlow.", StringComparison.Ordinal)); + + [Fact] + public void La_Gateway_ne_reference_aucun_microservice() + { + // La Gateway route par HTTP : elle ne doit dépendre que des briques techniques communes. + var references = TaskFlowReferences(Gateway).ToList(); + + references.ShouldAllBe(name => name == "TaskFlow.ServiceDefaults", + $"Références interdites : {string.Join(", ", references)}"); + } + + [Fact] + public void Les_Contracts_ne_dependent_d_aucun_autre_projet_TaskFlow() + { + // Un contrat public doit pouvoir être référencé par n'importe quel service sans rien entraîner. + TaskFlowReferences(ProjectsContracts).ShouldBeEmpty(); + } +} diff --git a/tests/TaskFlow.ArchitectureTests/TaskFlow.ArchitectureTests.csproj b/tests/TaskFlow.ArchitectureTests/TaskFlow.ArchitectureTests.csproj index dcfda33..470f029 100644 --- a/tests/TaskFlow.ArchitectureTests/TaskFlow.ArchitectureTests.csproj +++ b/tests/TaskFlow.ArchitectureTests/TaskFlow.ArchitectureTests.csproj @@ -10,7 +10,8 @@ - + + diff --git a/tests/TaskFlow.Projects.UnitTests/TaskFlow.Projects.UnitTests.csproj b/tests/TaskFlow.Projects.UnitTests/TaskFlow.Projects.UnitTests.csproj index 7f905d3..966d1ce 100644 --- a/tests/TaskFlow.Projects.UnitTests/TaskFlow.Projects.UnitTests.csproj +++ b/tests/TaskFlow.Projects.UnitTests/TaskFlow.Projects.UnitTests.csproj @@ -9,7 +9,7 @@ - + diff --git a/web/taskflow-ui/proxy.conf.mjs b/web/taskflow-ui/proxy.conf.mjs index 6e24ced..c47b4cc 100644 --- a/web/taskflow-ui/proxy.conf.mjs +++ b/web/taskflow-ui/proxy.conf.mjs @@ -1,16 +1,16 @@ -// Redirige /api/* du serveur de dev Angular vers l'API .NET. -// Quand l'app est lancée par l'AppHost Aspire, l'adresse de l'API est injectée en variable d'environnement -// (WithReference(api)). Hors Aspire, on retombe sur l'adresse locale par défaut de l'API. -const apiUrl = - process.env['API_HTTPS'] ?? - process.env['services__api__https__0'] ?? - process.env['API_HTTP'] ?? - process.env['services__api__http__0'] ?? - 'https://localhost:7209'; +// Redirige /api/* du serveur de dev Angular vers la Gateway (le front ne parle jamais directement aux microservices). +// Lancé par l'AppHost Aspire, l'adresse de la Gateway est injectée en variable d'environnement +// (WithReference(gateway)). Hors Aspire, on retombe sur l'adresse locale par défaut de la Gateway. +const gatewayUrl = + process.env['GATEWAY_HTTPS'] ?? + process.env['services__gateway__https__0'] ?? + process.env['GATEWAY_HTTP'] ?? + process.env['services__gateway__http__0'] ?? + 'https://localhost:7288'; export default { '/api': { - target: apiUrl, + target: gatewayUrl, secure: false, // certificat de dev ASP.NET auto-signé changeOrigin: true, logLevel: 'info',