using Akka.Actor; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Core.Authorization; using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// Shared node-incarnation write state, explicitly wired only when the data plane is ready. public sealed class DataWriteRuntime { private readonly LocalCatalogCoordinator _catalog; private readonly DataOperationPolicy _policy; private readonly DataCapabilitiesProvider _capabilities; private readonly RedundancyRoleView _role; private readonly WriteOperationRegistry _registry; private readonly WriteValueBudget _values; private readonly TimeProvider _clock; private readonly DriverWriteBounds _bounds; internal readonly WriteRouteState Routes; internal readonly IWriteDispatchGate Gate; internal readonly LateWriteObserver Observer; internal Action? BeforeDriverStopForTests { get; set; } public DataWriteRuntime(LocalCatalogCoordinator catalog, CatalogActivation activation, DataPlaneAuthorityState authority, DataOperationPolicy policy, DataCapabilitiesProvider capabilities, RedundancyRoleView role, TimeProvider clock, DriverWriteBounds bounds, string servingIncarnation, int maxOperations, long maxRegistryBytes, long maxWriteBytes, int maxPhysicalWrites, TimeSpan retention) { if (!ReferenceEquals(authority.DispatchFence, catalog.DispatchFence) || !ReferenceEquals(authority.DispatchFence, activation.DispatchFence) || !ReferenceEquals(authority.DispatchFence, role.DispatchFence) || !policy.UsesAuthority(authority) || capabilities.Serving.Incarnation != servingIncarnation) throw new ArgumentException("Rich write publishers must share one fence and authority."); _catalog = catalog; _policy = policy; _capabilities = capabilities; _role = role; _clock = clock; _bounds = bounds; Routes = new(authority.DispatchFence); Gate = new DataWriteDispatchGate(catalog, activation, authority, policy, role, Routes, clock, bounds); Observer = new(maxPhysicalWrites, retention, clock); _registry = new(servingIncarnation, maxOperations, maxRegistryBytes, retention, clock); _values = new(maxWriteBytes); } internal bool MatchesHost(LocalCatalogCoordinator? coordinator, IDriverPrimaryRoleSource? role, TimeProvider clock, DriverWriteBounds bounds) => ReferenceEquals(_catalog, coordinator) && ReferenceEquals(_role, role) && ReferenceEquals(_clock, clock) && _bounds == bounds; /// Creates an executor for an authenticated transport context and this node's driver host. public IDataWriteService ForCaller(DataAuthenticatedContext context, Func resolveHost) => new DataWriteExecutor(context, () => _catalog.Current, _policy, _capabilities, new ActorDataWriteRoute(resolveHost, Routes, _role, _bounds, _clock), _registry, _values, _clock, _bounds); } internal sealed class ActorDataWriteRoute(Func resolveHost, WriteRouteState routes, RedundancyRoleView role, DriverWriteBounds bounds, TimeProvider? clock = null) : IDataWriteRoute { public bool TryResolve(DataView view, out WriteRouteTarget? target) { if (!routes.TryResolve(view, out var found) || found is null || role.PrimaryGeneration <= 0) { target = null; return false; } target = found with { PrimaryGeneration = role.PrimaryGeneration }; return true; } public async Task DispatchAsync(WriteAdmissionTicket ticket, WriteClaim claim, CancellationToken ct) { var host = resolveHost(); if (host is null) { var rejected = new DataWriteOutcome(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Driver host unavailable."); if (claim.Complete(rejected)) ticket.Dispose(); return claim.CurrentOutcome ?? rejected; } try { using var deadline = new CancellationTokenSource(bounds.GatewayAsk, clock ?? TimeProvider.System); using var linked = CancellationTokenSource.CreateLinkedTokenSource(deadline.Token, ct); return await host.Ask(new DriverHostActor.RouteRichWrite(ticket, claim), Timeout.InfiniteTimeSpan, linked.Token) .ConfigureAwait(false); } catch { var rejected = new DataWriteOutcome(DataWriteState.RejectedBeforeDispatch, 0x800A0000u, "Route timed out before dispatch."); if (claim.Complete(rejected)) { ticket.Dispose(); return rejected; } var unknown = new DataWriteOutcome(DataWriteState.OutcomeUnknown, 0x800A0000u, "Route outcome unknown."); claim.Complete(unknown); return claim.CurrentOutcome ?? unknown; } } }