using Akka.Hosting;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
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.Host.Grpc;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
using ZB.MOM.WW.Secrets.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Host.Configuration;
internal sealed record DataConnectionProcessIdentity(string ClusterId, string NodeId, string Incarnation);
/// Composes the actual node-local publishers and transport without constructing a second actor graph.
public static class DataConnectionRegistration
{
public static DataConnectionOptions AddOtOpcUaDataConnections(this IServiceCollection services,
IConfiguration configuration, IHostEnvironment environment, bool hasDriver)
{
var options = configuration.GetSection(DataConnectionOptions.SectionName).Get() ?? new();
var errors = DataConnectionOptionsValidator.Validate(options, environment.IsDevelopment());
if (errors.Count != 0) throw new OptionsValidationException(string.Empty, typeof(DataConnectionOptions), errors);
services.AddOptions().Bind(configuration.GetSection(DataConnectionOptions.SectionName)).ValidateOnStart();
services.AddSingleton>(new DataConnectionOptionsValidator(environment));
if (!options.Enabled) return options;
if (!hasDriver) throw new InvalidOperationException("DataConnections requires this node's driver role.");
// Fail host start on a wire-contract drift (frozen field numbers and the X0 reservations); a descriptor walk, cheap.
ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnectionProtoContract.Validate();
services.TryAddSingleton(TimeProvider.System);
services.TryAddSingleton();
services.TryAddSingleton();
services.AddSingleton(sp =>
{
var role = sp.GetRequiredService();
if (string.IsNullOrWhiteSpace(role.ClusterId)) throw new InvalidOperationException("DataConnections requires a configured owning cluster role.");
return new DataConnectionProcessIdentity(role.ClusterId, role.LocalNode.Value, Guid.NewGuid().ToString("N"));
});
services.AddSingleton(sp => new CatalogActivation(sp.GetRequiredService()));
services.AddSingleton(sp =>
{
var identity = sp.GetRequiredService();
var role = sp.GetRequiredService();
var warm = sp.GetRequiredService();
var settings = sp.GetService() ?? WarmRedundancySettings.Unset;
return new LocalCatalogCoordinator(sp.GetRequiredService(), sp.GetRequiredService(),
() =>
{
var state = CaptureReadRole(role, warm);
var servingRole = settings.IsWarm && state.WarmRole != WarmRole.Active ? "Standby" : state.Role;
return new(identity.NodeId, identity.Incarnation, servingRole, 0, 0, state.Generation);
}) { Logger = LoggerFor(sp) };
});
services.AddSingleton(sp => new PartitionedSampleHub(options.Hub, sp.GetRequiredService()));
services.AddSingleton(sp => new SourceSamplePublisher(sp.GetRequiredService(),
() => sp.GetRequiredService().Serving, sp.GetRequiredService().ClusterId));
services.AddSingleton(sp => new DataOperationPolicy(sp.GetRequiredService(),
sp.GetRequiredService(), sp.GetRequiredService()));
services.AddSingleton();
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton(sp => new ProjectedCatalogCache(options.MaxMonitoredItems, options.Hub.MaxTrackedSources,
sp.GetRequiredService(), sp.GetRequiredService(), options.MaxTransportBytes));
services.AddSingleton(sp => new BrowseContinuationRegistry(options.MaxMonitoredItems, sp.GetRequiredService()));
services.AddSingleton(sp => new RemoteNamespaceResolver(sp.GetRequiredService(),
sp.GetRequiredService(), sp.GetRequiredService(),
sp.GetRequiredService(), 256, options.MaxConcurrentCalls));
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton(sp => new ProjectedMappingDeploymentRuntime(sp.GetRequiredService(),
sp.GetRequiredService()) { Logger = LoggerFor(sp) });
services.TryAddSingleton();
services.AddSingleton();
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton();
services.AddSingleton(sp => new ProjectedNamespaceApplier(sp.GetRequiredService(),
sp.GetRequiredService(), options.MaxConcurrentCalls));
services.AddSingleton(sp => new ProjectedBrowseAccess(sp.GetRequiredService(),
sp.GetRequiredService(), sp.GetRequiredService(),
sp.GetRequiredService(), (uri, identifier) =>
sp.GetRequiredService().TryGetNodeId(uri, identifier, out var nodeId) ? nodeId : null,
new DataBudget(options.UnaryTimeout, 1000, options.MaxMessageBytes), options.MaxConcurrentCalls));
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton(sp => new ActorProjectedValuePublisher(
() => sp.GetService() is { } registry && registry.TryGet(out var host) ? host : null,
route =>
{
var catalog = sp.GetRequiredService();
var mappings = sp.GetRequiredService();
return catalog.TryResolveProjected(route.Realm, route.LocalIdentifier, out var proof) && proof is not null
&& proof.Generation == route.ProjectionGeneration && proof.Lease.IsValid && proof.Lease.Serving == route.Serving
&& proof.Metadata.View.MappingId is { } mappingId && mappings.TryGetConnectionId(mappingId, out var connectionId)
&& route.DriverInstanceId == "grpc-data:" + connectionId;
}, options.MaxMonitoredItems, options.MaxPendingBytes, sp.GetRequiredService(), options.MaxTransportBytes));
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton(sp => new ProjectedDataAccess(sp.GetRequiredService(),
sp.GetRequiredService(), sp.GetRequiredService(),
mappingId => sp.GetRequiredService().TryGetConnectionId(mappingId, out var connectionId)
? connectionId : null,
sp.GetRequiredService(), sp.GetRequiredService(),
sp.GetRequiredService(),
new(options.MaxMonitoredItems, options.MaxConcurrentCalls, options.MaxPendingBytes, options.MaxStreams),
localWriteRole: () =>
{
var role = sp.GetRequiredService();
var state = CaptureWriteRole(role, sp.GetRequiredService());
var settings = sp.GetService() ?? WarmRedundancySettings.Unset;
var active = sp.GetRequiredService().Current is { IsActive: true };
return (active && role.ShouldActAsPrimary && state.Role == "Primary" &&
(!settings.IsWarm || state.WarmRole == WarmRole.Active), state.Generation);
}, renewalSink: sp.GetRequiredService()));
services.AddSingleton(sp => sp.GetRequiredService());
// H3: OPC UA HistoryRead on projected variables, forwarded over the mapping's deployed connection.
services.AddSingleton(sp => new ProjectedHistoryAccess(sp.GetRequiredService(),
sp.GetRequiredService(),
mappingId => sp.GetRequiredService().TryGetHistoryAssemblyBudget(mappingId, out var bytes)
? bytes : null,
sp.GetRequiredService()));
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton(sp => new ConfiguredProjectionDiscovery(
sp.GetRequiredService(), sp.GetRequiredService(),
sp.GetRequiredService(), sp.GetRequiredService(),
sp.GetRequiredService(),
new DataBudget(options.UnaryTimeout, Math.Min(options.MaxMonitoredItems, 1000), options.MaxMessageBytes), 256));
services.AddSingleton(sp => new ConfiguredProjectedInterestOwner(
sp.GetRequiredService(), options.MaxMonitoredItems,
options.MaxConcurrentCalls, options.MaxTransportBytes, sp.GetRequiredService()));
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton(sp =>
{
var catalog = sp.GetRequiredService();
return new DataCapabilitiesProvider(sp.GetRequiredService().ClusterId,
() => catalog.Serving, () => catalog.Current is not null && sp.GetRequiredService().CurrentScopeReady,
new(500, 1000, options.MaxMessageBytes, options.MaxMonitoredItems, Math.Min(options.MaxStreams, options.MaxStreamsPerPrincipal),
options.MaxPendingBytes, TimeSpan.FromSeconds(15), options.MaxSessionLifetime, TimeSpan.FromSeconds(30)));
});
services.AddSingleton(sp => new SubscriptionAcquisitionCapacity(options.Hub.MaxTrackedSources));
services.AddSingleton(sp => new DataWriteRuntime(sp.GetRequiredService(),
sp.GetRequiredService(), sp.GetRequiredService(),
sp.GetRequiredService(), sp.GetRequiredService(),
sp.GetRequiredService(), sp.GetRequiredService(),
sp.GetService() ?? DriverWriteBounds.Default,
sp.GetRequiredService().Incarnation,
10_000, 16 * 1024 * 1024, 16 * 1024 * 1024, 128, TimeSpan.FromSeconds(30)));
services.AddSingleton(sp =>
{
if (sp.GetService() is not { } registry || !registry.TryGet(out var host))
throw new InvalidOperationException("The local driver host is not registered yet.");
return new LocalDataRuntimeComposition(sp.GetRequiredService(), sp.GetRequiredService(),
sp.GetRequiredService(), sp.GetRequiredService(),
sp.GetRequiredService(), sp.GetRequiredService(), host,
sp.GetRequiredService(), new(4096, options.Hub.MaxTrackedSources,
options.MaxStreams, Math.Min(options.MaxStreams, options.MaxStreamsPerPrincipal), options.MaxTransportBytes,
128, 64, options.MaxPendingBytes, options.MaxSessionLifetime, TimeSpan.FromSeconds(5)),
// H2: remote history over the node manager's history port, resolved once the SDK server is up.
new DeferredOriginHistoryPort(sp.GetRequiredService()), LoggerFor(sp));
});
services.AddSingleton(sp => new DeferredFactory(() => sp.GetRequiredService().Services));
services.AddSingleton();
services.AddSingleton(sp =>
{
var id = sp.GetRequiredService();
return new DataConnectionSecretProvisioner(sp.GetRequiredService(), sp.GetRequiredService(),
sp.GetRequiredService(), sp.GetRequiredService(), id.ClusterId, id.NodeId);
});
services.AddSingleton(sp =>
{
var id = sp.GetRequiredService();
return new DataConnectionCredentialResolver(sp.GetRequiredService(), sp.GetRequiredService(), id.ClusterId, id.NodeId);
});
services.AddSingleton(sp =>
{
var id = sp.GetRequiredService();
return new DataConnectionTrustPolicyStore(sp.GetRequiredService(), sp.GetRequiredService(),
sp.GetRequiredService(), id.ClusterId, id.NodeId);
});
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton(sp =>
{
var id = sp.GetRequiredService();
var role = sp.GetRequiredService();
var warm = sp.GetRequiredService();
var settings = sp.GetService() ?? WarmRedundancySettings.Unset;
DataConnectionDeploymentRuntime? runtime = null;
runtime = new DataConnectionDeploymentRuntime(id.NodeId, id.ClusterId, sp.GetRequiredService(),
sp.GetRequiredService(), 256, sp.GetRequiredService(),
() =>
{
var state = CaptureReadRole(role, warm);
var mode = settings.Mode switch
{
OpcUaRedundancyMode.Warm => RedundancyMode.Warm,
OpcUaRedundancyMode.None => RedundancyMode.None,
_ => runtime?.CurrentConsumerMode ?? RedundancyMode.None
};
return state.Generation > 0 && Enum.TryParse(state.Role, out var actual)
&& DataConnectionRoleAdapter.MayAcquire(mode, state.WarmRole, actual);
}, useCompactBatches: options.UseCompactBatches, consumerRoleSnapshot: artifactMode =>
{
var mode = settings.Mode switch
{
OpcUaRedundancyMode.Warm => RedundancyMode.Warm,
OpcUaRedundancyMode.None => RedundancyMode.None,
_ => artifactMode
};
if (mode == RedundancyMode.Hot)
{
var hot = role.CaptureDataServingRole();
var hotEligible = hot.Generation > 0 && Enum.TryParse(hot.Role, out var hotRole)
&& DataConnectionRoleAdapter.MayAcquire(mode, null, hotRole);
return new DataConnectionConsumerRoleSnapshot(mode, hotEligible, hot.ReadEligibilityEpoch);
}
var state = CaptureReadRole(role, warm);
var eligible = state.Generation > 0 && Enum.TryParse(state.Role, out var actual)
&& DataConnectionRoleAdapter.MayAcquire(mode, state.WarmRole, actual);
return new DataConnectionConsumerRoleSnapshot(mode, eligible, state.Generation);
})
{
Logger = LoggerFor(sp),
};
return runtime;
});
services.AddSingleton(sp =>
{
var id = sp.GetRequiredService();
return new DataConnectionBundleLoader(sp.GetRequiredService(),
sp.GetRequiredService(), id.ClusterId, id.NodeId);
});
services.AddHostedService(sp => new DataConnectionBundleBackgroundService(sp.GetRequiredService(),
options.CredentialBundlePath, options.TrustBundlePath, options.BundleRefreshInterval));
services.AddSingleton();
services.AddGrpc().AddServiceOptions(grpc =>
{
grpc.MaxReceiveMessageSize = options.MaxMessageBytes;
grpc.MaxSendMessageSize = options.MaxMessageBytes;
grpc.EnableDetailedErrors = false;
});
return options;
}
private static Microsoft.Extensions.Logging.ILogger LoggerFor(IServiceProvider sp) =>
(Microsoft.Extensions.Logging.ILogger?)sp.GetService()?.CreateLogger()
?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance;
private static (string Role, long Generation, WarmRole? WarmRole, long ReadEpoch) CaptureReadRole(
RedundancyRoleView role, DataConnectionWarmRoleView warm)
{
if (!ReferenceEquals(role.DispatchFence, warm.DispatchFence)) return ("Unknown", 0, null, 0);
// Both verdicts are immutable. The monotone primary generation brackets
// the Warm read, so a stable generation gives a pair that coexisted.
// A competing read or dispatch does not withdraw an unchanged role.
var primary = role.CaptureDataServingRole();
var warmVerdict = warm.Snapshot;
return primary.Generation == role.PrimaryGeneration
? CombineRole(primary, warmVerdict)
: ("Unknown", 0, null, 0);
}
private static (string Role, long Generation, WarmRole? WarmRole, long ReadEpoch) CaptureWriteRole(
RedundancyRoleView role, DataConnectionWarmRoleView warm)
{
if (!ReferenceEquals(role.DispatchFence, warm.DispatchFence) || !role.DispatchFence.TryEnter(out var lease))
return ("Unknown", 0, null, 0);
using (lease)
return CombineRole(role.CaptureDataServingRole(), warm.Snapshot);
}
private static (string Role, long Generation, WarmRole? WarmRole, long ReadEpoch) CombineRole(
DataServingRoleSnapshot primary, DataConnectionWarmRoleSnapshot warm)
{
if (primary.Generation == long.MaxValue || warm.Generation == long.MaxValue
|| primary.Generation > long.MaxValue - warm.Generation)
return ("Unknown", long.MaxValue, null, long.MaxValue);
return (primary.Role, primary.Generation + warm.Generation, warm.Role, primary.ReadEligibilityEpoch);
}
private sealed class DeferredFactory(Func resolve) : IDataConnectionFactory
{
public IDataConnection Create(DataAuthenticatedContext context, DataTarget target) => resolve().Create(context, target);
}
}