Skip to content

Latest commit

 

History

History
247 lines (177 loc) · 13.5 KB

README.md

File metadata and controls

247 lines (177 loc) · 13.5 KB

Contoso Samples

The samples folder contains reference implementations of domain microservices built with CoreEx: Products (PostgreSQL) and Shopping (SQL Server) are complete; Customers (Azure Cosmos DB) demonstrates typed CRUD, reference data, a transactional outbox, and a change-feed Outbox Relay against a schemaless store. Customers has no Subscribe host. A fourth, Orders, is a work in progress that will eventually demonstrate asynchronous workflow processing.

Sample architecture interactions

Each of Products and Shopping is an independently deployable unit with an API host, an Outbox Relay host, and an Event Subscriber host, backed by an applicable data repository, and connected to other domains via synchronous HTTP and asynchronous messaging over Azure Service Bus. Customers has API and Relay hosts: its relay forwards events from both Cosmos containers to the shared topic. Shopping still consumes Customers only via synchronous HTTP (see flow ⑧), not event-driven replication.

Documentation — detailed guides for layers, patterns, tooling, and testing are in samples/docs.

Guide Description
Layers Business and host layer overview with dependency diagram
Patterns Catalog of architectural patterns implemented across the samples
Search: from keywords to vectors Beginner-friendly explanation and staged design for Products search, PostgreSQL/pgvector, hybrid ranking, indexing, and MCP; distinguishes implemented behavior from planned work
Tooling Code generation (*.CodeGen) and database management (*.Database)
Testing Unit, intra-domain, inter-domain, and E2E testing strategy
Aspire & E2E Local orchestration and cross-domain end-to-end validation

Architecture

The domains communicate via synchronous HTTP and asynchronous messaging over Azure Service Bus.

graph TB
    subgraph INFRA["Shared Infrastructure"]
        direction LR
        SQLSERVER[("SQL Server\n:1433")]
        REDIS[("Redis\n:6379")]
        ASB[["Azure Service Bus\nEmulator\n:5672"]]
        ASPIRE["Aspire Dashboard\n:18888"]
    end

    subgraph PRODUCTS["Contoso.Products Domain"]
        direction TB
        PAPI["Products API\n─────────────────\nGET/POST/PUT/PATCH/DELETE /products\nPOST /inventory/reserve\nPOST /inventory/adjust\nGET /products/{id}/on-hand\nGET /refdata"]
        PAPP["Products Application\n─────────────────\nProductService\nMovementService\nInventoryService"]
        PINFRA["Products Infrastructure\n─────────────────\nProductRepository\nMovementRepository\nInventoryRepository\nProductsOutboxPublisher"]
        PSUBSCRIBE["Products.Subscribe\n─────────────────\nReservationConfirmSubscriber\nReservationCancelSubscriber"]
        POUTBOX["Products.Relay\n─────────────────\nOutbox to Service Bus\nPartitioned relay"]
        PDB[("SQL Server\n[Products] schema\n─────────────\nProduct\nInventory\nMovement\nOutbox / OutboxLease\nRef data")]
    end

    subgraph CUSTOMERS["Contoso.Customers Domain"]
        direction TB
        CAPI["Customers API\n─────────────────\nGET/POST/PUT/PATCH/DELETE /customers\nGET /refdata"]
        CDB[("Cosmos DB\ncustomers / ref-data\nCo-located outbox events\n$outbox-leases")]
        COUTBOX["Customers.Relay\nChange feed to Service Bus"]
    end

    subgraph SHOPPING["Contoso.Shopping Domain"]
        direction TB
        SAPI["Shopping API\n─────────────────\nPOST /customers/{id}/baskets\nPOST /{id}/checkout\nPUT /{id}/apply-discount\nPOST/PUT/DELETE /{id}/items\nGET /baskets"]
        SAPP["Shopping Application\n─────────────────\nBasketService\nBasketReadService"]
        SDOMAIN["Shopping Domain\n─────────────────\nBasket (Aggregate Root)\nBasketItem (Entity)\nItemPricing (Value Object)"]
        SINFRA["Shopping Infrastructure\n─────────────────\nBasketRepository\nShoppingOutboxPublisher\nProductAdapter (ACL)\nProductsHttpClient\nProductSyncAdapter\nCustomerAdapter (ACL)\nCustomersHttpClient"]
        SSUBSCRIBE["Shopping.Subscribe\n─────────────────\nProductModifySubscriber\nProductDeleteSubscriber"]
        SOUTBOX["Shopping.Relay\n─────────────────\nOutbox to Service Bus\nPartitioned relay"]
        SDB[("SQL Server\n[Shopping] schema\n─────────────\nBasket\nBasketItem\nProduct (replica)\nOutbox / OutboxLease\nRef data")]
    end

    PAPI --> PAPP
    CAPI --> CDB
    CAPI -->|"L1/L2 Hybrid Cache + backplane"| REDIS
    CDB -->|"Change feed"| COUTBOX
    COUTBOX -->|"Publish customer and reference-data events"| ASB
    PAPP --> PINFRA
    PINFRA --> PDB
    POUTBOX -->|"Poll Outbox table"| PDB

    SAPI --> SAPP
    SAPP --> SDOMAIN
    SAPP --> SINFRA
    SINFRA --> SDB
    SOUTBOX -->|"Poll Outbox table"| SDB
    SINFRA -->|"L1/L2 Hybrid Cache"| REDIS

    SINFRA -->|"① HTTP POST /api/inventory/reserve\nReserve inventory at checkout"| PAPI
    SINFRA -->|"⑧ HTTP GET /api/customers/{id}\nValidate customer + default address"| CAPI

    POUTBOX -->|"② Publish product.created/updated/deleted"| ASB
    ASB -->|"③ Consume product events (replication)"| SSUBSCRIBE
    SSUBSCRIBE -->|"④ Sync product replica"| SDB

    SOUTBOX -->|"⑤ Publish reservation.confirm (on checkout success)"| ASB
    SINFRA -->|"⑥ Publish reservation.cancel (on checkout failure, direct)"| ASB
    ASB -->|"⑦ Consume reservation commands"| PSUBSCRIBE
    PSUBSCRIBE --> PAPP

    PDB --- SQLSERVER
    SDB --- SQLSERVER

    PAPI -.->|"OpenTelemetry"| ASPIRE
    SAPI -.->|"OpenTelemetry"| ASPIRE
Loading

Inter-Domain Communication

Flow Direction Mechanism
① Inventory reservation Shopping → Products Synchronous HTTP — ProductAdapter calls POST /api/inventory/reserve at basket checkout.
② – ④ Product replication Products → Shopping Products Outbox → Relay → Service Bus → Shopping.Subscribe keeps a local product replica in sync.
⑤ – ⑦ Reservation commands Shopping → Products On checkout success the outbox enqueues reservation.confirm; on failure Shopping publishes reservation.cancel directly to Service Bus (the transaction has already rolled back).
⑧ Customer lookup Shopping → Customers Synchronous HTTP — CustomerAdapter calls GET /api/customers/{id} when a basket is created (the customerId is validated and the shipping address defaulted from the customer) and when the checkout confirmation email is addressed. Unlike Products there is no replication: this is the alternate, real-time adapter pattern (with successful lookups held briefly in the IHybridCache).

See Patterns for the full catalog of architectural patterns demonstrated across the samples.

Project Layout

Path Purpose
src/Contoso.Products.* Products domain — Contracts, Application, Infrastructure, API, Relay, Subscribe, CodeGen, Database
src/Contoso.Shopping.* Shopping domain — same layer split plus Domain aggregate
src/Contoso.Mcp HTTP MCP facade that composes the Products and Shopping APIs
src/Contoso.Customers.* Customers domain (Cosmos DB) — Contracts, Application, Infrastructure, API, Relay, CodeGen, Database (Cosmos provisioning console); no Subscribe project
src/Contoso.Orders.* Orders domain (work in progress)
aspire/Contoso.Aspire Aspire AppHost — orchestrates all hosts for local development and E2E validation
tests/Contoso.*.Test.* Unit, API, Relay, and Subscribe test projects per domain
tests/Contoso.E2E.Runner Interactive E2E and load-simulation console runner

See Layers for the full layer-by-layer breakdown of each project's responsibilities.

Prerequisites

  • .NET 11 SDK for the full net8.0, net9.0, net10.0, and net11.0 build; install the corresponding runtimes to run each target.

  • A container runtime (Docker or Podman).

  • Aspire CLI:

    # Windows (PowerShell)
    iwr -useb https://aspire.dev/install.ps1 | iex
    
    # Linux/macOS
    curl -sSL https://aspire.dev/install.sh | bash

    Verify with aspire --version. See aspire.dev/get-started/install-cli for details.

Getting Started

1 — Start Infrastructure

podman compose -f docker-compose.yml up -d

This starts the required data store(s), Redis, and the Azure Service Bus emulator.

2 — Initialize Databases

Run migrations and seed reference data for each domain:

dotnet run --project samples/src/Contoso.Products.Database -- All
dotnet run --project samples/src/Contoso.Shopping.Database -- All
dotnet run --project samples/src/Contoso.Orders.Database   -- All

Customers (Cosmos DB) is schemaless, so Contoso.Customers.Database is not a schema migration tool: it declares the containers and seed data and runs them through the reusable CoreEx.Cosmos.Provisioning console (dotnet run --project samples/src/Contoso.Customers.Database -- All; use DropAndAll or Create,ResetAndData to start clean, noting Drop/Reset prompt for confirmation unless --accept-prompts is specified; ResetAndData alone fails where the database does not yet exist). Tests reuse the same definition via Test.MigrateCosmosDataAsync<TestData>(...).

The E2E runner's Database Migration and Base Data Refresh option loads the shared demo catalog, bootstraps Shopping and prepares real-model search. This is a destructive reset: stop writers and restart serving hosts/caches afterwards. See Aspire & E2E for details.

See Tooling for the full list of database commands and what each does.

3 — Start All Hosts

aspire run

This starts every domain API, Outbox Relay, Subscribe host, and the Contoso MCP endpoint as a single distributed application and opens the Aspire Dashboard for centralized logs, traces, and metrics. See Aspire & E2E for a full walkthrough and the Contoso MCP demo for connecting a local MCP client.

4 — Run Tests

dotnet test samples/tests/Contoso.Products.Test.Unit
dotnet test samples/tests/Contoso.Products.Test.Api
dotnet test samples/tests/Contoso.Products.Test.Relay
dotnet test samples/tests/Contoso.Products.Test.Subscribe
dotnet test samples/tests/Contoso.Shopping.Test.Api
dotnet test samples/tests/Contoso.Customers.Test.Unit
dotnet test samples/tests/Contoso.Customers.Test.Api
dotnet test samples/tests/Contoso.Customers.Test.Relay

The required infrastructure (data store, Redis, Service Bus emulator) must be running for API, Relay, and Subscribe tests. Customers' API tests require cosmos-emulator and Redis instead of a SQL Server/Postgres store; its Relay tests require Cosmos and Service Bus.

The Customers relay deliberately skips pending events older than its startup boundary when no checkpoint exists. Subsequent restarts resume saved checkpoints; delivery is at-least-once and retries can duplicate messages. Provision $outbox-leases with Contoso.Customers.Database before starting the relay. See Hosts for configuration and recovery implications.

See Testing for an explanation of test taxonomy, intra-domain vs inter-domain boundaries, data seeding, mock patterns, and the fluent assertion model.

5 — Run E2E Scenarios

dotnet run --project samples/tests/Contoso.E2E.Runner

The runner drives real HTTP calls across all domains, supports one-shot scenarios and parallel load simulation, and requires all hosts to be running (step 3 above).

See Aspire & E2E for the interactive menu reference, configuration, and recommended first-run order.

Stop Infrastructure

podman compose -f docker-compose.yml down

Troubleshooting

Outbox Relay Does Not Pick Up Messages

Symptom:

  • API operations succeed but published events are not processed by the relay/subscriber as expected.

Likely cause:

  • Local machine UTC time is skewed relative to message timestamps (clock drift where local UTC is ahead of expected outbox processing windows).

What to try:

  1. Verify and correct system date/time and time zone settings.
  2. Restart the outbox relay host (or restart all sample hosts from Aspire).
  3. If the behavior persists, restart the machine to force a clean time sync.

Dependencies Not Healthy

Symptom:

  • Hosts fail on startup or repeatedly log dependency connectivity errors.

What to try:

  1. Ensure infrastructure containers are running: podman compose -f docker-compose.yml up -d.
  2. Check container health: docker ps or podman ps.
  3. Restart containers: podman compose -f docker-compose.yml down && podman compose -f docker-compose.yml up -d.

Database Errors On Startup

Symptom:

  • API or relay hosts fail with database or schema-related errors.

What to try:

  1. Re-run migrations and data seeding for the affected domain (step 2 above).
  2. Confirm the data store container(s) are healthy before restarting hosts.