97 lines
7.8 KiB
C#
97 lines
7.8 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Reflection;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using ConfigModalCanary.Components;
|
|
using ZB.MOM.WW.OtOpcUa.AdminUI.Acls;
|
|
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;
|
|
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
|
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
|
var builder=WebApplication.CreateBuilder(args);builder.WebHost.UseStaticWebAssets();
|
|
builder.Services.AddRazorComponents().AddInteractiveServerComponents().AddCircuitOptions(o=>o.DisconnectedCircuitRetentionPeriod=TimeSpan.Zero);
|
|
builder.Services.AddSingleton<FixtureRegistry>();builder.Services.AddScoped<FixtureSession>();
|
|
builder.Services.AddDbContextFactory<OtOpcUaConfigDbContext>(o=>o.UseInMemoryDatabase("ui-config-"+FixtureRegistry.DatabaseId));
|
|
builder.Services.AddScoped<RawTagCsvExportReader>();
|
|
builder.Services.AddScoped<IRawTreeService>(s=>{var p=DispatchProxy.Create<IRawTreeService,SyntheticRaw>();((SyntheticRaw)(object)p).Session=s.GetRequiredService<FixtureSession>();return p;});
|
|
builder.Services.AddScoped<IAclScopeService>(s=>{var p=DispatchProxy.Create<IAclScopeService,SyntheticScopes>();((SyntheticScopes)(object)p).Session=s.GetRequiredService<FixtureSession>();return p;});
|
|
builder.Services.AddScoped<IAdminOperationsClient>(s=>{var p=DispatchProxy.Create<IAdminOperationsClient,RefuseOperational>();((RefuseOperational)(object)p).Session=s.GetRequiredService<FixtureSession>();return p;});
|
|
builder.Services.AddScoped<AdminProbeService>();
|
|
var app=builder.Build();app.UseAntiforgery();app.MapStaticAssets();
|
|
using(var scope=app.Services.CreateScope())
|
|
{
|
|
using var db=scope.ServiceProvider.GetRequiredService<IDbContextFactory<OtOpcUaConfigDbContext>>().CreateDbContext();
|
|
FixtureRegistry.Provider=db.Database.ProviderName??"unknown";
|
|
db.ServerClusters.Add(new(){ClusterId="C1",Name="Synthetic cluster",Enterprise="fixture",Site="loopback",RedundancyMode=RedundancyMode.None,CreatedBy="fixture"});
|
|
db.DriverInstances.Add(new(){DriverInstanceId="CSV-DRV",ClusterId="C1",Name="fixture-driver",DriverType="Modbus",DriverConfig="{}"});
|
|
foreach(var id in new[]{"CSV-A","CSV-B"})
|
|
{
|
|
db.Devices.Add(new(){DeviceId=id,DriverInstanceId="CSV-DRV",Name=id,DeviceConfig="{}"});
|
|
for(var i=0;i<(id=="CSV-A"?127:3);i++)db.Tags.Add(new(){TagId=id+"-"+i,DeviceId=id,Name="fixture-tag-"+i,DataType="Int16",AccessLevel=TagAccessLevel.Read,TagConfig="{\"region\":\"HoldingRegisters\",\"address\":"+i+",\"marker\":\""+id+"\"}"});
|
|
}
|
|
db.SaveChanges();
|
|
}
|
|
app.MapGet("/fixture/provenance",()=>new{purpose="Loopback synthetic configuration modal fixture",backend="EF InMemory CSV seed only; fake component reads and mutation results; all operational/probe clients refuse",provider=FixtureRegistry.Provider,productionDownloadAuthorization="Not exercised here; existing endpoint metadata tests retained"});
|
|
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(),picked=s.Picked.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" or "exception")||!registry.Sessions.TryGetValue(id,out var s)||s.Pending is null)return Results.BadRequest();
|
|
if(outcome=="exception")s.Pending.TrySetException(new InvalidOperationException("Synthetic old target exception"));else s.Pending.TrySetResult(new(outcome=="success",outcome=="failure"?"Synthetic old target failure":null));return Results.Ok();
|
|
});
|
|
app.MapGet("/api/raw/tags.csv",async(string deviceId,string driverType,RawTagCsvExportReader reader)=>
|
|
{
|
|
if(deviceId is not("CSV-A" or "CSV-B")||driverType!="Modbus")return Results.BadRequest();
|
|
var csv=await RawTagCsvExport.BuildAsync(reader,deviceId,null,driverType);return csv is null?Results.NotFound():Results.File(System.Text.Encoding.UTF8.GetBytes(csv.Csv),"text/csv",csv.FileName);
|
|
});
|
|
app.MapRazorComponents<App>().AddInteractiveServerRenderMode();app.Run();
|
|
public sealed class FixtureRegistry {public static string Provider="unknown";public static readonly string DatabaseId=Guid.NewGuid().ToString("N");public ConcurrentDictionary<Guid,FixtureSession> Sessions=new();}
|
|
public sealed class FixtureSession
|
|
{
|
|
public readonly Guid Id=Guid.NewGuid();public string Target="A";public Func<Task>? Changed;
|
|
public readonly ConcurrentQueue<Mutation> Operations=new();public readonly ConcurrentQueue<string> Saved=new(),Closed=new(),Picked=new();
|
|
public int Forbidden;public TaskCompletionSource<UnsMutationResult>? Pending;
|
|
public Task<UnsMutationResult> Dispatch(Mutation operation){Operations.Enqueue(operation);Pending=new(TaskCreationOptions.RunContinuationsAsynchronously);return Pending.Task;}
|
|
}
|
|
public sealed record Mutation(string Method,string Target,string Name,string Json,bool? Enabled,string? Resilience,byte[] Version);
|
|
public class SyntheticRaw:DispatchProxy
|
|
{
|
|
public FixtureSession Session=null!;
|
|
protected override object? Invoke(MethodInfo? method,object?[]? args)
|
|
{
|
|
var id=(string)args![0]!;var name=id=="A"?"alpha":"beta";var marker="\"marker\":\""+id+"\"";
|
|
switch(method?.Name)
|
|
{
|
|
case "LoadDeviceForEditAsync":return Task.FromResult<RawDeviceEditDto?>(new(id,"PARENT-"+id,name,"{\"Host\":\"127.0.0.1\",\"Port\":502,\"UnitId\":1,"+marker+"}",true,"Modbus",[1,2]));
|
|
case "LoadDriverForEditAsync":return Task.FromResult<RawDriverEditDto?>(new(id,name,"Modbus","{"+marker+"}",null,[1,2]));
|
|
case "LoadTagForEditAsync":return Task.FromResult<RawTagEditDto?>(new(id,"device-"+id,null,name,"Float",TagAccessLevel.Read,false,null,"{"+marker+"}",[1,2]));
|
|
case "LoadMergedProbeConfigAsync":return Task.FromResult<(string DriverType,string MergedConfigJson)?>(("Modbus","{\"Host\":\"127.0.0.1\",\"Port\":502,"+marker+"}"));
|
|
case "UpdateDeviceAsync":return Session.Dispatch(new(method.Name,id,(string)args[1]!, (string)args[2]!, (bool)args[3]!,null,((byte[])args[4]!).ToArray()));
|
|
case "UpdateDriverAsync":return Session.Dispatch(new(method.Name,id,(string)args[1]!, (string)args[2]!,null,(string?)args[3],((byte[])args[4]!).ToArray()));
|
|
case "UpdateTagAsync":var tag=(RawTagInput)args[1]!;return Session.Dispatch(new(method.Name,id,tag.Name,tag.TagConfig,null,null,((byte[])args[2]!).ToArray()));
|
|
default:Interlocked.Increment(ref Session.Forbidden);throw new InvalidOperationException("Operational request refused: "+method?.Name);
|
|
}
|
|
}
|
|
}
|
|
public class SyntheticScopes:DispatchProxy
|
|
{
|
|
public FixtureSession Session=null!;
|
|
protected override object? Invoke(MethodInfo? method,object?[]? args)
|
|
{
|
|
if(method?.Name=="LoadRootsAsync")return Task.FromResult(new AclScopeRoots([Node((string)args![0]!)],[]));
|
|
if(method?.Name=="LoadChildrenAsync")return Task.FromResult<IReadOnlyList<AclScopeNode>>([Node("child-"+((AclScopeNode)args![0]!).Key)]);
|
|
Interlocked.Increment(ref Session.Forbidden);throw new InvalidOperationException("Scope operation refused");
|
|
}
|
|
private static AclScopeNode Node(string id)=>new(){Key="scope-"+id,DisplayName="Synthetic scope "+id,Icon="C",ScopeKind=NodeAclScopeKind.Cluster,PathLabel="Synthetic scope "+id,HasLazyChildren=true};
|
|
}
|
|
public class RefuseOperational:DispatchProxy
|
|
{
|
|
public FixtureSession Session=null!;
|
|
protected override object? Invoke(MethodInfo? method,object?[]? args){Interlocked.Increment(ref Session.Forbidden);throw new InvalidOperationException("No operational/probe access in UI fixture");}
|
|
}
|