using System.Text.Json;using System.Text.RegularExpressions;using Generated;using Generated.Models;using TeaQL.Core;using TeaQL.Sql;using TeaQL.Provider.Sqlite;using Microsoft.Data.Sqlite; const string Seed="Seed stock reservation fixture",Reserve="Reserve Order inventory atomically"; static string[]? Session(string token)=>token switch{"a"=>["ACTOR-A","TENANT-A","BUYER-A"],"b"=>["ACTOR-B","TENANT-A","BUYER-B"],"c"=>["ACTOR-C","TENANT-B","BUYER-A"],_=>null}; static bool Has(JsonElement r,string k)=>r.TryGetProperty(k,out _); static void Validate(string token,JsonElement r){if(Session(token)==null)throw new Denied("UNAUTHENTICATED");if(new[]{"tenant","buyer","actor","permissions","policy","userContext"}.Any(k=>Has(r,k)))throw new Denied("FORGED_SCOPE");if(r.EnumerateObject().Select(p=>p.Name).Order().SequenceEqual(new[]{"orderNumber","quantity","requestKey","sku"})==false||r.GetProperty("quantity").ValueKind!=JsonValueKind.Number||!r.GetProperty("quantity").TryGetInt64(out long q)||q<1||q>10||r.GetProperty("requestKey").ValueKind!=JsonValueKind.String||!Regex.IsMatch(r.GetProperty("requestKey").GetString()!,"\\A[A-Z0-9-]{1,64}\\z"))throw new Denied("INVALID_REQUEST");foreach(string key in new[]{"orderNumber","sku"})if(r.GetProperty(key).ValueKind!=JsonValueKind.String||r.GetProperty(key).GetString()!.Length is <1 or >64)throw new Denied("INVALID_REQUEST");} static bool Conflict(Exception error){string t=error.ToString().ToLowerInvariant();return !new[]{"busy","locked","timeout"}.Any(t.Contains)&&new[]{"version","optimistic","conflict","stale","authoritative persisted state"}.Any(t.Contains);} static Dictionary Result(string code,long? receipt,int attempts,List reasons)=>new(){["code"]=code,["receiptId"]=receipt,["attempts"]=attempts,["conflicts"]=reasons.Count,["conflictReasons"]=reasons.ToArray()}; static async Task Barrier(object ready){string? folder=Environment.GetEnvironmentVariable("ORDER_BARRIER");if(folder==null)return;string worker=Environment.GetEnvironmentVariable("ORDER_WORKER")!,temp=Path.Combine(folder,worker+".tmp");File.WriteAllText(temp,JsonSerializer.Serialize(ready));File.Move(temp,Path.Combine(folder,worker+".ready"));var end=DateTime.UtcNow.AddSeconds(45);while(!File.Exists(Path.Combine(folder,"release"))){if(DateTime.UtcNow>end)throw new Exception("Barrier timeout");await Task.Delay(10);}} static async Task Handle(UserContext context,string token,JsonElement r){int attempts=0;var reasons=new List();try{ Validate(token,r);var session=Session(token)!;string tenant=session[1],buyer=session[2],key=r.GetProperty("requestKey").GetString()!,number=r.GetProperty("orderNumber").GetString()!,sku=r.GetProperty("sku").GetString()!;long qty=r.GetProperty("quantity").GetInt64(); for(int attempt=0;attempt<3;attempt++){ attempts++;var roots=await Q.CommercePlatforms().WithTenantKeyIs(tenant) .SelectCustomerOrderListWith(Q.CustomerOrders().WithBuyerReferenceIs(buyer).WithOrderNumberIs(number).Limit(2)) .SelectInventoryListWith(Q.Inventory().WithSkuCodeIs(sku).Limit(2)) .SelectStockReservationListWith(Q.StockReservations().WithBuyerReferenceIs(buyer).WithRequestKeyIs(key).Limit(2)) .Limit(2).Comment("Load trusted tenant reservation aggregate").Purpose("Bind Order inventory and receipt to server session").ExecuteForListAsync(context); if(roots.Count!=1)throw new Exception("Invalid trusted root");var root=roots[0];var receipts=root.StockReservationList;if(receipts.Count>1)throw new Exception("Duplicate persisted request key"); if(receipts.Count==1){var e=E.StockReservation(receipts[0]);bool same=e.OrderNumber().Eval()==number&&e.SkuCode().Eval()==sku&&e.Quantity().Eval()==qty;return Result(same?"REPLAY":"IDEMPOTENCY_CONFLICT",same?e.Id().Eval():null,attempts,reasons);} var orders=root.CustomerOrderList;var stocks=root.InventoryList;if(orders.Count!=1||stocks.Count!=1)throw new Denied("NOT_FOUND");var order=orders[0];var stock=stocks[0];var oe=E.CustomerOrder(order);var se=E.Inventory(stock); if(oe.OrderStatusId().Eval()!=1001)throw new Denied("ORDER_NOT_DRAFT");var items=await Q.OrderItems().FilterByCustomerOrder(oe.Id().Eval()!.Value).Limit(2).Comment("Validate complete bounded Order items").Purpose("Reject mismatched reservation quantity or SKU").ExecuteForListAsync(context); if(items.Count!=1||E.OrderItem(items[0]).SkuCode().Eval()!=sku||E.OrderItem(items[0]).Quantity().Eval()!=qty)throw new Denied("INVALID_ORDER_ITEMS");long available=se.AvailableQuantity().Eval()!.Value,reserved=se.ReservedQuantity().Eval()!.Value;if(available<0||reserved<0)throw new Exception("Invalid inventory");if(available