Skip to content

feat(orders): saga de orquestração liga o checkout ponta a ponta (fase 4b) - #6

Merged
thomasmoreira merged 1 commit into
mainfrom
feat/orders-saga
Jun 8, 2026
Merged

thomasmoreira merged 1 commit into
mainfrom
feat/orders-saga

Conversation

@thomasmoreira

@thomasmoreira thomasmoreira commented Jun 8, 2026 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features
    • Orders now progress through a coordinated workflow handling stock reservation, payment processing, and confirmation.
    • Automatic stock release when payment fails, ensuring inventory is properly restored during checkout.

…e 4b)

O Orders deixa de só produzir e passa a CONSUMIR as respostas dos participantes,
dirigindo uma saga persistida até o estado final do pedido (spec §5.3, ADR-003).

- Contracts: ReleaseStockRequested (comando de compensação emitido pela saga)
- Saga: OrderSagaInstance (estado persistido por pedido) + OrderSagaCoordinator
  (carrega instância, avança a máquina de estados OrderSaga, aplica efeitos: confirma,
  cancela ou pede compensação) — não salva; roda na transação do inbox
- PlaceOrder: inicia a saga (Started) ao criar o pedido
- Infrastructure: tabela saga_state (schema orders) + migration AddSagaState
- Consumers: 5 consumidores finos (StockReserved/StockReservationFailed/PaymentCharged/
  PaymentFailed/StockReleased) traduzem evento -> trigger da saga
- Host: wire do consumer (AddRabbitMqConsumer + os 5 consumidores + coordinator)

Fluxo: OrderPlaced -> (Inventory reserva) StockReserved -> (Payments cobra) PaymentCharged
-> saga Completed -> Order Confirmed. Falhas: StockReservationFailed -> Cancelled;
PaymentFailed -> Compensating + ReleaseStockRequested -> (StockReleased) -> Cancelled.

Testes: happy path confirma; falha de estoque cancela; falha de pagamento compensa e
cancela. Build limpo (0/0); unit 4/4; integration 11 passam + 2 skipped (F1/F4).
@coderabbitai

coderabbitai Bot commented Jun 8, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

This PR implements distributed order orchestration via a saga pattern. It introduces saga persistence, a coordinator that drives state transitions and emits corresponding outbox events, event consumers that respond to external service outcomes, and integration that ties saga initialization into order creation with comprehensive end-to-end tests.

Changes

Order Saga Orchestration

Layer / File(s) Summary
Saga Persistence Model and Database
src/Services/Orders/Saga/OrderSagaInstance.cs, src/Services/Orders/Infrastructure/OrderSagaInstanceConfiguration.cs, src/Services/Orders/Infrastructure/OrdersDbContext.cs, src/Services/Orders/Migrations/20260608171930_AddSagaState.cs, src/Services/Orders/Migrations/20260608171930_AddSagaState.Designer.cs, src/Services/Orders/Migrations/OrdersDbContextModelSnapshot.cs
OrderSagaInstance persists saga state (OrderId and State enum) in the orders.saga_state table. EF Core configuration maps the entity, context exposes a DbSet<OrderSagaInstance>, and migrations establish the table schema.
Saga Orchestration and Compensation Logic
src/Contracts/CheckoutEvents.cs, src/Services/Orders/Saga/OrderSagaCoordinator.cs
OrderSagaCoordinator handles saga state transitions by loading persisted saga instances, advancing them via OrderSagaTrigger, and applying state-dependent side effects: confirms orders and emits OrderConfirmed, cancels orders and emits OrderCancelled, or compensates by emitting ReleaseStockRequested. The new ReleaseStockRequested contract carries order and stock details for compensation.
Event Consumers and Order Integration
src/Services/Orders/Consumers/OrderSagaConsumers.cs, src/Services/Orders/Features/PlaceOrder.cs, src/Services/Orders/Program.cs
Five sealed consumers (StockReservedSagaConsumer, StockReservationFailedSagaConsumer, PaymentChargedSagaConsumer, PaymentFailedSagaConsumer, StockReleasedSagaConsumer) translate integration events into saga triggers. PlaceOrder initializes saga instances alongside order creation. Program.cs registers the coordinator, consumers, and RabbitMQ consumer for the "orders" queue.
Integration Tests
tests/Integration/OrderSagaOrchestrationTests.cs
End-to-end tests boot Postgres, migrate schema, and validate three scenarios: happy path (stock + payment success → confirmed), stock failure (→ cancelled), and payment failure (→ compensation via release event, then cancelled).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐰 A saga's dance through states so grand,
Stock and payment, hand in hand,
Compensating when things go wrong,
Outbox events, steady and strong!
Distributed yet consistent, we prance,
In orchestrated sync—the rabbit's chance!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.71% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title in Portuguese describes the implementation of an order saga orchestration that connects the checkout end-to-end (phase 4b), which directly aligns with the changeset that adds saga coordination, consumers, state persistence, and integration tests.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/orders-saga

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@thomasmoreira
thomasmoreira merged commit cbb9094 into main Jun 8, 2026
1 of 2 checks passed
@thomasmoreira
thomasmoreira deleted the feat/orders-saga branch June 8, 2026 17:24
thomasmoreira added a commit that referenced this pull request Jun 10, 2026
…e 4b) (#6)

O Orders deixa de só produzir e passa a CONSUMIR as respostas dos participantes,
dirigindo uma saga persistida até o estado final do pedido (spec §5.3, ADR-003).

- Contracts: ReleaseStockRequested (comando de compensação emitido pela saga)
- Saga: OrderSagaInstance (estado persistido por pedido) + OrderSagaCoordinator
  (carrega instância, avança a máquina de estados OrderSaga, aplica efeitos: confirma,
  cancela ou pede compensação) — não salva; roda na transação do inbox
- PlaceOrder: inicia a saga (Started) ao criar o pedido
- Infrastructure: tabela saga_state (schema orders) + migration AddSagaState
- Consumers: 5 consumidores finos (StockReserved/StockReservationFailed/PaymentCharged/
  PaymentFailed/StockReleased) traduzem evento -> trigger da saga
- Host: wire do consumer (AddRabbitMqConsumer + os 5 consumidores + coordinator)

Fluxo: OrderPlaced -> (Inventory reserva) StockReserved -> (Payments cobra) PaymentCharged
-> saga Completed -> Order Confirmed. Falhas: StockReservationFailed -> Cancelled;
PaymentFailed -> Compensating + ReleaseStockRequested -> (StockReleased) -> Cancelled.

Testes: happy path confirma; falha de estoque cancela; falha de pagamento compensa e
cancela. Build limpo (0/0); unit 4/4; integration 11 passam + 2 skipped (F1/F4).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant