8c28506d96
Gate #1026 (2048 projected items, rig seed --scale 2048) still failed after #1115. Three defects, found by first making the origin and the consumer say why: Diagnostics (origin + consumer) - SourceInvalidationReason (bounded enum, classified from the publisher's reason constants): counted per reason (`otopcua.dataconn.source.invalidations{reason}`, `Invalidate.<Reason>` in SourceIngressDiagnostics), recorded on the source and logged at Debug (PartitionedSampleHub.Logger). - An interest lease records why it stopped; the origin Subscribe stream's Reset text names it ("Source invalidated (<reason>).", "Source retired.", "Source interest released.", "Source routing changed.", "Source partition reset.", "Source binding replaced.") instead of always "Source change history expired."; logged at Information (Released at Debug). The texts are for people/counters only: the consumer classifies them into ResetSourceInvalidated / ResetInterestLost (no peer branches on them; the rig probe whitelist is updated). - Consumer: renewal started/succeeded/failed/budget/slot counters, RenewalFail.<point> and AttemptEnd.<reason> (bounded, constant keys). 1. Origin: a binding check invalidated live sources. The driver actor's source-binding retry re-walks every desired reference (offset 0, every <= 30 s once any one failed); for an already-bound reference it took the source's serialization gate, and when the poll thread was publishing that source both sides invalidated it (BindingContention / SerializationContention) and reset every origin stream holding it. Live s1026-c: the only invalidation reasons were those two (5+5 during the open, recurring every ~30 s). EnsureDriverBinding now answers an already-bound, current source without the gate. Live after: 0 BindingContention. 2. Consumer: per-item metadata lease renewal could not keep up. Each projected item renewed its 15 s lease with its own capabilities + GetMetadata pair holding a 256 KiB unary reservation; at the default 1 MiB budget four ran at once and the rest retried on the next 250 ms tick (~16 items/s). Live s1026-d: 155 703 renewals started, 153 019 refused by the unary budget, 2 564 committed; ~1900 of 2048 items stood down BadUserAccessDenied; 0 recovered after the origin restart. RemoteNamespaceResolver.RenewExactBatchAsync renews many items with one capabilities call and one GetMetadata per origin MaxBatchItems (the single-item renewal is now the batch of one: same checks, lease bound and commit); a cohort renews every due item of a tick in batches of 128, and the between-attempt renewal (every item after an origin restart) is batched too. 3. Consumer: two demands of one node in one cohort deadlocked the batch: the second joined (#969) the first's claim, and the batch waited for the joiner before publishing its verdict. The batch now publishes first. Live (OrbStack rig, 160 + 1888 items, 4 Hz churn, SOURCE pair restart): s1026-f run 1 open 10.2 s, recovery 1.5 s, 0 resets of any kind; s1026-h run 2 PASS (open 3.1 s, recovery 3.6 s, 0 resets, no history-expired or source-invalidated log line). Remaining (not fixed here): s1026-h run 1 recovered only 852 of 1888 large-mapping items after the restart: their renewals fail in the catalog cache's predecessor-chain bound (RenewalFail.Cache.PredecessorChain 81 163). Tests: GrpcData1026BindingContentionTests (fails without the fast path), GrpcData1026RenewalBatchWireTests (one tick renews all due items in one metadata call - fails with per-item renewals; two demands of one node - fails without the ordering fix), GrpcData1026ResetReasonTests. Co-Authored-By: Claude <noreply@anthropic.com>
356 lines
26 KiB
C#
356 lines
26 KiB
C#
using Akka.Hosting;
|
|
using Microsoft.Extensions.DependencyInjection.Extensions;
|
|
using Microsoft.Extensions.Logging;
|
|
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);
|
|
|
|
/// <summary>Composes the actual node-local publishers and transport without constructing a second actor graph.</summary>
|
|
public static class DataConnectionRegistration
|
|
{
|
|
public static DataConnectionOptions AddOtOpcUaDataConnections(this IServiceCollection services,
|
|
IConfiguration configuration, IHostEnvironment environment, bool hasDriver)
|
|
{
|
|
var options = configuration.GetSection(DataConnectionOptions.SectionName).Get<DataConnectionOptions>() ?? new();
|
|
var errors = DataConnectionOptionsValidator.Validate(options, environment.IsDevelopment());
|
|
if (errors.Count != 0) throw new OptionsValidationException(string.Empty, typeof(DataConnectionOptions), errors);
|
|
services.AddOptions<DataConnectionOptions>().Bind(configuration.GetSection(DataConnectionOptions.SectionName)).ValidateOnStart();
|
|
services.AddSingleton<IValidateOptions<DataConnectionOptions>>(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>(TimeProvider.System);
|
|
services.TryAddSingleton<DataWriteDispatchFence>();
|
|
services.TryAddSingleton<DataConnectionWarmRoleView>();
|
|
AddDataConnectionAuditLog(services);
|
|
services.AddSingleton(sp =>
|
|
{
|
|
var role = sp.GetRequiredService<IClusterRoleInfo>();
|
|
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<DataWriteDispatchFence>()));
|
|
// A1: the condition-key deriver (validated above; absent secret ⇒ Unavailable, conditions never advertised).
|
|
services.AddSingleton(_ => ConditionKeys.FromSecret(options.ConditionKeySecret));
|
|
services.AddSingleton(sp =>
|
|
{
|
|
var identity = sp.GetRequiredService<DataConnectionProcessIdentity>();
|
|
var role = sp.GetRequiredService<RedundancyRoleView>();
|
|
var warm = sp.GetRequiredService<DataConnectionWarmRoleView>();
|
|
var settings = sp.GetService<WarmRedundancySettings>() ?? WarmRedundancySettings.Unset;
|
|
return new LocalCatalogCoordinator(sp.GetRequiredService<CatalogActivation>(), sp.GetRequiredService<DataPlaneAuthorityState>(),
|
|
() =>
|
|
{
|
|
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<LocalCatalogCoordinator>(sp),
|
|
ConditionKeys = ReportConditionKeys(sp.GetRequiredService<ConditionKeys>(), LoggerFor<LocalCatalogCoordinator>(sp))
|
|
};
|
|
});
|
|
services.AddSingleton(sp => new PartitionedSampleHub(options.Hub, sp.GetRequiredService<TimeProvider>())
|
|
{ Logger = LoggerFor<PartitionedSampleHub>(sp) });
|
|
services.AddSingleton(sp => new SourceSamplePublisher(sp.GetRequiredService<PartitionedSampleHub>(),
|
|
() => sp.GetRequiredService<LocalCatalogCoordinator>().Serving, sp.GetRequiredService<DataConnectionProcessIdentity>().ClusterId));
|
|
services.AddSingleton(sp => new DataOperationPolicy(sp.GetRequiredService<DataPlaneAuthorityState>(),
|
|
sp.GetRequiredService<IPermissionEvaluator>(), sp.GetRequiredService<TimeProvider>()));
|
|
services.AddSingleton<DeployedGrpcDataConnectionSource>();
|
|
services.AddSingleton<IGrpcDataAdapterConnectionSource>(sp => sp.GetRequiredService<DeployedGrpcDataConnectionSource>());
|
|
services.AddSingleton(sp => new ProjectedCatalogCache(options.MaxMonitoredItems, options.Hub.MaxTrackedSources,
|
|
sp.GetRequiredService<TimeProvider>(), sp.GetRequiredService<DataOperationPolicy>(), options.MaxTransportBytes));
|
|
services.AddSingleton(sp => new BrowseContinuationRegistry(options.MaxMonitoredItems, sp.GetRequiredService<TimeProvider>()));
|
|
services.AddSingleton(sp => new RemoteNamespaceResolver(sp.GetRequiredService<ProjectedCatalogCache>(),
|
|
sp.GetRequiredService<BrowseContinuationRegistry>(), sp.GetRequiredService<IGrpcDataAdapterConnectionSource>(),
|
|
sp.GetRequiredService<DataOperationPolicy>(), 256, options.MaxConcurrentCalls));
|
|
services.AddSingleton<IFederatedProjectionCatalog>(sp => sp.GetRequiredService<RemoteNamespaceResolver>());
|
|
services.AddSingleton(sp => new ProjectedMappingDeploymentRuntime(sp.GetRequiredService<LocalCatalogCoordinator>(),
|
|
sp.GetRequiredService<RemoteNamespaceResolver>()) { Logger = LoggerFor<ProjectedMappingDeploymentRuntime>(sp) });
|
|
services.TryAddSingleton<DeferredAddressSpaceSink>();
|
|
services.AddSingleton<DeferredProjectedNodeAccess>();
|
|
services.AddSingleton<IProjectedNodeLookup>(sp => sp.GetRequiredService<DeferredProjectedNodeAccess>());
|
|
services.AddSingleton<IProjectedAnchorSink>(sp => sp.GetRequiredService<DeferredProjectedNodeAccess>());
|
|
services.AddSingleton<IProjectedNamespacePageSink, DeferredProjectedNamespacePageSink>();
|
|
services.AddSingleton(sp => new ProjectedNamespaceApplier(sp.GetRequiredService<IFederatedProjectionCatalog>(),
|
|
sp.GetRequiredService<IProjectedNamespacePageSink>(), options.MaxConcurrentCalls));
|
|
services.AddSingleton(sp => new ProjectedBrowseAccess(sp.GetRequiredService<ProjectedMappingDeploymentRuntime>(),
|
|
sp.GetRequiredService<IFederatedProjectionCatalog>(), sp.GetRequiredService<ProjectedNamespaceApplier>(),
|
|
sp.GetRequiredService<IProjectedAnchorSink>(), (uri, identifier) =>
|
|
sp.GetRequiredService<IProjectedNodeLookup>().TryGetNodeId(uri, identifier, out var nodeId) ? nodeId : null,
|
|
new DataBudget(options.UnaryTimeout, 1000, options.MaxMessageBytes), options.MaxConcurrentCalls));
|
|
services.AddSingleton<IProjectedBrowseAccess>(sp => sp.GetRequiredService<ProjectedBrowseAccess>());
|
|
services.AddSingleton(sp => new ActorProjectedValuePublisher(
|
|
() => sp.GetService<ActorRegistry>() is { } registry && registry.TryGet<DriverHostActorKey>(out var host) ? host : null,
|
|
route =>
|
|
{
|
|
var catalog = sp.GetRequiredService<IFederatedProjectionCatalog>();
|
|
var mappings = sp.GetRequiredService<ProjectedMappingDeploymentRuntime>();
|
|
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<TimeProvider>(), options.MaxTransportBytes));
|
|
services.AddSingleton<IProjectedValuePublisher>(sp => sp.GetRequiredService<ActorProjectedValuePublisher>());
|
|
services.AddSingleton(sp => new ProjectedDataAccess(sp.GetRequiredService<IFederatedProjectionCatalog>(),
|
|
sp.GetRequiredService<IProjectedNodeLookup>(), sp.GetRequiredService<IGrpcDataAdapterConnectionSource>(),
|
|
mappingId => sp.GetRequiredService<ProjectedMappingDeploymentRuntime>().TryGetConnectionId(mappingId, out var connectionId)
|
|
? connectionId : null,
|
|
sp.GetRequiredService<DataOperationPolicy>(), sp.GetRequiredService<IProjectedValuePublisher>(),
|
|
sp.GetRequiredService<TimeProvider>(),
|
|
new(options.MaxMonitoredItems, options.MaxConcurrentCalls, options.MaxPendingBytes, options.MaxStreams),
|
|
localWriteRole: () =>
|
|
{
|
|
var role = sp.GetRequiredService<RedundancyRoleView>();
|
|
var state = CaptureWriteRole(role, sp.GetRequiredService<DataConnectionWarmRoleView>());
|
|
var settings = sp.GetService<WarmRedundancySettings>() ?? WarmRedundancySettings.Unset;
|
|
var active = sp.GetRequiredService<LocalCatalogCoordinator>().Current is { IsActive: true };
|
|
return (active && role.ShouldActAsPrimary && state.Role == "Primary" &&
|
|
(!settings.IsWarm || state.WarmRole == WarmRole.Active), state.Generation);
|
|
}, renewalSink: sp.GetRequiredService<IProjectedNamespacePageSink>()));
|
|
services.AddSingleton<IProjectedDataAccess>(sp => sp.GetRequiredService<ProjectedDataAccess>());
|
|
// H4: one dependency-free history diagnostics instance shared by the origin services, the consumer gateway and the
|
|
// diagnostics readers (it also backs the otopcua.dataconn.history.* metrics).
|
|
services.AddSingleton(sp =>
|
|
{
|
|
// Before the first peer call composes the origin services, report the backend's availability (and zeros) from a
|
|
// probe of the same deferred history port, so a fresh H4 origin never reads like a pre-H4 build (H4 review 2).
|
|
var diagnostics = new DataConnectionHistoryDiagnostics();
|
|
var probe = new DeferredOriginHistoryPort(sp.GetRequiredService<DeferredAddressSpaceSink>());
|
|
diagnostics.AttachProvisionalOrigin(() => probe.Serving is not null);
|
|
return diagnostics;
|
|
});
|
|
// A4: one dependency-free condition diagnostics instance shared by the origin condition items, the consumer runtime and
|
|
// the diagnostics readers (it also backs the side-labelled otopcua.dataconn.condition* metrics).
|
|
services.AddSingleton(sp =>
|
|
{
|
|
var diagnostics = new DataConnectionConditionDiagnostics();
|
|
if (sp.GetService<ConditionStateHub>() is { } hub) diagnostics.AttachUnsignalled(() => hub.Unsignalled.Values.Sum(x => x.Conditions));
|
|
return diagnostics;
|
|
});
|
|
// H3: OPC UA HistoryRead on projected variables, forwarded over the mapping's deployed connection.
|
|
services.AddSingleton(sp => new ProjectedHistoryAccess(sp.GetRequiredService<ProjectedDataAccess>(),
|
|
sp.GetRequiredService<IGrpcDataAdapterConnectionSource>(),
|
|
mappingId => sp.GetRequiredService<ProjectedMappingDeploymentRuntime>().TryGetHistoryAssemblyBudget(mappingId, out var bytes)
|
|
? bytes : null,
|
|
sp.GetRequiredService<TimeProvider>(), sp.GetRequiredService<DataConnectionHistoryDiagnostics>()));
|
|
services.AddSingleton<IProjectedHistoryAccess>(sp => sp.GetRequiredService<ProjectedHistoryAccess>());
|
|
// A3: imported conditions (§5.3–§5.5) — the gate, per-connection demand and the stream runtime. The node manager is
|
|
// bound as its sink by OtOpcUaServerHostedService once the server is up.
|
|
services.AddSingleton(sp => new ProjectedConditionAccess(
|
|
new DeployedConditionMappings(sp.GetRequiredService<ProjectedMappingDeploymentRuntime>()),
|
|
sp.GetRequiredService<IGrpcDataAdapterConnectionSource>(), sp.GetRequiredService<DataOperationPolicy>(), null,
|
|
sp.GetRequiredService<TimeProvider>(), ProjectedConditionOptions.Default with
|
|
{
|
|
MaxImportedConditionNodes = options.MaxImportedConditionNodes,
|
|
MaxImportedConditionBytes = options.MaxImportedConditionBytes,
|
|
}, sp.GetRequiredService<ILoggerFactory>().CreateLogger<ProjectedConditionAccess>(),
|
|
sp.GetRequiredService<DataConnectionConditionDiagnostics>()));
|
|
services.AddSingleton<IProjectedConditionAccess>(sp => sp.GetRequiredService<ProjectedConditionAccess>());
|
|
services.AddSingleton<IConfiguredProjectionDiscovery>(sp => new ConfiguredProjectionDiscovery(
|
|
sp.GetRequiredService<ProjectedMappingDeploymentRuntime>(), sp.GetRequiredService<IFederatedProjectionCatalog>(),
|
|
sp.GetRequiredService<ProjectedNamespaceApplier>(), sp.GetRequiredService<IProjectedNodeLookup>(),
|
|
sp.GetRequiredService<ProjectedDataAccess>(),
|
|
new DataBudget(options.UnaryTimeout, Math.Min(options.MaxMonitoredItems, 1000), options.MaxMessageBytes), 256));
|
|
services.AddSingleton(sp => new ConfiguredProjectedInterestOwner(
|
|
sp.GetRequiredService<IConfiguredProjectionDiscovery>(), options.MaxMonitoredItems,
|
|
options.MaxConcurrentCalls, options.MaxTransportBytes, sp.GetRequiredService<TimeProvider>()));
|
|
services.AddSingleton<IProjectedDependencyInterestSink>(sp => sp.GetRequiredService<ConfiguredProjectedInterestOwner>());
|
|
services.AddSingleton(sp =>
|
|
{
|
|
var catalog = sp.GetRequiredService<LocalCatalogCoordinator>();
|
|
return new DataCapabilitiesProvider(sp.GetRequiredService<DataConnectionProcessIdentity>().ClusterId,
|
|
() => catalog.Serving, () => catalog.Current is not null && sp.GetRequiredService<DataConnectionDeploymentRuntime>().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<LocalCatalogCoordinator>(),
|
|
sp.GetRequiredService<CatalogActivation>(), sp.GetRequiredService<DataPlaneAuthorityState>(),
|
|
sp.GetRequiredService<DataOperationPolicy>(), sp.GetRequiredService<DataCapabilitiesProvider>(),
|
|
sp.GetRequiredService<RedundancyRoleView>(), sp.GetRequiredService<TimeProvider>(),
|
|
sp.GetService<DriverWriteBounds>() ?? DriverWriteBounds.Default,
|
|
sp.GetRequiredService<DataConnectionProcessIdentity>().Incarnation,
|
|
10_000, 16 * 1024 * 1024, 16 * 1024 * 1024, 128, TimeSpan.FromSeconds(30)));
|
|
services.AddSingleton(sp =>
|
|
{
|
|
if (sp.GetService<ActorRegistry>() is not { } registry || !registry.TryGet<DriverHostActorKey>(out var host))
|
|
throw new InvalidOperationException("The local driver host is not registered yet.");
|
|
return new LocalDataRuntimeComposition(sp.GetRequiredService<LocalCatalogCoordinator>(), sp.GetRequiredService<PartitionedSampleHub>(),
|
|
sp.GetRequiredService<DataOperationPolicy>(), sp.GetRequiredService<DataCapabilitiesProvider>(),
|
|
sp.GetRequiredService<TimeProvider>(), sp.GetRequiredService<DataWriteRuntime>(), host,
|
|
sp.GetRequiredService<SubscriptionAcquisitionCapacity>(), new(4096, options.Hub.MaxTrackedSources,
|
|
options.MaxStreams, Math.Min(options.MaxStreams, options.MaxStreamsPerPrincipal), options.MaxTransportBytes,
|
|
128, 64, options.MaxPendingBytes, options.MaxSessionLifetime, TimeSpan.FromSeconds(5),
|
|
options.MaxConditionMethodOperations, options.MaxConditionMethodOperationsPerPrincipal),
|
|
// H2: remote history over the node manager's history port, resolved once the SDK server is up.
|
|
new DeferredOriginHistoryPort(sp.GetRequiredService<DeferredAddressSpaceSink>()), LoggerFor<LocalDataServices>(sp),
|
|
sp.GetRequiredService<DataConnectionHistoryDiagnostics>(),
|
|
// A2: root-scoped condition items over the A1 hub and the node manager's snapshot port.
|
|
sp.GetService<ConditionStateHub>(), new DeferredOriginConditionSource(sp.GetRequiredService<DeferredAddressSpaceSink>()),
|
|
// A2b security review: the audit trail on its OWN category from the host's logger factory.
|
|
sp.GetRequiredService<IDataConnectionAuditLog>(), sp.GetRequiredService<DataConnectionConditionDiagnostics>());
|
|
});
|
|
services.AddSingleton<IDataConnectionFactory>(sp => new DeferredFactory(() => sp.GetRequiredService<LocalDataRuntimeComposition>().Services));
|
|
services.AddSingleton<DataConnectionSecretChangeHandler>();
|
|
services.AddSingleton(sp =>
|
|
{
|
|
var id = sp.GetRequiredService<DataConnectionProcessIdentity>();
|
|
return new DataConnectionSecretProvisioner(sp.GetRequiredService<ISecretStore>(), sp.GetRequiredService<ISecretCipher>(),
|
|
sp.GetRequiredService<ISecretCacheInvalidator>(), sp.GetRequiredService<DataConnectionSecretChangeHandler>(), id.ClusterId, id.NodeId);
|
|
});
|
|
services.AddSingleton(sp =>
|
|
{
|
|
var id = sp.GetRequiredService<DataConnectionProcessIdentity>();
|
|
return new DataConnectionCredentialResolver(sp.GetRequiredService<ISecretStore>(), sp.GetRequiredService<ISecretCipher>(), id.ClusterId, id.NodeId);
|
|
});
|
|
services.AddSingleton(sp =>
|
|
{
|
|
var id = sp.GetRequiredService<DataConnectionProcessIdentity>();
|
|
return new DataConnectionTrustPolicyStore(sp.GetRequiredService<ISecretStore>(), sp.GetRequiredService<ISecretCipher>(),
|
|
sp.GetRequiredService<DataConnectionSecretChangeHandler>(), id.ClusterId, id.NodeId);
|
|
});
|
|
services.AddSingleton<IDataConnectionSecurityProvider, DataConnectionSecurityProvider>();
|
|
services.AddSingleton<IDataConnectionBundleCommitObserver, DataConnectionBundleCommitObserver>();
|
|
services.AddSingleton<IDataConnectionScopeActivator, DataConnectionScopeActivator>();
|
|
services.AddSingleton(sp =>
|
|
{
|
|
var id = sp.GetRequiredService<DataConnectionProcessIdentity>();
|
|
var role = sp.GetRequiredService<RedundancyRoleView>();
|
|
var warm = sp.GetRequiredService<DataConnectionWarmRoleView>();
|
|
var settings = sp.GetService<WarmRedundancySettings>() ?? WarmRedundancySettings.Unset;
|
|
DataConnectionDeploymentRuntime? runtime = null;
|
|
runtime = new DataConnectionDeploymentRuntime(id.NodeId, id.ClusterId, sp.GetRequiredService<IDataConnectionSecurityProvider>(),
|
|
sp.GetRequiredService<IDataConnectionScopeActivator>(), 256, sp.GetRequiredService<TimeProvider>(),
|
|
() =>
|
|
{
|
|
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<RedundancyRole>(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<RedundancyRole>(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<RedundancyRole>(state.Role, out var actual)
|
|
&& DataConnectionRoleAdapter.MayAcquire(mode, state.WarmRole, actual);
|
|
return new DataConnectionConsumerRoleSnapshot(mode, eligible, state.Generation);
|
|
})
|
|
{
|
|
Logger = LoggerFor<DataConnectionDeploymentRuntime>(sp),
|
|
HistoryDiagnostics = sp.GetRequiredService<DataConnectionHistoryDiagnostics>(),
|
|
ConditionDiagnostics = sp.GetRequiredService<DataConnectionConditionDiagnostics>(),
|
|
};
|
|
return runtime;
|
|
});
|
|
services.AddSingleton(sp =>
|
|
{
|
|
var id = sp.GetRequiredService<DataConnectionProcessIdentity>();
|
|
return new DataConnectionBundleLoader(sp.GetRequiredService<DataConnectionSecretProvisioner>(),
|
|
sp.GetRequiredService<DataConnectionTrustPolicyStore>(), id.ClusterId, id.NodeId);
|
|
});
|
|
services.AddHostedService(sp => new DataConnectionBundleBackgroundService(sp.GetRequiredService<DataConnectionBundleLoader>(),
|
|
options.CredentialBundlePath, options.TrustBundlePath, options.BundleRefreshInterval));
|
|
services.AddSingleton<DataConnectionAuthenticator>();
|
|
services.AddGrpc().AddServiceOptions<DataConnectionGrpcService>(grpc =>
|
|
{
|
|
grpc.MaxReceiveMessageSize = options.MaxMessageBytes;
|
|
grpc.MaxSendMessageSize = options.MaxMessageBytes;
|
|
grpc.EnableDetailedErrors = false;
|
|
});
|
|
return options;
|
|
}
|
|
|
|
/// <summary>A1 fail-closed diagnostic: an origin without a condition-key secret says so once, when its catalog starts.</summary>
|
|
private static ConditionKeys ReportConditionKeys(ConditionKeys keys, Microsoft.Extensions.Logging.ILogger logger)
|
|
{
|
|
if (!keys.IsAvailable)
|
|
Microsoft.Extensions.Logging.LoggerExtensions.LogInformation(logger, "{Reason}", keys.UnavailableReason);
|
|
return keys;
|
|
}
|
|
/// <summary>
|
|
/// A2b security review: registers the data-connection audit log — a logger of
|
|
/// <see cref="LoggerDataConnectionAuditLog.Category"/> created from the host's REAL <c>ILoggerFactory</c> (no factory ⇒ no
|
|
/// output), so operators can route the audit trail by category. A test or host may register its own first.
|
|
/// </summary>
|
|
internal static void AddDataConnectionAuditLog(IServiceCollection services) =>
|
|
services.TryAddSingleton<IDataConnectionAuditLog>(sp =>
|
|
LoggerDataConnectionAuditLog.Create(sp.GetService<Microsoft.Extensions.Logging.ILoggerFactory>()));
|
|
|
|
private static Microsoft.Extensions.Logging.ILogger LoggerFor<T>(IServiceProvider sp) =>
|
|
(Microsoft.Extensions.Logging.ILogger?)sp.GetService<Microsoft.Extensions.Logging.ILoggerFactory>()?.CreateLogger<T>()
|
|
?? 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<IDataConnectionFactory> resolve) : IDataConnectionFactory
|
|
{
|
|
public IDataConnection Create(DataAuthenticatedContext context, DataTarget target) => resolve().Create(context, target);
|
|
}
|
|
}
|