using System.Collections.Concurrent; using System.Reflection; using System.Security.Claims; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.EntityFrameworkCore; using ConfigModalCanary.Components; using ZB.MOM.WW.OtOpcUa.AdminUI.Browsing; using ZB.MOM.WW.OtOpcUa.AdminUI.Clients; using ZB.MOM.WW.OtOpcUa.AdminUI.Uns; using ZB.MOM.WW.OtOpcUa.Commons.Interfaces; using ZB.MOM.WW.OtOpcUa.Configuration; var builder=WebApplication.CreateBuilder(args);builder.WebHost.UseStaticWebAssets(); builder.Services.AddRazorComponents().AddInteractiveServerComponents().AddCircuitOptions(o=>o.DisconnectedCircuitRetentionPeriod=TimeSpan.Zero); builder.Services.AddSingleton();builder.Services.AddScoped(); builder.Services.AddDbContextFactory(o=>o.UseInMemoryDatabase("uns-fixture-only")); builder.Services.AddScoped();builder.Services.AddScoped(); builder.Services.AddAuthorizationCore(o=>o.AddPolicy("DriverOperator",p=>p.RequireAuthenticatedUser()));builder.Services.AddScoped(); builder.Services.AddScoped(s=>{var p=DispatchProxy.Create();((SyntheticUns)(object)p).Session=s.GetRequiredService();return p;}); builder.Services.AddScoped(_=>DispatchProxy.Create()); builder.Services.AddScoped(_=>DispatchProxy.Create()); builder.Services.AddScoped(_=>DispatchProxy.Create()); var app=builder.Build();app.UseAntiforgery();app.MapStaticAssets(); app.MapGet("/fixture/provenance",()=>new{purpose="Loopback synthetic UNS wrapper fixture",backend="Fake reads, deferred fake mutation results; all fleet/provider/database operations refused"}); app.MapGet("/fixture/state/{id:guid}",(Guid id,FixtureRegistry registry)=>registry.Sessions.TryGetValue(id,out var s)?Results.Ok(new{target=s.Target,operations=s.Operations.ToArray(),saved=s.Saved.ToArray(),closed=s.Closed.ToArray(),forbidden=s.Forbidden}):Results.NotFound()); app.MapPost("/fixture/target/{id:guid}/{target}",async(Guid id,string target,FixtureRegistry registry)=>{if(target is not("A" or "B")||!registry.Sessions.TryGetValue(id,out var s))return Results.BadRequest();s.Target=target;if(s.Changed is not null)await s.Changed();return Results.Ok();}); app.MapPost("/fixture/release/{id:guid}/{outcome}",(Guid id,string outcome,FixtureRegistry registry)=>{if(outcome is not("success" or "failure")||!registry.Sessions.TryGetValue(id,out var s)||s.Release is null)return Results.BadRequest();s.Release(outcome=="success");return Results.Ok();}); app.MapPost("/api/script-analysis/diagnostics",()=>Results.Ok(new{markers=Array.Empty()})); app.MapPost("/api/script-analysis/{operation}",()=>Results.Ok(new{items=Array.Empty()})); app.MapRazorComponents().AddInteractiveServerRenderMode();app.Run(); public sealed class AnonymousAuth:AuthenticationStateProvider{public override Task GetAuthenticationStateAsync()=>Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())));} public sealed class FixtureRegistry{public ConcurrentDictionary Sessions=new();} public sealed class FixtureSession { public readonly Guid Id=Guid.NewGuid();public string Target="A";public Func? Changed;public Action? Release; public readonly ConcurrentQueue Operations=new();public readonly ConcurrentQueue Saved=new(),Closed=new();public int Forbidden; public Task Mutation(string name,object?[] args){Operations.Enqueue(new{method=name,args=args.Where(x=>x is not CancellationToken).ToArray()});var t=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);Release=ok=>t.TrySetResult(new(ok,ok?null:"Synthetic current failure","NEW-SCRIPT"));return t.Task;} public Task Import(object rows){Operations.Enqueue(new{method="ImportEquipmentAsync",rows});var t=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);Release=ok=>t.TrySetResult(new(ok?1:0,0,ok?[]:["Synthetic import failure"]));return t.Task;} public Task<(bool Ok,string? Error)> Script(object?[] args){Operations.Enqueue(new{method="UpdateScriptSourceAsync",args=args.Where(x=>x is not CancellationToken).ToArray()});var t=new TaskCompletionSource<(bool,string?)>(TaskCreationOptions.RunContinuationsAsynchronously);Release=ok=>t.TrySetResult((ok,ok?null:"Synthetic script failure"));return t.Task;} } public class SyntheticUns:DispatchProxy { public FixtureSession Session=null!; protected override object? Invoke(MethodInfo? method,object?[]? args) { switch(method?.Name) { case "LoadReferencePickerRootAsync":var id=(string)args![0]!;var root=new RawNode{Kind=RawNodeKind.Cluster,Key="cluster-"+id,EntityId=id,ClusterId=id,DisplayName="Synthetic cluster "+id,Expanded=true,Loaded=true};root.Children.Add(new(){Kind=RawNodeKind.Tag,Key="tag-"+id,EntityId="tag-"+id,ClusterId=id,DisplayName="Synthetic raw tag "+id});return Task.FromResult(root); case "LoadDescendantTagIdsAsync":return Task.FromResult>(["tag-"+Session.Target]); case "GetScriptSourceAsync":var script=(string)args![0]!;return Task.FromResult<(string SourceCode,byte[] RowVersion,string Name)?>(("// synthetic "+script+"\nreturn 1.0;",new byte[]{1,2},"Synthetic "+script)); case "CountVirtualTagsUsingScriptAsync":return Task.FromResult(2); case "CreateScriptAsync":case "CreateVirtualTagAsync":case "UpdateVirtualTagAsync":case "CreateScriptedAlarmAsync":case "UpdateScriptedAlarmAsync":case "AddReferencesAsync":return Session.Mutation(method.Name,args!); case "ImportEquipmentAsync":return Session.Import(args![0]!); case "UpdateScriptSourceAsync":return Session.Script(args!); default:Interlocked.Increment(ref Session.Forbidden);throw new InvalidOperationException("Refused UNS operation: "+method?.Name); } } } public class RefuseOperational:DispatchProxy{protected override object? Invoke(MethodInfo? method,object?[]? args)=>throw new InvalidOperationException("No operational access in UI fixture: "+method?.Name);}