From dc96d781b7f2f4142db6b3ffde20a2aa237579d0 Mon Sep 17 00:00:00 2001 From: M-Grimaldi-Neuram Date: Wed, 25 Nov 2026 12:08:47 +0100 Subject: [PATCH 1/2] fix: make matching engine consistent with the event store - Order book is per symbol; resting orders are inserted once (no re-match on AddOrder) - Engine writes are serialized (SemaphoreSlim) for the full match + persist unit - Book is checkpointed and restored when persistence fails; change tracker cleared on retry - Recovery loads open orders by time priority without matching - Settlement: buyers pay trade price and release reservation at limit price - Maker accounts get their own OrderMatched events/versions; events carry balance deltas - Replay supports all account events (legacy OrderMatched counted as skipped) - Cancel tolerates orders missing from the book and rolls back on failure - Idempotency keys are claimed atomically, scoped to method+path, released on failure - Tests for engine service and handlers (EF InMemory) Co-Authored-By: Claude Opus 5.5 --- .../Notifications/NotificationHandlerTests.cs | 6 +- .../Application/Orders/OrderHandlerTests.cs | 153 +++++++++++ .../Domain/OrderBook/OrderBookTests.cs | 6 +- .../Infrastructure/OrderBookServiceTests.cs | 98 +++++++ backend-csharp.Tests/NexusEngine.Tests.csproj | 1 + .../Abstractions/INexusUnitOfWork.cs | 2 + .../Abstractions/IOrderBookService.cs | 49 ++-- .../DepositFunds/DepositFundsHandler.cs | 22 +- .../ReplayAccount/ReplayAccountHandler.cs | 56 +++- .../ReplayAccount/ReplayAccountQuery.cs | 4 +- .../Application/Common/AccountLedger.cs | 58 ++++ .../CancelOrder/CancelOrderHandler.cs | 85 +++--- .../Commands/PlaceOrder/PlaceOrderHandler.cs | 259 +++++++----------- backend-csharp/Domain/OrderBook/OrderBook.cs | 44 +++ .../Idempotency/IdempotencyFilter.cs | 110 ++++++-- .../OrderBookChangedNotificationHandler.cs | 2 +- .../OrderBook/OrderBookRecoveryService.cs | 14 +- .../OrderBook/OrderBookService.cs | 123 +++++---- .../Persistence/NexusUnitOfWork.cs | 2 + 19 files changed, 722 insertions(+), 372 deletions(-) create mode 100644 backend-csharp.Tests/Application/Orders/OrderHandlerTests.cs create mode 100644 backend-csharp.Tests/Infrastructure/OrderBookServiceTests.cs create mode 100644 backend-csharp/Application/Common/AccountLedger.cs diff --git a/backend-csharp.Tests/Application/Notifications/NotificationHandlerTests.cs b/backend-csharp.Tests/Application/Notifications/NotificationHandlerTests.cs index 5b79ee0..1964070 100644 --- a/backend-csharp.Tests/Application/Notifications/NotificationHandlerTests.cs +++ b/backend-csharp.Tests/Application/Notifications/NotificationHandlerTests.cs @@ -115,7 +115,7 @@ public async Task Handle_FetchesSnapshotAndBroadcasts() { var mockOrderBookService = new Mock(); var expectedSnapshot = new { Bids = new object[] { }, Asks = new object[] { }, Symbol = "TEST" }; - mockOrderBookService.Setup(s => s.GetSnapshot()).Returns(expectedSnapshot); + mockOrderBookService.Setup(s => s.GetSnapshot("TEST")).Returns(expectedSnapshot); var mockClients = new Mock(); var mockClientProxy = new Mock(); @@ -130,7 +130,7 @@ public async Task Handle_FetchesSnapshotAndBroadcasts() await handler.Handle(notification, CancellationToken.None); - mockOrderBookService.Verify(s => s.GetSnapshot(), Times.Once); + mockOrderBookService.Verify(s => s.GetSnapshot("TEST"), Times.Once); mockClientProxy.Verify( p => p.SendCoreAsync( "OrderBookSnapshot", @@ -146,7 +146,7 @@ public async Task Handle_FetchesSnapshotAndBroadcasts() public async Task Handle_CancellationToken_ForwardsToSignalR() { var mockOrderBookService = new Mock(); - mockOrderBookService.Setup(s => s.GetSnapshot()).Returns(new object()); + mockOrderBookService.Setup(s => s.GetSnapshot("TEST")).Returns(new object()); var mockClients = new Mock(); var mockClientProxy = new Mock(); diff --git a/backend-csharp.Tests/Application/Orders/OrderHandlerTests.cs b/backend-csharp.Tests/Application/Orders/OrderHandlerTests.cs new file mode 100644 index 0000000..257146c --- /dev/null +++ b/backend-csharp.Tests/Application/Orders/OrderHandlerTests.cs @@ -0,0 +1,153 @@ +namespace NexusEngine.Tests.Application.Orders; + +using MediatR; +using Microsoft.EntityFrameworkCore; +using Moq; +using NexusEngine.Api.Application.Accounts.Commands.DepositFunds; +using NexusEngine.Api.Application.Accounts.Queries.ReplayAccount; +using NexusEngine.Api.Application.Orders.Commands.CancelOrder; +using NexusEngine.Api.Application.Orders.Commands.PlaceOrder; +using NexusEngine.Api.Application.Orders.Validation; +using NexusEngine.Api.Domain.Entities; +using NexusEngine.Api.Infrastructure.Persistence; +using NexusEngine.Infrastructure.OrderBook; +using Xunit; + +public class OrderHandlerTests +{ + private readonly string _dbName = Guid.NewGuid().ToString(); + private readonly OrderBookService _engine = new(); + private readonly Mock _mediator = new(); + + private NexusUnitOfWork NewUow() => new(new NexusDbContext( + new DbContextOptionsBuilder().UseInMemoryDatabase(_dbName).Options)); + + private async Task CreateAccount(decimal deposit) + { + var id = Guid.NewGuid(); + var uow = NewUow(); + uow.Accounts.Add(new Account { Id = id, OwnerName = "t", Currency = "USD", LastEventVersion = 1 }); + uow.DomainEvents.Add(new DomainEvent + { + AggregateId = id, + AggregateType = "Account", + EventType = "AccountCreated", + AggregateVersion = 1, + Payload = "{\"OwnerName\":\"t\",\"Currency\":\"USD\",\"InitialBalance\":0}" + }); + await uow.SaveChangesAsync(); + + if (deposit > 0) + await new DepositFundsHandler(NewUow()).Handle(new DepositFundsCommand(id, deposit), default); + + return id; + } + + private Task Place(Guid account, string side, decimal qty, decimal price, string symbol = "BTC/USD") + { + var handler = new PlaceOrderHandler( + NewUow(), + [new AccountExistsValidation(), new AccountActiveValidation(), new SufficientBalanceValidation()], + _engine, + _mediator.Object); + return handler.Handle(new PlaceOrderCommand(account, symbol, side, qty, price), default); + } + + private Task Cancel(Guid orderId, Guid account, OrderBookService? engine = null) => + new CancelOrderHandler(NewUow(), engine ?? _engine, _mediator.Object) + .Handle(new CancelOrderCommand(orderId, account), default); + + private async Task LoadAccount(Guid id) => (await NewUow().Accounts.FindAsync(id))!; + + private async Task LoadOrder(Guid id) => (await NewUow().Orders.FindAsync(id))!; + + [Fact] + public async Task Fill_BuyerPaysTradePrice_AndPriceImprovementIsReleased() + { + var seller = await CreateAccount(0m); + var buyer = await CreateAccount(1000m); + + await Place(seller, "Sell", 2m, 90m); + await Place(buyer, "Buy", 2m, 100m); + + var b = await LoadAccount(buyer); + Assert.Equal(820m, b.Balance); + Assert.Equal(0m, b.ReservedBalance); + Assert.Equal(180m, (await LoadAccount(seller)).Balance); + } + + [Fact] + public async Task RestingOrder_IsInBookOnlyOnce() + { + var buyer = await CreateAccount(1000m); + var seller = await CreateAccount(0m); + + await Place(buyer, "Buy", 1m, 100m); + await Place(seller, "Sell", 1m, 100m); + var second = await Place(seller, "Sell", 1m, 100m); + + Assert.Equal("Pending", (await LoadOrder(second)).Status); + } + + [Fact] + public async Task EveryAccount_ReplayMatchesProjection() + { + var seller = await CreateAccount(0m); + var buyer = await CreateAccount(1000m); + + await Place(seller, "Sell", 3m, 90m); + await Place(buyer, "Buy", 2m, 100m); + var resting = await Place(buyer, "Buy", 1m, 50m); + await Cancel(resting, buyer); + + foreach (var id in new[] { seller, buyer }) + { + var projection = await LoadAccount(id); + var replay = await new ReplayAccountHandler(NewUow()).Handle(new ReplayAccountQuery(id), default); + + Assert.NotNull(replay); + Assert.Equal(projection.Balance, replay!.Balance); + Assert.Equal(projection.ReservedBalance, replay.ReservedBalance); + Assert.Equal(projection.LastEventVersion, replay.LastEventVersion); + Assert.Equal(0, replay.LegacyEventsSkipped); + } + } + + [Fact] + public async Task RejectedOrder_LeavesBookUntouched() + { + var seller = await CreateAccount(0m); + await Place(seller, "Sell", 1m, 100m); + + var poorBuyer = await CreateAccount(10m); + await Assert.ThrowsAsync(() => Place(poorBuyer, "Buy", 1m, 100m)); + + var buyer = await CreateAccount(1000m); + await Place(buyer, "Buy", 1m, 100m); + Assert.Equal(100m, (await LoadAccount(seller)).Balance); + } + + [Fact] + public async Task DifferentSymbols_DoNotCross() + { + var seller = await CreateAccount(0m); + var buyer = await CreateAccount(1000m); + + await Place(seller, "Sell", 1m, 100m, "BTC/USD"); + var buyId = await Place(buyer, "Buy", 1m, 100m, "ETH/USD"); + + Assert.Equal("Pending", (await LoadOrder(buyId)).Status); + } + + [Fact] + public async Task Cancel_OrderMissingFromBook_StillReleasesReservation() + { + var buyer = await CreateAccount(1000m); + var orderId = await Place(buyer, "Buy", 1m, 100m); + + await Cancel(orderId, buyer, new OrderBookService()); + + Assert.Equal(0m, (await LoadAccount(buyer)).ReservedBalance); + Assert.Equal("Cancelled", (await LoadOrder(orderId)).Status); + } +} diff --git a/backend-csharp.Tests/Domain/OrderBook/OrderBookTests.cs b/backend-csharp.Tests/Domain/OrderBook/OrderBookTests.cs index 5c5633a..d1f2784 100644 --- a/backend-csharp.Tests/Domain/OrderBook/OrderBookTests.cs +++ b/backend-csharp.Tests/Domain/OrderBook/OrderBookTests.cs @@ -244,10 +244,10 @@ public void Recovery_AddOrdersToNewBook_RestoresState() initialBook.Match(buyOrder); initialBook.Match(sellOrder); - // Simulate recovery: fresh book, reload orders via AddOrder + // Simulate recovery: fresh book, reload orders via Add (no matching) var recoveredBook = new NexusEngine.Domain.OrderBook.OrderBook("TEST"); - recoveredBook.Match(buyOrder); - recoveredBook.Match(sellOrder); + recoveredBook.Add(buyOrder); + recoveredBook.Add(sellOrder); // Assert Assert.Contains(100m, recoveredBook.Bids.Keys); diff --git a/backend-csharp.Tests/Infrastructure/OrderBookServiceTests.cs b/backend-csharp.Tests/Infrastructure/OrderBookServiceTests.cs new file mode 100644 index 0000000..d491203 --- /dev/null +++ b/backend-csharp.Tests/Infrastructure/OrderBookServiceTests.cs @@ -0,0 +1,98 @@ +namespace NexusEngine.Tests.Infrastructure; + +using NexusEngine.Api.Domain.Entities; +using NexusEngine.Infrastructure.OrderBook; +using Xunit; +using Book = NexusEngine.Domain.OrderBook.OrderBook; + +public class OrderBookServiceTests +{ + private static Order NewOrder(string symbol, string side, decimal price, decimal qty) => new() + { + Id = Guid.NewGuid(), + Symbol = symbol, + Side = side, + Price = price, + Quantity = qty, + RemainingQuantity = qty + }; + + [Fact] + public void Book_Add_DoesNotMatchCrossingOrders() + { + var book = new Book("TEST"); + book.Add(NewOrder("TEST", "Buy", 100m, 1m)); + book.Add(NewOrder("TEST", "Sell", 90m, 1m)); + + Assert.Single(book.Bids); + Assert.Single(book.Asks); + } + + [Fact] + public void Book_Match_RestingRemainderIsInsertedExactlyOnce() + { + var book = new Book("TEST"); + book.Match(NewOrder("TEST", "Buy", 100m, 2m)); + + Assert.Single(book.Bids[100m]); + } + + [Fact] + public void Book_TryRemoveOrder_MissingOrder_ReturnsFalse() + { + var book = new Book("TEST"); + Assert.False(book.TryRemoveOrder(NewOrder("TEST", "Buy", 100m, 1m))); + } + + [Fact] + public void Book_Clone_IsIndependentOfOriginal() + { + var book = new Book("TEST"); + book.Match(NewOrder("TEST", "Sell", 100m, 5m)); + var clone = book.Clone(); + + book.Match(NewOrder("TEST", "Buy", 100m, 5m)); + + Assert.Empty(book.Asks); + Assert.Equal(5m, clone.Asks[100m].Peek().RemainingQuantity); + } + + [Fact] + public void Service_BooksAreIsolatedPerSymbol() + { + var service = new OrderBookService(); + service.Match(NewOrder("BTC/USD", "Sell", 100m, 1m)); + + var result = service.Match(NewOrder("ETH/USD", "Buy", 200m, 1m)); + + Assert.Empty(result.Trades); + } + + [Fact] + public void Service_Restore_RevertsMatching() + { + var service = new OrderBookService(); + service.Match(NewOrder("BTC/USD", "Sell", 100m, 1m)); + + var checkpoint = service.Checkpoint("BTC/USD"); + Assert.Single(service.Match(NewOrder("BTC/USD", "Buy", 100m, 1m)).Trades); + + service.Restore(checkpoint); + + Assert.Single(service.Match(NewOrder("BTC/USD", "Buy", 100m, 1m)).Trades); + } + + [Fact] + public async Task Service_Acquire_SerializesWriters() + { + var service = new OrderBookService(); + var first = await service.AcquireAsync(); + + var second = service.AcquireAsync(); + await Task.Delay(50); + Assert.False(second.IsCompleted); + + first.Dispose(); + (await second).Dispose(); + } +} diff --git a/backend-csharp.Tests/NexusEngine.Tests.csproj b/backend-csharp.Tests/NexusEngine.Tests.csproj index 65d5925..d9fdc6f 100644 --- a/backend-csharp.Tests/NexusEngine.Tests.csproj +++ b/backend-csharp.Tests/NexusEngine.Tests.csproj @@ -10,6 +10,7 @@ + diff --git a/backend-csharp/Application/Abstractions/INexusUnitOfWork.cs b/backend-csharp/Application/Abstractions/INexusUnitOfWork.cs index 0f5ade8..149e0d8 100644 --- a/backend-csharp/Application/Abstractions/INexusUnitOfWork.cs +++ b/backend-csharp/Application/Abstractions/INexusUnitOfWork.cs @@ -29,5 +29,7 @@ public interface INexusUnitOfWork DbSet DomainEvents { get; } DbSet IdempotencyKeys { get; } + void DiscardChanges(); + Task SaveChangesAsync(CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/backend-csharp/Application/Abstractions/IOrderBookService.cs b/backend-csharp/Application/Abstractions/IOrderBookService.cs index 64d7d8e..647d6a3 100644 --- a/backend-csharp/Application/Abstractions/IOrderBookService.cs +++ b/backend-csharp/Application/Abstractions/IOrderBookService.cs @@ -1,31 +1,7 @@ -// ============================================================================ -// Copyright (c) NexusEngine Enterprise. All rights reserved. -// Product: NexusEngine.Api -// Layer: Application.Abstractions -// -// FILE DESCRIPTION: -// Defines the service contract for the limit-order matching engine. -// Provides an abstraction over the OrderBook domain logic for the -// Application layer, following the same pattern as INexusUnitOfWork. -// -// CLASS DOCUMENTATION: -// - IOrderBookService: Interface exposing order matching and order placement -// operations. The concrete implementation lives in Infrastructure.OrderBook. -// This keeps the Application layer decoupled from the matching engine's -// internal state management. -// -// MEMBER DOCUMENTATION: -// - Match(): Processes an incoming order through price-time priority FIFO -// matching. Returns all trades produced during matching. Unmatched quantity -// is automatically added to the resting book. -// - AddOrder(): Places an order directly into the book without explicit -// match result handling. The matching engine processes it internally. -// - RemoveOrder(): Removes a resting order from the book. Throws -// InvalidOperationException if the price level or order is not found. -// - GetSnapshot(): Returns the current state of the order book as an -// anonymous object with Bids (descending by price), Asks (ascending -// by price), and Symbol. -// ============================================================================ +// Matching engine abstraction. Books are kept per symbol in memory. +// Mutations (Match/Load/Remove/Checkpoint/Restore) must happen while holding the +// engine lock obtained from AcquireAsync, so that the in-memory book and the +// database are changed as a single serialized unit of work. namespace NexusEngine.Application.Abstractions; @@ -34,11 +10,22 @@ namespace NexusEngine.Application.Abstractions; public interface IOrderBookService { + Task AcquireAsync(CancellationToken cancellationToken = default); + MatchResult Match(Order order); - void AddOrder(Order order); + void Load(Order order); + + bool RemoveOrder(Order order); + + IOrderBookCheckpoint Checkpoint(string symbol); - void RemoveOrder(Order order); + void Restore(IOrderBookCheckpoint checkpoint); - object GetSnapshot(); + object GetSnapshot(string symbol); +} + +public interface IOrderBookCheckpoint +{ + string Symbol { get; } } diff --git a/backend-csharp/Application/Accounts/Commands/DepositFunds/DepositFundsHandler.cs b/backend-csharp/Application/Accounts/Commands/DepositFunds/DepositFundsHandler.cs index b3c32d9..e30727c 100644 --- a/backend-csharp/Application/Accounts/Commands/DepositFunds/DepositFundsHandler.cs +++ b/backend-csharp/Application/Accounts/Commands/DepositFunds/DepositFundsHandler.cs @@ -26,7 +26,6 @@ namespace NexusEngine.Api.Application.Accounts.Commands.DepositFunds; -using System.Text.Json; using MediatR; using Microsoft.EntityFrameworkCore; using NexusEngine.Api.Application.Abstractions; @@ -56,6 +55,7 @@ public async Task Handle( } catch (DbUpdateException ex) when (OptimisticConcurrencyHelper.IsUniqueConstraintViolation(ex)) { + _uow.DiscardChanges(); if (attempt < maxAttempts) { var delay = Random.Shared.Next(50, 300); @@ -91,27 +91,15 @@ private async Task ExecuteOnce( throw new InvalidOperationException( $"Account {command.AccountId} is not Active."); - var nextVersion = account.LastEventVersion + 1; - - var domainEvent = new DomainEvent - { - AggregateId = command.AccountId, - AggregateType = "Account", - EventType = "FundsDeposited", - AggregateVersion = nextVersion, - Payload = JsonSerializer.Serialize(new + AccountLedger.Append(_uow, account, "FundsDeposited", orderId: null, + balanceDelta: command.Amount, reservedDelta: 0m, + new { command.Amount, BalanceBefore = account.Balance, BalanceAfter = account.Balance + command.Amount - }) - }; - - account.Balance += command.Amount; - account.LastEventVersion = nextVersion; - account.UpdatedAt = DateTime.UtcNow; + }); - _uow.DomainEvents.Add(domainEvent); await _uow.SaveChangesAsync(cancellationToken); return Unit.Value; diff --git a/backend-csharp/Application/Accounts/Queries/ReplayAccount/ReplayAccountHandler.cs b/backend-csharp/Application/Accounts/Queries/ReplayAccount/ReplayAccountHandler.cs index 0f8af30..0cdff1e 100644 --- a/backend-csharp/Application/Accounts/Queries/ReplayAccount/ReplayAccountHandler.cs +++ b/backend-csharp/Application/Accounts/Queries/ReplayAccount/ReplayAccountHandler.cs @@ -72,11 +72,10 @@ public ReplayAccountHandler(INexusUnitOfWork uow) break; case "FundsDeposited": - var deposited = JsonSerializer.Deserialize( - evt.Payload, - new JsonSerializerOptions { PropertyNameCaseInsensitive = true } - )!; - state.Balance = deposited.BalanceAfter; + case "OrderPlaced": + case "OrderMatched": + case "OrderCancelled": + ApplyBalanceEvent(state, evt.EventType, evt.Payload); break; default: @@ -87,7 +86,7 @@ public ReplayAccountHandler(INexusUnitOfWork uow) "Update the replay handler to support this event."); } } - catch (System.Text.Json.JsonException ex) + catch (Exception ex) when (ex is JsonException or KeyNotFoundException or FormatException) { throw new InvalidOperationException( $"Event {evt.Id} (type={evt.EventType}, " + @@ -102,18 +101,55 @@ public ReplayAccountHandler(INexusUnitOfWork uow) state.Id, state.OwnerName, state.Balance, + state.ReservedBalance, state.Currency, state.Status, state.LastEventVersion, - EventsReplayed: events.Count + EventsReplayed: events.Count, + LegacyEventsSkipped: state.LegacyEventsSkipped ); } + // New events carry explicit deltas. Events written before deltas existed are + // interpreted from their original fields; legacy OrderMatched events cannot be + // interpreted safely (no side information) and are counted as skipped. + private static void ApplyBalanceEvent(AccountState state, string eventType, string payload) + { + using var doc = JsonDocument.Parse(payload); + var root = doc.RootElement; + + if (root.TryGetProperty("BalanceDelta", out var balanceDelta) + && root.TryGetProperty("ReservedDelta", out var reservedDelta)) + { + state.Balance += balanceDelta.GetDecimal(); + state.ReservedBalance += reservedDelta.GetDecimal(); + return; + } + + switch (eventType) + { + case "FundsDeposited": + state.Balance = root.GetProperty("BalanceAfter").GetDecimal(); + break; + case "OrderPlaced": + state.ReservedBalance += root.GetProperty("ReservationAmount").GetDecimal(); + break; + case "OrderCancelled": + state.ReservedBalance -= root.GetProperty("RefundAmount").GetDecimal(); + break; + default: + state.LegacyEventsSkipped++; + break; + } + } + private class AccountState { public Guid Id { get; set; } public string OwnerName { get; set; } = string.Empty; public decimal Balance { get; set; } + public decimal ReservedBalance { get; set; } + public int LegacyEventsSkipped { get; set; } public string Currency { get; set; } = string.Empty; public string Status { get; set; } = string.Empty; public int LastEventVersion { get; set; } @@ -124,10 +160,4 @@ private record AccountCreatedPayload( string Currency, decimal InitialBalance ); - - private record FundsDepositedPayload( - decimal Amount, - decimal BalanceBefore, - decimal BalanceAfter - ); } \ No newline at end of file diff --git a/backend-csharp/Application/Accounts/Queries/ReplayAccount/ReplayAccountQuery.cs b/backend-csharp/Application/Accounts/Queries/ReplayAccount/ReplayAccountQuery.cs index 3715d6f..ea20999 100644 --- a/backend-csharp/Application/Accounts/Queries/ReplayAccount/ReplayAccountQuery.cs +++ b/backend-csharp/Application/Accounts/Queries/ReplayAccount/ReplayAccountQuery.cs @@ -39,9 +39,11 @@ public record ReplayAccountDto( Guid Id, string OwnerName, decimal Balance, + decimal ReservedBalance, string Currency, string Status, int LastEventVersion, - int EventsReplayed + int EventsReplayed, + int LegacyEventsSkipped ); diff --git a/backend-csharp/Application/Common/AccountLedger.cs b/backend-csharp/Application/Common/AccountLedger.cs new file mode 100644 index 0000000..324e654 --- /dev/null +++ b/backend-csharp/Application/Common/AccountLedger.cs @@ -0,0 +1,58 @@ +// Appends a domain event to an Account aggregate together with its ledger row, +// bumping the projection's version. Every balance-affecting event carries +// BalanceDelta / ReservedDelta so the account can be rebuilt purely from events. + +namespace NexusEngine.Api.Application.Common; + +using System.Text.Json; +using NexusEngine.Api.Application.Abstractions; +using NexusEngine.Api.Domain.Entities; + +public static class AccountLedger +{ + public static DomainEvent Append( + INexusUnitOfWork uow, + Account account, + string eventType, + Guid? orderId, + decimal balanceDelta, + decimal reservedDelta, + object details) + { + account.Balance += balanceDelta; + account.ReservedBalance += reservedDelta; + account.LastEventVersion++; + account.UpdatedAt = DateTime.UtcNow; + + var payload = JsonSerializer.SerializeToElement(details); + var dict = payload.EnumerateObject().ToDictionary(p => p.Name, p => (object?)p.Value); + dict["BalanceDelta"] = balanceDelta; + dict["ReservedDelta"] = reservedDelta; + + var domainEvent = new DomainEvent + { + AggregateId = account.Id, + AggregateType = "Account", + EventType = eventType, + AggregateVersion = account.LastEventVersion, + Payload = JsonSerializer.Serialize(dict) + }; + uow.DomainEvents.Add(domainEvent); + + if (orderId is not null) + { + uow.Transactions.Add(new Transaction + { + Id = Guid.NewGuid(), + AccountId = account.Id, + OrderId = orderId, + Type = eventType, + Amount = balanceDelta != 0 ? balanceDelta : -reservedDelta, + EventId = domainEvent.Id, + OccurredAt = DateTime.UtcNow + }); + } + + return domainEvent; + } +} diff --git a/backend-csharp/Application/Orders/Commands/CancelOrder/CancelOrderHandler.cs b/backend-csharp/Application/Orders/Commands/CancelOrder/CancelOrderHandler.cs index 917aa18..840595d 100644 --- a/backend-csharp/Application/Orders/Commands/CancelOrder/CancelOrderHandler.cs +++ b/backend-csharp/Application/Orders/Commands/CancelOrder/CancelOrderHandler.cs @@ -25,9 +25,9 @@ namespace NexusEngine.Api.Application.Orders.Commands.CancelOrder; -using System.Text.Json; using MediatR; using NexusEngine.Api.Application.Abstractions; +using NexusEngine.Api.Application.Common; using NexusEngine.Api.Application.Orders.Notifications; using NexusEngine.Api.Domain.Entities; using NexusEngine.Application.Abstractions; @@ -52,66 +52,55 @@ public async Task Handle( CancelOrderCommand command, CancellationToken cancellationToken) { - var order = await _uow.Orders.FindAsync([command.OrderId], cancellationToken) - ?? throw new KeyNotFoundException($"Order {command.OrderId} not found."); + Account account; + string symbol; - if (order.AccountId != command.AccountId) - throw new InvalidOperationException("Order does not belong to this account."); + using (await _orderBookService.AcquireAsync(cancellationToken)) + { + var order = await _uow.Orders.FindAsync([command.OrderId], cancellationToken) + ?? throw new KeyNotFoundException($"Order {command.OrderId} not found."); - if (order.Status != "Pending" && order.Status != "PartiallyFilled") - throw new InvalidOperationException( - "Only Pending or PartiallyFilled orders can be cancelled."); + if (order.AccountId != command.AccountId) + throw new InvalidOperationException("Order does not belong to this account."); - var account = await _uow.Accounts.FindAsync([order.AccountId], cancellationToken) - ?? throw new KeyNotFoundException($"Account {order.AccountId} not found."); + if (order.Status != "Pending" && order.Status != "PartiallyFilled") + throw new InvalidOperationException( + "Only Pending or PartiallyFilled orders can be cancelled."); - var refundAmount = order.Side == "Buy" - ? order.RemainingQuantity * order.Price - : 0m; + account = await _uow.Accounts.FindAsync([order.AccountId], cancellationToken) + ?? throw new KeyNotFoundException($"Account {order.AccountId} not found."); - _orderBookService.RemoveOrder(order); + symbol = order.Symbol; + var refundAmount = order.Side == "Buy" + ? order.RemainingQuantity * order.Price + : 0m; - account.ReservedBalance -= refundAmount; - account.UpdatedAt = DateTime.UtcNow; + order.Status = "Cancelled"; + order.UpdatedAt = DateTime.UtcNow; - order.Status = "Cancelled"; - order.UpdatedAt = DateTime.UtcNow; + AccountLedger.Append(_uow, account, "OrderCancelled", order.Id, + balanceDelta: 0m, reservedDelta: -refundAmount, + new { OrderId = order.Id, RefundAmount = refundAmount }); - account.LastEventVersion++; + var checkpoint = _orderBookService.Checkpoint(symbol); + _orderBookService.RemoveOrder(order); - var domainEvent = new DomainEvent - { - AggregateId = command.AccountId, - AggregateType = "Account", - EventType = "OrderCancelled", - AggregateVersion = account.LastEventVersion, - Payload = JsonSerializer.Serialize(new + try { - OrderId = command.OrderId, - RefundAmount = refundAmount - }) - }; - - _uow.Transactions.Add(new Transaction - { - Id = Guid.NewGuid(), - AccountId = command.AccountId, - OrderId = command.OrderId, - Type = "OrderCancelled", - Amount = refundAmount, - EventId = domainEvent.Id, - OccurredAt = DateTime.UtcNow - }); - - _uow.DomainEvents.Add(domainEvent); - await _uow.SaveChangesAsync(cancellationToken); + await _uow.SaveChangesAsync(cancellationToken); + } + catch + { + _orderBookService.Restore(checkpoint); + _uow.DiscardChanges(); + throw; + } + } - await _mediator.Publish( - new OrderBookChangedNotification(order.Symbol), cancellationToken); + await _mediator.Publish(new OrderBookChangedNotification(symbol), cancellationToken); await _mediator.Publish( - new BalanceChangedNotification( - command.AccountId, account.Balance, account.ReservedBalance), + new BalanceChangedNotification(account.Id, account.Balance, account.ReservedBalance), cancellationToken); return Unit.Value; diff --git a/backend-csharp/Application/Orders/Commands/PlaceOrder/PlaceOrderHandler.cs b/backend-csharp/Application/Orders/Commands/PlaceOrder/PlaceOrderHandler.cs index 9fcafb5..489bf62 100644 --- a/backend-csharp/Application/Orders/Commands/PlaceOrder/PlaceOrderHandler.cs +++ b/backend-csharp/Application/Orders/Commands/PlaceOrder/PlaceOrderHandler.cs @@ -1,40 +1,16 @@ -// ============================================================================ -// Copyright (c) NexusEngine Enterprise. All rights reserved. -// Product: NexusEngine.Api -// Layer: Application.Orders.Commands.PlaceOrder +// Places a limit order: validates, matches against the in-memory book, settles +// both sides of every trade and persists events + projections atomically. // -// FILE DESCRIPTION: -// Implements the MediatR handler for PlaceOrderCommand. -// Integrates with IOrderBookService to match incoming orders against -// resting liquidity using price-time priority FIFO matching. -// -// CLASS DOCUMENTATION: -// - PlaceOrderHandler: Executes the place order workflow with matching. -// Delegates validation to IOrderValidationStrategy implementations. -// Applies optimistic concurrency control via the unique constraint on -// (aggregate_id, aggregate_version) in the domain_events table. Retries -// up to 3 times with random jitter on unique constraint violations. -// Routes the order through IOrderBookService.Match() for price-time -// priority matching. Processes resulting trades by updating maker -// orders and accounts atomically. Places unmatched quantity back -// into the order book via AddOrder(). Writes OrderMatched and -// OrderPlaced domain events with corresponding transaction records. -// -// MEMBER DOCUMENTATION: -// - _uow: Injected INexusUnitOfWork -- single unit of work for atomic persistence. -// - _validations: Injected collection of validation strategies -- Open/Closed Principle. -// - _orderBookService: Injected IOrderBookService singleton -- in-memory matching engine. -// - _mediator: Injected IMediator -- publishes notifications after successful persistence. -// - Handle: Validates, matches via OrderBook, processes trades, persists atomically. -// - ApplyTradeToAccount: Adjusts account balance and reserved balance based on trade side. -// Throws KeyNotFoundException if account or maker order does not exist. -// Throws InvalidOperationException if any validation rule is violated -// or retries are exhausted due to concurrent activity. -// ============================================================================ +// Consistency rules: +// - The whole command runs under the matching-engine lock (serialized writers). +// - The book is checkpointed before matching and restored if persistence fails, +// so memory never diverges from the database. +// - Buyers reserve quantity * limit price; on each fill they pay quantity * trade +// price and release quantity * their own limit price (price improvement is freed). +// - Every affected account (taker and makers) receives its own event and version. namespace NexusEngine.Api.Application.Orders.Commands.PlaceOrder; -using System.Text.Json; using MediatR; using Microsoft.EntityFrameworkCore; using NexusEngine.Api.Application.Abstractions; @@ -43,9 +19,12 @@ namespace NexusEngine.Api.Application.Orders.Commands.PlaceOrder; using NexusEngine.Api.Application.Orders.Validation; using NexusEngine.Api.Domain.Entities; using NexusEngine.Application.Abstractions; +using NexusEngine.Domain.OrderBook; public class PlaceOrderHandler : IRequestHandler { + private const int MaxAttempts = 3; + private readonly INexusUnitOfWork _uow; private readonly IEnumerable _validations; private readonly IOrderBookService _orderBookService; @@ -63,53 +42,60 @@ public PlaceOrderHandler( _mediator = mediator; } - private static void ApplyTradeToAccount(Account account, string side, decimal amount) + public async Task Handle(PlaceOrderCommand command, CancellationToken cancellationToken) { - if (side == "Buy") + Outcome outcome; + + using (await _orderBookService.AcquireAsync(cancellationToken)) { - account.ReservedBalance -= amount; + outcome = await ExecuteWithRetry(command, cancellationToken); } - else + + if (outcome.Trades.Count > 0) + await _mediator.Publish(new TradeExecutedNotification(outcome.Trades), cancellationToken); + + await _mediator.Publish(new OrderBookChangedNotification(command.Symbol), cancellationToken); + + foreach (var account in outcome.TouchedAccounts) { - account.Balance += amount; + await _mediator.Publish( + new BalanceChangedNotification(account.Id, account.Balance, account.ReservedBalance), + cancellationToken); } - account.UpdatedAt = DateTime.UtcNow; + + return outcome.OrderId; } - public async Task Handle( - PlaceOrderCommand command, - CancellationToken cancellationToken) + private async Task ExecuteWithRetry(PlaceOrderCommand command, CancellationToken cancellationToken) { - const int maxAttempts = 3; - - for (var attempt = 1; attempt <= maxAttempts; attempt++) + for (var attempt = 1; ; attempt++) { + var checkpoint = _orderBookService.Checkpoint(command.Symbol); try { return await ExecuteOnce(command, cancellationToken); } - catch (DbUpdateException ex) when (OptimisticConcurrencyHelper.IsUniqueConstraintViolation(ex)) + catch (Exception ex) { - if (attempt < maxAttempts) - { - var delay = Random.Shared.Next(50, 300); - await Task.Delay(delay, cancellationToken); - } - else - { + _orderBookService.Restore(checkpoint); + _uow.DiscardChanges(); + + var retryable = ex is DbUpdateException dbEx + && OptimisticConcurrencyHelper.IsUniqueConstraintViolation(dbEx); + + if (!retryable) + throw; + + if (attempt >= MaxAttempts) throw new InvalidOperationException( "Order could not be placed due to concurrent activity. Please try again."); - } + + await Task.Delay(Random.Shared.Next(50, 300), cancellationToken); } } - - throw new InvalidOperationException( - "Order could not be placed due to concurrent activity. Please try again."); } - private async Task ExecuteOnce( - PlaceOrderCommand command, - CancellationToken cancellationToken) + private async Task ExecuteOnce(PlaceOrderCommand command, CancellationToken cancellationToken) { var account = await _uow.Accounts .FirstOrDefaultAsync(a => a.Id == command.AccountId, cancellationToken); @@ -117,15 +103,14 @@ private async Task ExecuteOnce( foreach (var validation in _validations) validation.Validate(account, command); - var reservationAmount = command.Side == "Buy" - ? command.Quantity * command.Price - : 0m; - - var orderId = Guid.NewGuid(); + var taker = account!; + var isBuy = command.Side == "Buy"; + var reservation = isBuy ? command.Quantity * command.Price : 0m; + var now = DateTime.UtcNow; var order = new Order { - Id = orderId, + Id = Guid.NewGuid(), AccountId = command.AccountId, Symbol = command.Symbol, Side = command.Side, @@ -134,23 +119,31 @@ private async Task ExecuteOnce( FilledQuantity = 0, Price = command.Price, Status = "Pending", - CreatedAt = DateTime.UtcNow + CreatedAt = now, + UpdatedAt = now }; - var matchResult = _orderBookService.Match(order); - - account!.ReservedBalance += reservationAmount; + AccountLedger.Append(_uow, taker, "OrderPlaced", order.Id, + balanceDelta: 0m, reservedDelta: reservation, + new + { + OrderId = order.Id, + command.Symbol, + command.Side, + command.Quantity, + command.Price, + ReservationAmount = reservation + }); - var domainEvents = new List(); - var transactions = new List(); - var version = account.LastEventVersion; + var matchResult = _orderBookService.Match(order); + var touched = new Dictionary { [taker.Id] = taker }; foreach (var trade in matchResult.Trades) { - var makerOrder = await _uow.Orders.FindAsync(trade.MakerOrderId, cancellationToken) + var makerOrder = await _uow.Orders.FindAsync([trade.MakerOrderId], cancellationToken) ?? throw new KeyNotFoundException($"Maker order {trade.MakerOrderId} not found."); - var makerAccount = await _uow.Accounts.FindAsync(makerOrder.AccountId, cancellationToken) + var makerAccount = await _uow.Accounts.FindAsync([makerOrder.AccountId], cancellationToken) ?? throw new KeyNotFoundException($"Maker account {makerOrder.AccountId} not found."); makerOrder.RemainingQuantity -= trade.Quantity; @@ -158,107 +151,43 @@ private async Task ExecuteOnce( makerOrder.Status = makerOrder.RemainingQuantity == 0 ? "Filled" : "PartiallyFilled"; makerOrder.UpdatedAt = DateTime.UtcNow; - ApplyTradeToAccount(makerAccount, makerOrder.Side, trade.Price * trade.Quantity); - ApplyTradeToAccount(account, order.Side, trade.Price * trade.Quantity); + Settle(makerAccount, makerOrder, order.Id, trade, "Maker"); + Settle(taker, order, makerOrder.Id, trade, "Taker"); - version++; - var matchedEvent = new DomainEvent - { - AggregateId = command.AccountId, - AggregateType = "Account", - EventType = "OrderMatched", - AggregateVersion = version, - Payload = JsonSerializer.Serialize(new - { - OrderId = orderId, - MakerOrderId = trade.MakerOrderId, - trade.Price, - trade.Quantity - }) - }; - domainEvents.Add(matchedEvent); - - transactions.Add(new Transaction - { - Id = Guid.NewGuid(), - AccountId = command.AccountId, - OrderId = orderId, - Type = "OrderMatched", - Amount = trade.Price * trade.Quantity, - EventId = matchedEvent.Id, - OccurredAt = DateTime.UtcNow - }); + touched[makerAccount.Id] = makerAccount; } var totalTraded = matchResult.Trades.Sum(t => t.Quantity); order.FilledQuantity = totalTraded; order.RemainingQuantity = command.Quantity - totalTraded; - - if (order.RemainingQuantity == 0) - order.Status = "Filled"; - else if (order.FilledQuantity > 0) - order.Status = "PartiallyFilled"; - - if (order.RemainingQuantity > 0) - _orderBookService.AddOrder(order); - - version++; - var placedEvent = new DomainEvent - { - AggregateId = command.AccountId, - AggregateType = "Account", - EventType = "OrderPlaced", - AggregateVersion = version, - Payload = JsonSerializer.Serialize(new - { - OrderId = orderId, - command.Symbol, - command.Side, - command.Quantity, - command.Price, - ReservationAmount = reservationAmount - }) - }; - domainEvents.Add(placedEvent); - - transactions.Add(new Transaction - { - Id = Guid.NewGuid(), - AccountId = command.AccountId, - OrderId = orderId, - Type = "OrderPlaced", - Amount = -reservationAmount, - EventId = placedEvent.Id, - OccurredAt = DateTime.UtcNow - }); - - account.LastEventVersion = version; - account.UpdatedAt = DateTime.UtcNow; + order.Status = order.RemainingQuantity == 0 + ? "Filled" + : totalTraded > 0 ? "PartiallyFilled" : "Pending"; _uow.Orders.Add(order); - - foreach (var evt in domainEvents) - _uow.DomainEvents.Add(evt); - - foreach (var txn in transactions) - _uow.Transactions.Add(txn); - await _uow.SaveChangesAsync(cancellationToken); - if (matchResult.Trades.Count > 0) - { - await _mediator.Publish( - new TradeExecutedNotification(matchResult.Trades), cancellationToken); - } - - await _mediator.Publish( - new OrderBookChangedNotification(command.Symbol), cancellationToken); + return new Outcome(order.Id, matchResult.Trades, touched.Values.ToList()); + } - await _mediator.Publish( - new BalanceChangedNotification( - command.AccountId, account.Balance, account.ReservedBalance), - cancellationToken); + private void Settle(Account account, Order order, Guid counterOrderId, Trade trade, string role) + { + var notional = trade.Quantity * trade.Price; + var isBuy = order.Side == "Buy"; - return orderId; + AccountLedger.Append(_uow, account, "OrderMatched", order.Id, + balanceDelta: isBuy ? -notional : notional, + reservedDelta: isBuy ? -(trade.Quantity * order.Price) : 0m, + new + { + OrderId = order.Id, + CounterOrderId = counterOrderId, + Role = role, + order.Side, + trade.Price, + trade.Quantity + }); } + + private sealed record Outcome(Guid OrderId, IReadOnlyList Trades, IReadOnlyList TouchedAccounts); } diff --git a/backend-csharp/Domain/OrderBook/OrderBook.cs b/backend-csharp/Domain/OrderBook/OrderBook.cs index 9c38cb5..3e1a5b1 100644 --- a/backend-csharp/Domain/OrderBook/OrderBook.cs +++ b/backend-csharp/Domain/OrderBook/OrderBook.cs @@ -157,6 +157,50 @@ public void RemoveOrder(Order order) } } + public void Add(Order order) + { + if (order.RemainingQuantity > 0) + AddToBook(order); + } + + public bool TryRemoveOrder(Order order) + { + var book = order.Side.Equals("Buy", StringComparison.OrdinalIgnoreCase) + ? _bids + : _asks; + + if (!book.TryGetValue(order.Price, out var queue) || queue.All(o => o.Id != order.Id)) + return false; + + RemoveOrder(order); + return true; + } + + public OrderBook Clone() + { + var copy = new OrderBook(Symbol); + foreach (var level in _bids) + copy._bids[level.Key] = new Queue(level.Value.Select(CopyOrder)); + foreach (var level in _asks) + copy._asks[level.Key] = new Queue(level.Value.Select(CopyOrder)); + return copy; + } + + private static Order CopyOrder(Order o) => new() + { + Id = o.Id, + AccountId = o.AccountId, + Symbol = o.Symbol, + Side = o.Side, + Price = o.Price, + Quantity = o.Quantity, + RemainingQuantity = o.RemainingQuantity, + FilledQuantity = o.FilledQuantity, + Status = o.Status, + CreatedAt = o.CreatedAt, + UpdatedAt = o.UpdatedAt + }; + private void AddToBook(Order order) { var book = order.Side.Equals("Buy", StringComparison.OrdinalIgnoreCase) diff --git a/backend-csharp/Infrastructure/Idempotency/IdempotencyFilter.cs b/backend-csharp/Infrastructure/Idempotency/IdempotencyFilter.cs index 94716c7..b9cba7b 100644 --- a/backend-csharp/Infrastructure/Idempotency/IdempotencyFilter.cs +++ b/backend-csharp/Infrastructure/Idempotency/IdempotencyFilter.cs @@ -25,15 +25,25 @@ namespace NexusEngine.Api.Infrastructure.Idempotency; +using System.Security.Cryptography; +using System.Text; using System.Text.Json; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.EntityFrameworkCore; using NexusEngine.Api.Application.Abstractions; +using NexusEngine.Api.Application.Common; using NexusEngine.Api.Domain.Entities; +// The key is claimed atomically BEFORE the action runs by inserting a placeholder +// row (ResponseStatus = 0); the primary key makes concurrent duplicates fail. +// A duplicate arriving while the first request is still running gets 409; a +// duplicate arriving afterwards gets the stored response. Failed requests release +// the key so the client can retry. Keys are scoped to method + path. public class IdempotencyFilter : IAsyncActionFilter { + private const int InProgress = 0; + private readonly INexusUnitOfWork _uow; public IdempotencyFilter(INexusUnitOfWork uow) @@ -45,47 +55,91 @@ public async Task OnActionExecutionAsync( ActionExecutingContext context, ActionExecutionDelegate next) { - if (!context.HttpContext.Request.Headers - .TryGetValue("X-Idempotency-Key", out var idempotencyKeyValues)) + var request = context.HttpContext.Request; + if (!request.Headers.TryGetValue("X-Idempotency-Key", out var values) + || string.IsNullOrWhiteSpace(values.ToString())) { await next(); return; } - var idempotencyKey = idempotencyKeyValues.ToString(); - - var existing = await _uow.IdempotencyKeys - .FirstOrDefaultAsync(k => k.Key == idempotencyKey, - context.HttpContext.RequestAborted); + var ct = context.HttpContext.RequestAborted; + var key = Scope(request.Method, request.Path, values.ToString()); - if (existing is not null) + if (!await TryClaim(key, ct)) { - context.Result = new ContentResult - { - StatusCode = existing.ResponseStatus, - Content = existing.ResponseBody, - ContentType = "application/json" - }; + var existing = await _uow.IdempotencyKeys.AsNoTracking() + .FirstOrDefaultAsync(k => k.Key == key, ct); + + context.Result = existing is null || existing.ResponseStatus == InProgress + ? new ConflictObjectResult("A request with this idempotency key is already in progress.") + : new ContentResult + { + StatusCode = existing.ResponseStatus, + Content = existing.ResponseBody, + ContentType = "application/json" + }; return; } var executed = await next(); - if (executed.Result is ObjectResult { Value: not null } objectResult) + _uow.DiscardChanges(); + var row = await _uow.IdempotencyKeys.FirstOrDefaultAsync(k => k.Key == key, CancellationToken.None); + if (row is null) + return; + + var status = (executed.Result as ObjectResult)?.StatusCode + ?? (executed.Result as StatusCodeResult)?.StatusCode; + + if (executed.Exception is null + && executed.Result is ObjectResult { Value: not null } result + && status is >= 200 and < 300) + { + row.ResponseBody = JsonSerializer.Serialize(result.Value); + row.ResponseStatus = status.Value; + } + else + { + _uow.IdempotencyKeys.Remove(row); + } + + await _uow.SaveChangesAsync(CancellationToken.None); + } + + private async Task TryClaim(string key, CancellationToken ct) + { + var expired = await _uow.IdempotencyKeys + .FirstOrDefaultAsync(k => k.Key == key && k.ExpiresAt < DateTime.UtcNow, ct); + if (expired is not null) + { + _uow.IdempotencyKeys.Remove(expired); + await _uow.SaveChangesAsync(ct); + } + + _uow.IdempotencyKeys.Add(new IdempotencyKey + { + Key = key, + ResponseStatus = InProgress, + ExpiresAt = DateTime.UtcNow.AddHours(24), + CreatedAt = DateTime.UtcNow + }); + + try + { + await _uow.SaveChangesAsync(ct); + return true; + } + catch (DbUpdateException ex) when (OptimisticConcurrencyHelper.IsUniqueConstraintViolation(ex)) { - var responseBody = JsonSerializer.Serialize(objectResult.Value); - var responseStatus = objectResult.StatusCode ?? 201; - - _uow.IdempotencyKeys.Add(new IdempotencyKey - { - Key = idempotencyKey, - ResponseBody = responseBody, - ResponseStatus = responseStatus, - ExpiresAt = DateTime.UtcNow.AddHours(24), - CreatedAt = DateTime.UtcNow - }); - - await _uow.SaveChangesAsync(context.HttpContext.RequestAborted); + _uow.DiscardChanges(); + return false; } } + + private static string Scope(string method, string path, string clientKey) + { + var bytes = SHA256.HashData(Encoding.UTF8.GetBytes($"{method}:{path}:{clientKey}")); + return Convert.ToHexString(bytes); + } } diff --git a/backend-csharp/Infrastructure/Notifications/OrderBookChangedNotificationHandler.cs b/backend-csharp/Infrastructure/Notifications/OrderBookChangedNotificationHandler.cs index b3ab371..7e0cbfa 100644 --- a/backend-csharp/Infrastructure/Notifications/OrderBookChangedNotificationHandler.cs +++ b/backend-csharp/Infrastructure/Notifications/OrderBookChangedNotificationHandler.cs @@ -34,7 +34,7 @@ public async Task Handle( OrderBookChangedNotification notification, CancellationToken cancellationToken) { - var snapshot = _orderBookService.GetSnapshot(); + var snapshot = _orderBookService.GetSnapshot(notification.Symbol); await _hubContext.Clients.All.SendAsync( "OrderBookSnapshot", snapshot, cancellationToken); diff --git a/backend-csharp/Infrastructure/OrderBook/OrderBookRecoveryService.cs b/backend-csharp/Infrastructure/OrderBook/OrderBookRecoveryService.cs index ea712e9..f3736b1 100644 --- a/backend-csharp/Infrastructure/OrderBook/OrderBookRecoveryService.cs +++ b/backend-csharp/Infrastructure/OrderBook/OrderBookRecoveryService.cs @@ -35,13 +35,16 @@ public class OrderBookRecoveryService : IHostedService { private readonly IServiceScopeFactory _scopeFactory; private readonly IOrderBookService _orderBookService; + private readonly ILogger _logger; public OrderBookRecoveryService( IServiceScopeFactory scopeFactory, - IOrderBookService orderBookService) + IOrderBookService orderBookService, + ILogger logger) { _scopeFactory = scopeFactory; _orderBookService = orderBookService; + _logger = logger; } public async Task StartAsync(CancellationToken cancellationToken) @@ -50,14 +53,17 @@ public async Task StartAsync(CancellationToken cancellationToken) var uow = scope.ServiceProvider.GetRequiredService(); var orders = await uow.Orders + .AsNoTracking() .Where(o => o.Status == "Pending" || o.Status == "PartiallyFilled") + .OrderBy(o => o.CreatedAt) .ToListAsync(cancellationToken); + using var _ = await _orderBookService.AcquireAsync(cancellationToken); foreach (var order in orders) - _orderBookService.AddOrder(order); + _orderBookService.Load(order); - Console.WriteLine( - $"[OrderBookRecovery] Reloaded {orders.Count} orders into order book."); + _logger.LogInformation( + "Order book recovery: reloaded {Count} open orders", orders.Count); } public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; diff --git a/backend-csharp/Infrastructure/OrderBook/OrderBookService.cs b/backend-csharp/Infrastructure/OrderBook/OrderBookService.cs index d7e6a2e..6f4516f 100644 --- a/backend-csharp/Infrastructure/OrderBook/OrderBookService.cs +++ b/backend-csharp/Infrastructure/OrderBook/OrderBookService.cs @@ -1,90 +1,97 @@ -// ============================================================================ -// Copyright (c) NexusEngine Enterprise. All rights reserved. -// Product: NexusEngine.Api -// Layer: Infrastructure.OrderBook -// -// FILE DESCRIPTION: -// Concrete implementation of IOrderBookService backed by the pure domain -// matching engine. Follows the same adapter pattern as NexusUnitOfWork -- -// bridges an Application abstraction with a domain implementation. -// -// CLASS DOCUMENTATION: -// - OrderBookService: Singleton service wrapping a single Domain.OrderBook -// instance configured for the "BTC/USD" trading pair. All methods delegate -// directly to the inner OrderBook without additional logic. Thread-safe -// via instance-level locking. -// -// MEMBER DOCUMENTATION: -// - _orderBook: The underlying domain matching engine instance. -// - _lock: Synchronization guard for singleton thread safety. -// - Match(): Delegates to Domain.OrderBook.Match(), returning all trades. -// - AddOrder(): Delegates to Domain.OrderBook.Match() to place an order. -// - RemoveOrder(): Thread-safe removal of a resting order from the book. -// - GetSnapshot(): Thread-safe snapshot of the current order book state. -// ============================================================================ +// In-memory, per-symbol matching engine. A SemaphoreSlim serializes writers for the +// whole duration of a command (match + persist); an inner lock protects reads +// (snapshots) that may run concurrently from notification handlers. namespace NexusEngine.Infrastructure.OrderBook; using NexusEngine.Api.Domain.Entities; using NexusEngine.Application.Abstractions; using NexusEngine.Domain.OrderBook; +using Book = NexusEngine.Domain.OrderBook.OrderBook; public class OrderBookService : IOrderBookService { - private readonly NexusEngine.Domain.OrderBook.OrderBook _orderBook; + private readonly Dictionary _books = new(StringComparer.OrdinalIgnoreCase); + private readonly SemaphoreSlim _writer = new(1, 1); private readonly object _lock = new(); - public OrderBookService() + public async Task AcquireAsync(CancellationToken cancellationToken = default) { - _orderBook = new NexusEngine.Domain.OrderBook.OrderBook("BTC/USD"); + await _writer.WaitAsync(cancellationToken); + return new Releaser(_writer); } public MatchResult Match(Order order) { - return _orderBook.Match(order); + lock (_lock) + return GetOrCreate(order.Symbol).Match(order); } - public void AddOrder(Order order) + public void Load(Order order) { - _orderBook.Match(order); + lock (_lock) + GetOrCreate(order.Symbol).Add(order); } - public void RemoveOrder(Order order) + public bool RemoveOrder(Order order) + { + lock (_lock) + return _books.TryGetValue(order.Symbol, out var book) && book.TryRemoveOrder(order); + } + + public IOrderBookCheckpoint Checkpoint(string symbol) + { + lock (_lock) + return new BookCheckpoint(symbol, GetOrCreate(symbol).Clone()); + } + + public void Restore(IOrderBookCheckpoint checkpoint) + { + var cp = (BookCheckpoint)checkpoint; + lock (_lock) + _books[cp.Symbol] = cp.Book; + } + + public object GetSnapshot(string symbol) { lock (_lock) { - _orderBook.RemoveOrder(order); + _books.TryGetValue(symbol, out var book); + + var bids = book?.Bids + .Select(b => new { Price = b.Key, Quantity = b.Value.Sum(o => o.RemainingQuantity) }) + .Where(l => l.Quantity > 0) + .ToList() ?? []; + + var asks = book?.Asks + .Select(a => new { Price = a.Key, Quantity = a.Value.Sum(o => o.RemainingQuantity) }) + .Where(l => l.Quantity > 0) + .ToList() ?? []; + + return new { Symbol = symbol, Bids = bids, Asks = asks }; } } - public object GetSnapshot() + private Book GetOrCreate(string symbol) { - lock (_lock) + if (!_books.TryGetValue(symbol, out var book)) + { + book = new Book(symbol); + _books[symbol] = book; + } + return book; + } + + private sealed record BookCheckpoint(string Symbol, Book Book) : IOrderBookCheckpoint; + + private sealed class Releaser(SemaphoreSlim semaphore) : IDisposable + { + private int _disposed; + + public void Dispose() { - var bids = _orderBook.Bids - .Where(b =>b.Value.Sum(o => o.RemainingQuantity) > 0) - .Select(b => new - { - Price = b.Key, - Quantity = b.Value.Sum(o => o.RemainingQuantity) - }) - .ToList(); - - var asks = _orderBook.Asks - .Where(b =>b.Value.Sum(o => o.RemainingQuantity) > 0) - .Select(a => new - { - Price = a.Key, - Quantity = a.Value.Sum(o => o.RemainingQuantity) - }) - .ToList(); - - return new - { - Symbol = _orderBook.Symbol, - Bids = bids, - Asks = asks - }; + if (Interlocked.Exchange(ref _disposed, 1) == 0) + semaphore.Release(); } } } diff --git a/backend-csharp/Infrastructure/Persistence/NexusUnitOfWork.cs b/backend-csharp/Infrastructure/Persistence/NexusUnitOfWork.cs index 4529398..1c48fb0 100644 --- a/backend-csharp/Infrastructure/Persistence/NexusUnitOfWork.cs +++ b/backend-csharp/Infrastructure/Persistence/NexusUnitOfWork.cs @@ -37,6 +37,8 @@ public NexusUnitOfWork(NexusDbContext db) public DbSet DomainEvents => _db.DomainEvents; public DbSet IdempotencyKeys => _db.IdempotencyKeys; + public void DiscardChanges() => _db.ChangeTracker.Clear(); + public Task SaveChangesAsync(CancellationToken cancellationToken = default) => _db.SaveChangesAsync(cancellationToken); } \ No newline at end of file From b22a6160092d5fedc9d15cdeba9152e10ae169f3 Mon Sep 17 00:00:00 2001 From: M-Grimaldi-Neuram Date: Wed, 25 Nov 2026 12:15:04 +0100 Subject: [PATCH 2/2] chore: deploy backend on Railway via Railpack (no Dockerfile), support DATABASE_URL, refresh AGENTS.md Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 37 ++++++++++++++++++++++--------------- backend-csharp/Program.cs | 21 ++++++++++++++++++++- railway.toml | 21 +++++++++++++++------ 3 files changed, 57 insertions(+), 22 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index cc4a192..6320b8f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,7 @@ # Nexus Engine — Agent Guide ## Active branch -`phase-2` is HEAD. `main` is stable. Work on `phase-2`. +`main` is the integration branch (phases 1-5 merged). Work on feature branches off `main`. ## Architecture in 10 lines @@ -9,6 +9,9 @@ - **CQRS**: MediatR commands/queries in `Application/`, thin controllers in `Controllers/`. - **Clean Architecture**: `Domain/` (pure C#) → `Application/` (depends on `INexusUnitOfWork` only) → `Infrastructure/` (EF Core, migrations). - **Optimistic Locking**: Unique index `(aggregate_id, aggregate_version)` on `domain_events`. Postgres error `23505` = concurrent write detected. +- **Matching engine**: in-memory, one `OrderBook` per symbol (`OrderBookService` singleton). Writers hold `AcquireAsync()` for match + persist; the book is checkpointed and restored if `SaveChanges` fails. Recovery reloads open orders with `Load` (no matching). Single instance only. +- **Ledger**: every balance-affecting event is written through `AccountLedger.Append` and carries `BalanceDelta`/`ReservedDelta`, so `/replay` rebuilds the projection exactly. Makers get their own events. +- **Real-time**: MediatR notifications -> SignalR hub `/hubs/nexus`. ## Docker Compose ```bash @@ -20,6 +23,10 @@ make db-shell # psql -U nexus -d nexusdb Port `5000:8080`. Frontend on `3000`. +## Production (Railway, no Docker) + +`railway.toml` builds with Railpack (`dotnet publish`). Dashboard: Root Directory `backend-csharp`, Postgres plugin (`DATABASE_URL` is auto-converted), App Sleeping off, 1 replica. + ### Generate a migration ```bash cd backend-csharp @@ -38,7 +45,7 @@ dotnet build dotnet run # http://localhost:5140, swagger at /swagger ``` -No test project exists for C# backend. +Tests: `dotnet test backend-csharp.Tests/NexusEngine.Tests.csproj` (xUnit, Moq, EF InMemory). CI runs them on push/PR to `main`. ## Database @@ -56,7 +63,10 @@ No test project exists for C# backend. | GET | `/api/accounts/{id}` | Get account projection | | POST | `/api/accounts/{id}/deposit` | Deposit funds | | GET | `/api/accounts/{id}/replay` | Reconstruct state from events | -| POST | `/api/orders` | Place order (reserves funds) | +| POST | `/api/orders` | Place order (reserves funds, matches) | +| GET | `/api/orders?accountId=` | List orders | +| DELETE | `/api/orders/{id}?accountId=` | Cancel order | +| GET | `/health/live`, `/health/ready` | Health checks | ## Key domain entities @@ -66,16 +76,16 @@ No test project exists for C# backend. | `Account` | `accounts` | Read-side projection (balance, reserved_balance, status) | | `Order` | `orders` | Read-side projection (side, price, qty, status) | | `Transaction` | `transactions` | Ledger row linking account/order/event | -| `IdempotencyKey` | `idempotency_keys` | Duplicate request protection (table exists, not fully wired) | +| `IdempotencyKey` | `idempotency_keys` | `X-Idempotency-Key` on `POST /api/orders`; claimed atomically, scoped to method+path | ## Frontend -Vite 8 scaffold with placeholder Vite/React demo content. **Not customized for Nexus Engine**. Build: +Vite + React dashboard (`src/components/NexusDashboard.tsx`, SignalR via `src/hooks/useNexusHub.ts`). Deployed on Vercel. ```bash cd frontend -npm run dev # local dev -npm run build # tsc -b && vite build -npm run lint # eslint . +npm run dev +npm run build +npm run lint ``` ## Conventions @@ -87,11 +97,8 @@ npm run lint # eslint . - Controllers do **zero business logic** — parse request → build command/query → dispatch via `IMediator`. - `INexusUnitOfWork` is the only persistence abstraction the Application layer sees. -## What doesn't exist yet +## Known gaps -- Frontend: not customized — still showing Vite/React demo. -- Order book / matching engine (Phase 3). -- Real-time: SignalR (Phase 4). -- Observability: structured logging, health checks, metrics (Phase 5). -- CI/CD: no GitHub Actions workflows. -- Tests: C# backend has no test project. +- No asset positions: sells don't require holdings and buyers don't receive the asset. +- Legacy `OrderMatched` events (written before deltas) are skipped by replay (`LegacyEventsSkipped`). +- Matching engine is in-process: run exactly one backend instance. diff --git a/backend-csharp/Program.cs b/backend-csharp/Program.cs index ac7440a..a07f85f 100644 --- a/backend-csharp/Program.cs +++ b/backend-csharp/Program.cs @@ -76,6 +76,7 @@ // immediatamente con un messaggio chiaro invece di crashare piu' tardi // con un errore criptico di connessione. var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") + ?? FromDatabaseUrl(Environment.GetEnvironmentVariable("DATABASE_URL")) ?? throw new InvalidOperationException( "Connection string 'DefaultConnection' not configured. " + "Set the environment variable 'ConnectionStrings__DefaultConnection'."); @@ -163,4 +164,22 @@ ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse }); -app.Run(); \ No newline at end of file +app.Run(); + +// Railway/Heroku style postgres://user:pass@host:port/db -> Npgsql key/value string. +static string? FromDatabaseUrl(string? url) +{ + if (string.IsNullOrWhiteSpace(url) || !Uri.TryCreate(url, UriKind.Absolute, out var uri)) + return null; + + var userInfo = uri.UserInfo.Split(':', 2); + return new Npgsql.NpgsqlConnectionStringBuilder + { + Host = uri.Host, + Port = uri.Port > 0 ? uri.Port : 5432, + Database = uri.AbsolutePath.TrimStart('/'), + Username = Uri.UnescapeDataString(userInfo[0]), + Password = userInfo.Length > 1 ? Uri.UnescapeDataString(userInfo[1]) : null, + SslMode = Npgsql.SslMode.Prefer + }.ConnectionString; +} \ No newline at end of file diff --git a/railway.toml b/railway.toml index a6292c1..2f57bea 100644 --- a/railway.toml +++ b/railway.toml @@ -1,9 +1,18 @@ +# Railway: native .NET build via Railpack (no Dockerfile). +# Service settings required in the Railway dashboard: +# - Root Directory: backend-csharp +# - Config file path: /railway.toml +# - Variable ConnectionStrings__DefaultConnection -> Railway Postgres +# - Serverless / App Sleeping: OFF (keeps the engine and its in-memory book always up) + [build] -dockerfilePath = "backend-csharp/Dockerfile" -buildCommand = "" +builder = "RAILPACK" +buildCommand = "dotnet publish NexusEngine.Api.csproj -c Release -o out" +watchPatterns = ["backend-csharp/**"] [deploy] -healthcheckPath = "/health/live" -healthcheckTimeout = 30 -restartPolicyType = "on_failure" -restartPolicyMaxRetries = 3 +startCommand = "dotnet out/NexusEngine.Api.dll" +healthcheckPath = "/health/ready" +healthcheckTimeout = 60 +restartPolicyType = "always" +numReplicas = 1