using Microsoft.Extensions.Caching.Hybrid; public sealed record CatalogView(string Name,long Version); public sealed record CatalogInput(string Name); public sealed record SharedView(string Value,int Generation); public sealed class CacheProbe { private int reads,factories; private readonly object sync=new(); private TaskCompletionSource gate=Ready(); private static TaskCompletionSource Ready() { var value=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); value.SetResult(true); return value; } public int Reads=>Volatile.Read(ref reads); public int Factories=>Volatile.Read(ref factories); public void Read()=>Interlocked.Increment(ref reads); public void Close() { lock(sync) if(gate.Task.IsCompleted) gate=new(TaskCreationOptions.RunContinuationsAsynchronously); } public void Open() { lock(sync) gate.TrySetResult(true); } public async ValueTask Create(CancellationToken token) { int generation=Interlocked.Increment(ref factories); Task wait; lock(sync) wait=gate.Task; await wait.WaitAsync(token); return new("shared",generation); } } public static class CacheLabs { public static void Map(WebApplication app) { app.MapGet("/cache/catalog",async (Store store,HybridCache cache,CacheProbe probe,CancellationToken token)=> { var value=await cache.GetOrCreateAsync("catalog:1",ct=> { ct.ThrowIfCancellationRequested(); probe.Read(); using var c=store.Open(); using var query=Store.Command(c,"SELECT name,version FROM catalog_cache WHERE id=1"); using var row=query.ExecuteReader(); row.Read(); return ValueTask.FromResult(new CatalogView(row.GetString(0),row.GetInt64(1))); },cancellationToken:token); return Results.Ok(value); }); app.MapPost("/cache/catalog",async (CatalogInput input,bool? failBeforeCommit,Store store,HybridCache cache,CancellationToken token)=> { if(string.IsNullOrWhiteSpace(input.Name)||input.Name.Length>30) return Results.BadRequest(); using(var c=store.Open()) using(var tx=c.BeginTransaction()) { Store.Execute(c,"UPDATE catalog_cache SET name=$name,version=version+1 WHERE id=1",tx,("$name",input.Name)); if(failBeforeCommit==true) { tx.Rollback(); return Results.Problem(statusCode:503,title:"Controlled cache-write rollback"); } tx.Commit(); } await cache.RemoveAsync("catalog:1",token); return Results.NoContent(); }); app.MapGet("/cache/shared",async (HybridCache cache,CacheProbe probe,CancellationToken token)=>Results.Ok(await cache.GetOrCreateAsync("stampede:demo",ct=>probe.Create(ct),cancellationToken:token))); app.MapGet("/cache/stats",(CacheProbe probe)=>new { reads=probe.Reads,factories=probe.Factories }); app.MapPost("/lab/cache/gate/{action}",(string action,CacheProbe probe)=> { if(action=="close") probe.Close(); else if(action=="open") probe.Open(); else return Results.BadRequest(); return Results.NoContent(); }); app.MapPost("/lab/cache/reset",async(HybridCache cache,CancellationToken token)=> { await cache.RemoveAsync("stampede:demo",token); return Results.NoContent(); }); } }