# Event Orchestration Example

Demonstrates the Saga Pattern with compensation logic for managing distributed transactions in a microservices environment using Azure Durable Functions.

## 📋 Overview

This example shows how to:

- Implement the Saga Pattern for distributed transactions
- Handle compensation (rollback) logic when failures occur
- Use Azure Durable Functions for orchestration
- Integrate with Azure Service Bus and Cosmos DB

## 🏗️ Architecture

The system implements the **Saga Pattern** with compensation to handle order fulfillment as a distributed transaction:

```mermaid
flowchart LR
    subgraph Forward["Forward Flow"]
        direction LR
        O["Order Creation"] --> I["Inventory Reservation"]
        I --> P["Payment Processing"]
        P --> F["Order Fulfillment"]
    end

    subgraph Actions["Actions"]
        direction LR
        A1["Store Order"] --> A2["Reserve Items"]
        A2 --> A3["Process Payment"]
        A3 --> A4["Ship Items"]
    end

    subgraph Compensate["Compensation (on failure)"]
        direction LR
        C1["Compensate"] --> C2["Release Items"]
        C2 --> C3["Refund Payment"]
        C3 --> C4["Cancel Shipment"]
    end
```

## 🧩 Components

| Project                    | Description                                                |
| -------------------------- | ---------------------------------------------------------- |
| `PetStore.Api`             | REST API for order management and event triggering         |
| `PetStore.Orchestration`   | Durable Functions with saga orchestration and compensation |
| `PetStore.Data`            | Cosmos DB models and Entity Framework context              |
| `PetStore.AppHost`         | Aspire orchestration host                                  |
| `PetStore.Data.Seed`       | Database seeding utility                                   |
| `PetStore.ServiceBus.Seed` | Service Bus message seeding utility                        |

## 🔑 Key Features

### Forward Activities

| Activity                   | Description                |
| -------------------------- | -------------------------- |
| `ReserveInventoryActivity` | Reserves product inventory |
| `ProcessPaymentActivity`   | Processes customer payment |
| `FulfillOrderActivity`     | Ships order to customer    |

### Compensation Activities

| Activity                    | Description                            |
| --------------------------- | -------------------------------------- |
| `ReleaseInventoryActivity`  | Releases reserved inventory on failure |
| `RefundPaymentActivity`     | Refunds processed payment on failure   |
| `CancelFulfillmentActivity` | Cancels order shipment on failure      |

## 📊 Data Models

### Order Management

- **Order** - Complete order information with items and payment
- **OrderItem** - Individual items within an order
- **PaymentInfo** - Payment details and status

### Saga State

- **OrderSaga** - Tracks orchestration progress and compensation state
- **SagaStep** - Individual step status and compensation data
- **SagaCompensationInfo** - Compensation tracking information

## 📂 Project Structure

```
foundry/dotnet/event-orchestration/
├── PetStore.sln
├── PetStore.AppHost/                 # Aspire orchestration
├── PetStore.Api/                     # REST API
├── PetStore.Orchestration/           # Durable Functions
│   ├── Orchestrators/
│   └── Activities/
├── PetStore.Data/                    # EF Core + Cosmos DB
├── PetStore.Data.Seed/               # DB seeding
└── PetStore.ServiceBus.Seed/         # Message seeding
```

## 🚀 Getting Started

### Prerequisites

- .NET 10.0 SDK
- Docker Desktop (for Cosmos DB emulator)
- Azure Service Bus (or emulator)

### Running the Example

```bash
cd foundry/dotnet/event-orchestration
dotnet run --project PetStore.AppHost
```

Access the Aspire dashboard at the URL shown in console.

## 🔄 Event Flow

1. **Order Creation**: Customer creates order via API
2. **Event Publishing**: `OrderCreated` event published to Service Bus
3. **Orchestration Trigger**: Service Bus trigger starts durable orchestration
4. **Saga Execution**: Sequential execution of business activities
5. **Compensation**: If any step fails, compensation activities execute in reverse order

## 💡 Use Cases

- **E-commerce Orders**: Multi-step order fulfillment with rollback
- **Financial Transactions**: Payment processing with refund capabilities
- **Inventory Management**: Reservation and release patterns

## 🔗 Related Patterns

- [Saga Pattern](https://microservices.io/patterns/data/saga.html)
- [Compensating Transaction Pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/compensating-transaction)

## 🔗 Related Documentation

- [Aspire Reference](../reference/tools/aspire.md) - Aspire fundamentals and configuration
- [Events with Cosmos DB Example](events-with-cosmos.md) - Simpler event-driven patterns
- [Entity Framework Reference](../reference/tools/entity-framework.md) - EF Core with Cosmos DB

## 📍 Source Code

**Location:** [`foundry/dotnet/event-orchestration/`](https://dev.azure.com/SAIFCorporation/Platform/_git/forge?path=/foundry/dotnet/event-orchestration)
