Files
lmxopcua/docs/ui-consistency/ot13-host-controls/canary/Program.cs
T
2026-11-14 01:40:16 -05:00

68 lines
4.8 KiB
C#

using System.Reflection;
using System.Security.Claims;
using Akka.Actor;
using Akka.Configuration;
using HostControlsCanary;
using HostControlsCanary.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.AdminUI.Hosts;
using ZB.MOM.WW.OtOpcUa.AdminUI.Hubs;
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
using ZB.MOM.WW.OtOpcUa.Configuration;
var builder=WebApplication.CreateBuilder(args);builder.WebHost.UseStaticWebAssets();
builder.Services.AddRazorComponents().AddInteractiveServerComponents();builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();
builder.Services.AddAuthorizationCore(o=>o.AddPolicy(ZB.MOM.WW.OtOpcUa.Security.Auth.AdminUiPolicies.DriverOperator,p=>p.RequireRole("Operator","Administrator")));
builder.Services.AddScoped<FixtureState>();builder.Services.AddScoped<AuthenticationStateProvider,FixturePrincipal>();
builder.Services.AddScoped<IAdminOperationsClient>(sp=>FixtureOperations.Create(sp.GetRequiredService<FixtureState>()));
builder.Services.AddDbContextFactory<OtOpcUaConfigDbContext>(o=>o.UseInMemoryDatabase("host-controls-local"));
builder.Services.AddScoped<DeployedDriverSet>();
var resilience=new InMemoryDriverResilienceStatusStore();
foreach(var id in FixtureState.DriverIds)resilience.Upsert(new(id,"synthetic-stale-target",true,2,1,DateTime.UtcNow.AddMinutes(-2),DateTime.UtcNow.AddMinutes(-2),DateTime.UtcNow.AddMinutes(-2)));
builder.Services.AddSingleton<IDriverResilienceStatusStore>(resilience);
var status=new InMemoryDriverStatusSnapshotStore();
foreach(var id in FixtureState.DriverIds)status.Upsert(new("synthetic-cluster",id,"Healthy",DateTime.UtcNow,null,0,DateTime.UtcNow));
builder.Services.AddSingleton<IDriverStatusSnapshotStore>(status);
var actors=ActorSystem.Create("host-controls-local",ConfigurationFactory.ParseString("""
akka.actor.provider = cluster
akka.remote.dot-netty.tcp.hostname = "127.0.0.1"
akka.remote.dot-netty.tcp.port = 0
akka.cluster.seed-nodes = []
akka.loglevel = ERROR
"""));builder.Services.AddSingleton(actors);
var app=builder.Build();app.Lifetime.ApplicationStopping.Register(()=>_=actors.Terminate());
using(var scope=app.Services.CreateScope())
{
using var db=scope.ServiceProvider.GetRequiredService<IDbContextFactory<OtOpcUaConfigDbContext>>().CreateDbContext();
for(var i=0;i<FixtureState.DriverIds.Length;i++)db.DriverInstances.Add(new(){DriverInstanceId=FixtureState.DriverIds[i],ClusterId="synthetic-cluster",Name="Synthetic driver "+(i+1),DriverType="Modbus",DriverConfig="{}",Enabled=true});
db.SaveChanges();
}
app.UseStaticFiles();app.UseAntiforgery();app.MapRazorComponents<App>().AddInteractiveServerRenderMode();app.Run();
namespace HostControlsCanary
{
public sealed class FixtureState
{
public static readonly string[] DriverIds=["synthetic-driver-with-a-deliberately-long-identifier-for-local-reflow-a","synthetic-driver-b"];
public string Role {get;set;}="Operator";public int Requests {get;set;}public string? LastOperation {get;set;}public event Action? Changed;public void Notify()=>Changed?.Invoke();
}
public sealed class FixturePrincipal(FixtureState state):AuthenticationStateProvider
{public override Task<AuthenticationState> GetAuthenticationStateAsync()=>Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity([new(ClaimTypes.Name,"synthetic-operator"),new(ClaimTypes.Role,state.Role)],"fixture"))));}
public class FixtureOperations:DispatchProxy
{
private FixtureState _state=null!;
public static IAdminOperationsClient Create(FixtureState state){var proxy=Create<IAdminOperationsClient,FixtureOperations>();((FixtureOperations)proxy)._state=state;return proxy;}
protected override object? Invoke(MethodInfo? method,object?[]? args)
{
if(method!.Name!="AskAsync")throw new NotSupportedException("Fixture refuses "+method.Name);
var result=method.GetGenericArguments().Single();
if(result==typeof(ReconnectDriverResult)&&args![0] is ReconnectDriver reconnect)return Reconnect(reconnect);
if(result==typeof(RestartDriverResult)&&args![0] is RestartDriver restart)return Restart(restart);
throw new NotSupportedException("Fixture refuses operation message");
}
private async Task<ReconnectDriverResult> Reconnect(ReconnectDriver command){_state.Requests++;_state.LastOperation="Reconnect:"+command.DriverInstanceId;_state.Notify();await Task.Delay(900);return new(true,null,command.CorrelationId);}
private async Task<RestartDriverResult> Restart(RestartDriver command){_state.Requests++;_state.LastOperation="Restart:"+command.DriverInstanceId;_state.Notify();await Task.Delay(900);return new(true,null,command.CorrelationId);}
}
}