feat: host tls data service and route node and cluster connections

This commit is contained in:
Joseph Doherty
2026-11-16 11:07:34 -05:00
parent af30a0266a
commit 47960a6d57
95 changed files with 9878 additions and 87 deletions
@@ -390,6 +390,24 @@ public sealed class AdminOperationsActor : ReceiveActor
private async Task<ComposeOutcome> ComposeDeploymentAsync(StartDeployment msg, string sourceNode)
{
await using var db = await _dbFactory.CreateDbContextAsync();
// The singleton update obtains a write lock BEFORE reading the draft. The revision and
// deployment row remain in this same transaction until the sealed artifact is committed.
await using var transaction = db.Database.IsRelational()
? await db.Database.BeginTransactionAsync(System.Data.IsolationLevel.Serializable)
: null;
DataConnectionScopeState scopeState;
if (transaction is not null)
{
var locked = await db.Database.ExecuteSqlRawAsync("UPDATE DataConnectionScopeState SET ScopeVersion = ScopeVersion WHERE Id = 1");
if (locked != 1) throw new InvalidOperationException("Authoritative data scope state is unavailable.");
scopeState = await db.DataConnectionScopeStates.SingleAsync(x => x.Id == 1);
}
else
{
// Nonrelational providers are used by isolated unit fixtures only.
scopeState = await db.DataConnectionScopeStates.SingleOrDefaultAsync(x => x.Id == 1) ?? new DataConnectionScopeState();
if (db.Entry(scopeState).State == EntityState.Detached) db.DataConnectionScopeStates.Add(scopeState);
}
// Full pre-seal gate: run the complete DraftValidator (one pass, all rules) and reject
// on ANY validation error. The config is now canonical — the company overlay loader emits
@@ -523,6 +541,10 @@ public sealed class AdminOperationsActor : ReceiveActor
// Composed from the validated snapshot, never from a second read: an edit that lands between
// validation and here is simply not in this artifact (R03:3.2).
var scope = DataConnectionScopeRevision.Advance(scopeState.ScopeVersion, scopeState.Fingerprint, draft.DataConnections);
scopeState.ScopeVersion = scope.Version;
scopeState.Fingerprint = scope.Fingerprint;
draft.DataConnectionScopeVersion = scope.Version;
var artifact = ConfigComposer.Compose(draft);
var deploymentId = DeploymentId.NewId();
var revHash = RevisionHash.Parse(artifact.RevisionHash);
@@ -547,6 +569,7 @@ public sealed class AdminOperationsActor : ReceiveActor
});
await db.SaveChangesAsync();
if (transaction is not null) await transaction.CommitAsync();
// Accepted message = the compile-cost advisory (if any) + any Warn-mode TagConfig warnings, so
// the operator sees the non-blocking strictness findings on a successful deploy.
@@ -95,6 +95,7 @@ public static class ConfigComposer
Scripts = snapshot.Scripts,
VirtualTags = snapshot.VirtualTags,
ScriptedAlarms = snapshot.ScriptedAlarms,
DataConnectionScopeVersion = snapshot.DataConnectionScopeVersion,
DataConnections = snapshot.DataConnections.OrderBy(x => x.DataConnectionId, StringComparer.Ordinal).Select(connection =>
{
var copy = JsonSerializer.Deserialize<ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnection>(JsonSerializer.SerializeToUtf8Bytes(connection, JsonOptions), JsonOptions)!;
@@ -0,0 +1,70 @@
using Grpc.Core;
using Grpc.Core.Interceptors;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Host.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.Host.Configuration;
/// <summary>Authenticates against the same deployed, process-local authority as operation admission.</summary>
public sealed class DataConnectionAuthenticator(IDataPlaneAuthoritySource authority, IOptions<ApiKeyOptions> options,
TimeProvider clock)
{
public DataAuthenticatedContext Authenticate(string bearer)
{
var snapshot = authority.Current;
if (!snapshot.HasArtifact || string.IsNullOrWhiteSpace(options.Value.Pepper)
|| !ApiKeySecret.TryParse(bearer, out var id, out var secret)) throw Denied();
var key = snapshot.FindUsableKey(id, clock.GetUtcNow().UtcDateTime);
if (key is null || string.IsNullOrWhiteSpace(key.Principal)
|| string.Equals(key.Principal, OpcUaPrincipals.Anonymous, StringComparison.OrdinalIgnoreCase)) throw Denied();
try { if (!ApiKeySecret.Verify(secret, options.Value.Pepper, key.SecretHash)) throw Denied(); }
catch (ArgumentException) { throw Denied(); }
var context = new DataAuthenticatedContext(key.Principal, key.ApiKeyId,
DataCallerIdentity.CredentialVersionFor(key), key.ExpiresUtc is { } expiry
? new DateTimeOffset(DateTime.SpecifyKind(expiry, DateTimeKind.Utc)) : null, snapshot.GenerationId);
if (!ReferenceEquals(snapshot, authority.Current) || !IsCurrent(context)) throw Denied();
return context;
}
public bool IsCurrent(DataAuthenticatedContext context)
{
var snapshot = authority.Current;
var now = clock.GetUtcNow();
if (!snapshot.HasArtifact || snapshot.GenerationId != context.AuthorityEpoch
|| context.CredentialExpiresUtc is { } originalExpiry && originalExpiry <= now) return false;
var key = snapshot.FindUsableKey(context.ApiKeyId, now.UtcDateTime);
return key is not null && string.Equals(key.Principal, context.PrincipalId, StringComparison.OrdinalIgnoreCase)
&& DataCallerIdentity.CredentialVersionFor(key) == context.CredentialVersion
&& ReferenceEquals(snapshot, authority.Current);
}
private static UnauthorizedAccessException Denied() => new("Data authentication failed.");
}
/// <summary>Defense in depth after the pre-parse listener/authentication middleware.</summary>
public sealed class DataConnectionAuthInterceptor(IOptions<DataConnectionOptions> options,
DataConnectionAuthenticator authenticator) : Interceptor
{
public override Task<TResponse> UnaryServerHandler<TRequest, TResponse>(TRequest request,
ServerCallContext context, UnaryServerMethod<TRequest, TResponse> continuation)
{ Validate(context); return continuation(request, context); }
public override Task DuplexStreamingServerHandler<TRequest, TResponse>(IAsyncStreamReader<TRequest> requests,
IServerStreamWriter<TResponse> responses, ServerCallContext context,
DuplexStreamingServerMethod<TRequest, TResponse> continuation)
{ Validate(context); return continuation(requests, responses, context); }
private void Validate(ServerCallContext context)
{
var http = context.GetHttpContext();
if (http.Connection.LocalPort == options.Value.ListenPort && options.Value.Enabled
&& !DataConnectionEndpoints.IsDataRequest(http, options.Value))
throw new RpcException(new Status(StatusCode.PermissionDenied, "Dedicated data listener."));
if (!context.Method.StartsWith(DataConnectionEndpoints.ServicePrefix, StringComparison.Ordinal)) return;
if (!DataConnectionEndpoints.IsDataRequest(http, options.Value)
|| http.Items[typeof(DataAuthenticatedContext)] is not DataAuthenticatedContext caller
|| !authenticator.IsCurrent(caller))
throw new RpcException(new Status(StatusCode.Unauthenticated, "Data authentication failed."));
}
}
@@ -0,0 +1,111 @@
using System.Security.Cryptography.X509Certificates;
using System.Text.Json;
using Microsoft.Extensions.Hosting;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Host.Configuration;
/// <summary>Installs an applied scope in both independent local security stores.</summary>
public sealed class DataConnectionScopeActivator(DataConnectionSecretProvisioner credentials, DataConnectionTrustPolicyStore trust) : IDataConnectionScopeActivator
{
public async Task SetScopeAsync(long version, IReadOnlyDictionary<string, string> allowlist, CancellationToken cancellationToken)
{
await credentials.SetScopeAsync(version, allowlist, cancellationToken).ConfigureAwait(false);
await trust.ApplyScopeAsync(version, allowlist.Keys, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>Node-local trust bundle. Root certificates are public DER encoded in base64.</summary>
public sealed record DataConnectionTrustBundle(string OwnerCluster, string ConsumerNode, long ScopeVersion, IReadOnlyList<DataConnectionTrustBundleEntry> Entries);
/// <summary>An independently versioned trust set; an empty root set is a removal tombstone.</summary>
public sealed record DataConnectionTrustBundleEntry(string ConnectionId, long Version, IReadOnlyList<string> Roots);
/// <summary>Reports which local bundle files were successfully processed.</summary>
public sealed record DataConnectionBundleLoadResult(bool CredentialsLoaded, bool TrustLoaded);
/// <summary>Reads a restricted, atomically replaced trust bundle under a fixed byte limit.</summary>
public sealed class DataConnectionTrustBundleReader(string path)
{
public async Task<DataConnectionTrustBundle> ReadAsync(CancellationToken ct)
{
const int maximumBytes = 1024 * 1024;
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, 4096, true);
if (stream.Length > maximumBytes) throw new InvalidDataException("Trust bundle exceeds the size limit.");
using var buffer = new MemoryStream(); var bytes = new byte[8192]; int count;
while ((count = await stream.ReadAsync(bytes, ct).ConfigureAwait(false)) != 0)
{
if (buffer.Length + count > maximumBytes) throw new InvalidDataException("Trust bundle exceeds the size limit.");
buffer.Write(bytes, 0, count);
}
return JsonSerializer.Deserialize<DataConnectionTrustBundle>(buffer.GetBuffer().AsSpan(0, checked((int)buffer.Length)))
?? throw new InvalidDataException("Trust bundle is empty.");
}
}
/// <summary>Imports local credential and trust mounts independently. No bundle content is logged.</summary>
public sealed class DataConnectionBundleLoader(DataConnectionSecretProvisioner credentials, DataConnectionTrustPolicyStore trust,
string ownerCluster, string consumerNode)
{
private readonly string _owner = DataConnectionSecretProvisioner.NormalizeId(ownerCluster);
private readonly string _node = DataConnectionSecretProvisioner.NormalizeId(consumerNode);
public async Task<DataConnectionBundleLoadResult> ApplyFilesAsync(string? credentialPath, string? trustPath, CancellationToken ct)
{
var credentialsLoaded = await TryCredentialsAsync(credentialPath, ct).ConfigureAwait(false);
var trustLoaded = await TryTrustAsync(trustPath, ct).ConfigureAwait(false);
return new(credentialsLoaded, trustLoaded);
}
private async Task<bool> TryCredentialsAsync(string? path, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(path)) return false;
try
{
var bundle = await new DataConnectionBundleReader(path).ReadAsync(ct).ConfigureAwait(false);
await credentials.ApplyAsync(bundle, ct).ConfigureAwait(false);
return true;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
catch (Exception) { return false; }
}
private async Task<bool> TryTrustAsync(string? path, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(path)) return false;
var certificates = new List<X509Certificate2>();
try
{
var bundle = await new DataConnectionTrustBundleReader(path).ReadAsync(ct).ConfigureAwait(false);
if (DataConnectionSecretProvisioner.NormalizeId(bundle.OwnerCluster) != _owner || DataConnectionSecretProvisioner.NormalizeId(bundle.ConsumerNode) != _node || bundle.Entries is null)
return false;
var entries = new List<(string ConnectionId, long Version, X509Certificate2[] Roots)>();
foreach (var entry in bundle.Entries)
{
var roots = new List<X509Certificate2>();
foreach (var encoded in entry.Roots)
{
var cert = X509CertificateLoader.LoadCertificate(Convert.FromBase64String(encoded));
certificates.Add(cert); roots.Add(cert);
}
entries.Add((entry.ConnectionId, entry.Version, roots.ToArray()));
}
await trust.SetBundleAsync(entries, bundle.ScopeVersion, ct).ConfigureAwait(false);
return true;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
catch (Exception) { return false; }
finally { foreach (var certificate in certificates) certificate.Dispose(); }
}
}
/// <summary>Retries local mounts without treating a missing mount as a revocation.</summary>
public sealed class DataConnectionBundleBackgroundService(DataConnectionBundleLoader loader, string? credentialPath,
string? trustPath, TimeSpan interval) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (interval <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(interval));
while (!stoppingToken.IsCancellationRequested)
{
await loader.ApplyFilesAsync(credentialPath, trustPath, stoppingToken).ConfigureAwait(false);
await Task.Delay(interval, stoppingToken).ConfigureAwait(false);
}
}
}
@@ -0,0 +1,47 @@
using ZB.MOM.WW.Secrets.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Host.Configuration;
/// <summary>A credential and its durable local version.</summary>
public sealed record DataConnectionCredential(string Value, long Version, string SecretName)
{
public override string ToString() => $"Credential version {Version} (redacted)";
}
/// <summary>Resolves only current, fully committed node-local credentials.</summary>
public sealed class DataConnectionCredentialResolver(ISecretStore store, ISecretCipher cipher, string ownerCluster, string consumerNode)
{
public async Task<bool> IsEligibleAsync(string connectionId, CancellationToken ct)
{
connectionId = DataConnectionSecretProvisioner.NormalizeId(connectionId);
await DataConnectionSecretProvisioner.Gate.WaitAsync(ct).ConfigureAwait(false);
try
{
var state = await DataConnectionSecretProvisioner.ReadStateAsync(store, cipher,
DataConnectionSecretProvisioner.GetStateName(ownerCluster, consumerNode), ct).ConfigureAwait(false);
return !state.PendingNotices.Contains(connectionId) && state.Scope.ContainsKey(connectionId);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
catch (Exception) { return false; }
finally { DataConnectionSecretProvisioner.Gate.Release(); }
}
public async Task<DataConnectionCredential?> ResolveAsync(string connectionId, CancellationToken ct)
{
connectionId = DataConnectionSecretProvisioner.NormalizeId(connectionId);
await DataConnectionSecretProvisioner.Gate.WaitAsync(ct).ConfigureAwait(false);
try
{
var state = await DataConnectionSecretProvisioner.ReadStateAsync(store, cipher,
DataConnectionSecretProvisioner.GetStateName(ownerCluster, consumerNode), ct).ConfigureAwait(false);
if (state.PendingNotices.Contains(connectionId) || !state.Scope.TryGetValue(connectionId, out var reference) || !state.Versions.TryGetValue(reference, out var version) || version.Deleted || version.Pending)
return null;
var row = await store.GetAsync(DataConnectionSecretProvisioner.StoreName(reference), ct).ConfigureAwait(false);
if (row is null) return null;
var value = cipher.Decrypt(row);
return DataConnectionSecretProvisioner.PayloadHash(value, false) != version.PayloadHash ? null : new DataConnectionCredential(value, version.Version, DataConnectionSecretProvisioner.StoreName(reference).Value);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
catch (Exception) { return null; }
finally { DataConnectionSecretProvisioner.Gate.Release(); }
}
}
@@ -0,0 +1,111 @@
using Microsoft.Extensions.Options;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Host.Configuration;
/// <summary>Actual listener isolation and bounded authentication before protobuf deserialization.</summary>
public static class DataConnectionEndpoints
{
public const string ServicePrefix = "/data_connection.v1.DataConnectionService/";
private static readonly HashSet<string> Methods = ["GetCapabilities", "Browse", "GetMetadata", "Read", "Write", "Subscribe"];
public static bool IsDataRequest(HttpContext context, DataConnectionOptions options) => options.Enabled
&& context.Connection.LocalPort == options.ListenPort
&& (context.Request.IsHttps || options.AllowDevelopmentCleartext)
&& context.Request.Protocol == "HTTP/2" && HttpMethods.IsPost(context.Request.Method)
&& options.AllowedHosts.Contains(context.Request.Host.Host, StringComparer.OrdinalIgnoreCase)
&& (context.Request.Host.Port is null || context.Request.Host.Port == options.ListenPort)
&& context.Request.Path.Value is { } path && path.StartsWith(ServicePrefix, StringComparison.Ordinal)
&& Methods.Contains(path[ServicePrefix.Length..]);
public static DataTarget RequestedTarget(HttpContext context)
{
string Required(string name)
{
var values = context.Request.Headers[name];
if (values.Count != 1 || string.IsNullOrWhiteSpace(values[0])) throw new ArgumentException("Missing data target policy.");
return values[0]!;
}
var modeText = Required("x-data-target-mode");
var consistencyText = Required("x-data-consistency");
// Parse names only: Enum.TryParse also accepts numeric enum values.
var mode = modeText switch { "Node" => DataTargetMode.Node, "Cluster" => DataTargetMode.Cluster, _ => throw new ArgumentException("Invalid target mode.") };
var consistency = consistencyText switch { "Primary" => DataConsistency.Primary, "ReadyReplica" => DataConsistency.ReadyReplica, _ => throw new ArgumentException("Invalid consistency.") };
var node = mode == DataTargetMode.Node ? Required("x-data-node-id") : null;
if (mode == DataTargetMode.Cluster && context.Request.Headers.ContainsKey("x-data-node-id"))
throw new ArgumentException("Cluster requests cannot pin a node.");
var target = new DataTarget(mode, Required("x-data-cluster-id"), node, consistency);
target.Validate();
return target;
}
public static IApplicationBuilder UseDataConnectionAdmission(this IApplicationBuilder app) => app.UseMiddleware<DataConnectionAdmissionMiddleware>();
}
/// <summary>Owns a finite admission slot until the real HTTP call ends.</summary>
public sealed class DataConnectionAdmissionMiddleware
{
private readonly RequestDelegate _next;
private readonly DataConnectionOptions _options;
private readonly SemaphoreSlim _calls;
private readonly SemaphoreSlim _streams;
public DataConnectionAdmissionMiddleware(RequestDelegate next, IOptions<DataConnectionOptions> options)
{
_next = next; _options = options.Value;
_calls = new(_options.MaxConcurrentCalls, _options.MaxConcurrentCalls);
_streams = new(_options.MaxStreams, _options.MaxStreams);
}
public async Task InvokeAsync(HttpContext context, DataConnectionAuthenticator authenticator)
{
var path = context.Request.Path.Value ?? "";
var dataPath = path.StartsWith(DataConnectionEndpoints.ServicePrefix, StringComparison.Ordinal);
var dataPort = _options.Enabled && context.Connection.LocalPort == _options.ListenPort;
if (!dataPath && !dataPort) { await _next(context).ConfigureAwait(false); return; }
if (!DataConnectionEndpoints.IsDataRequest(context, _options)) { Reject(context, 7); return; }
var isStream = path == DataConnectionEndpoints.ServicePrefix + "Subscribe";
var admission = isStream ? _streams : _calls;
if (!await admission.WaitAsync(0, context.RequestAborted).ConfigureAwait(false)) { Reject(context, 8); return; }
try
{
var authorization = context.Request.Headers.Authorization;
if (authorization.Count != 1 || authorization[0] is not { } header
|| !header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)
|| header.Length > 4096 || header[7..].Any(char.IsWhiteSpace)) { Reject(context, 16); return; }
try
{
context.Items[typeof(DataAuthenticatedContext)] = authenticator.Authenticate(header[7..]);
context.Items[typeof(DataTarget)] = DataConnectionEndpoints.RequestedTarget(context);
}
catch (UnauthorizedAccessException) { Reject(context, 16); return; }
catch (ArgumentException) { Reject(context, 3); return; }
if (isStream)
{
// The stream engine owns finite pre-Open/session lifetime and command deadlines.
await _next(context).ConfigureAwait(false);
}
else
{
// Starts before protobuf parsing and stays alive through serialization/writing.
// A caller that omits grpc-timeout cannot pin a unary parse/admission slot forever.
var originalAbort = context.RequestAborted;
context.Items[typeof(Grpc.DataConnectionUnaryLifetime)] = new Grpc.DataConnectionUnaryLifetime(TimeProvider.System, _options.UnaryTimeout);
using var deadline = new CancellationTokenSource(_options.UnaryTimeout);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(originalAbort, deadline.Token);
using var abort = deadline.Token.Register(static state => ((HttpContext)state!).Abort(), context);
context.RequestAborted = linked.Token;
try { await _next(context).ConfigureAwait(false); }
finally { context.RequestAborted = originalAbort; }
}
}
finally { admission.Release(); }
}
private static void Reject(HttpContext context, int grpcStatus)
{
context.Response.StatusCode = StatusCodes.Status200OK;
context.Response.ContentType = "application/grpc";
context.Response.Headers["grpc-status"] = grpcStatus.ToString(System.Globalization.CultureInfo.InvariantCulture);
context.Response.Headers["grpc-message"] = "Data request refused.";
}
}
@@ -0,0 +1,28 @@
namespace ZB.MOM.WW.OtOpcUa.Host.Configuration;
/// <summary>Dedicated data-plane listener and finite transport admission limits.</summary>
public sealed class DataConnectionOptions
{
public const string SectionName = "DataConnections";
public bool Enabled { get; set; }
public int ListenPort { get; set; }
public string ListenAddress { get; set; } = "0.0.0.0";
public string[] AllowedHosts { get; set; } = [];
public string? CertificatePath { get; set; }
public string? CertificateKeyPath { get; set; }
public bool AllowDevelopmentCleartext { get; set; }
public int MaxMessageBytes { get; set; } = 1_048_576;
public int MaxConcurrentCalls { get; set; } = 64;
public int MaxStreams { get; set; } = 256;
public int MaxStreamsPerPrincipal { get; set; } = 8;
public int MaxMonitoredItems { get; set; } = 10_000;
public long MaxTransportBytes { get; set; } = 64 * 1024 * 1024;
public long MaxPendingBytes { get; set; } = 1024 * 1024;
public TimeSpan MaxSessionLifetime { get; set; } = TimeSpan.FromHours(1);
public ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.DataResourceLimits Hub { get; set; } = new();
public TimeSpan UnaryTimeout { get; set; } = TimeSpan.FromSeconds(30);
public TimeSpan StreamCommandTimeout { get; set; } = TimeSpan.FromSeconds(5);
public string? CredentialBundlePath { get; set; }
public string? TrustBundlePath { get; set; }
public TimeSpan BundleRefreshInterval { get; set; } = TimeSpan.FromSeconds(1);
}
@@ -0,0 +1,44 @@
using System.Net;
using Microsoft.Extensions.Options;
namespace ZB.MOM.WW.OtOpcUa.Host.Configuration;
/// <summary>Rejects ambiguous listener identity and insecure production transport.</summary>
public sealed class DataConnectionOptionsValidator(IHostEnvironment environment) : IValidateOptions<DataConnectionOptions>
{
public ValidateOptionsResult Validate(string? name, DataConnectionOptions options)
{
var errors = Validate(options, environment.IsDevelopment());
return errors.Count == 0 ? ValidateOptionsResult.Success : ValidateOptionsResult.Fail(errors);
}
public static IReadOnlyList<string> Validate(DataConnectionOptions options, bool development)
{
ArgumentNullException.ThrowIfNull(options);
if (!options.Enabled) return [];
var errors = new List<string>();
if (options.ListenPort is < 1 or > 65535) errors.Add("DataConnections:ListenPort must be a dedicated port.");
if (!IPAddress.TryParse(options.ListenAddress, out var address)) errors.Add("DataConnections:ListenAddress must be an IP literal.");
if (options.AllowedHosts is not { Length: > 0 } || options.AllowedHosts.Any(host =>
string.IsNullOrWhiteSpace(host) || Uri.CheckHostName(host) == UriHostNameType.Unknown))
errors.Add("DataConnections:AllowedHosts must name the dedicated endpoint hosts.");
if (options.AllowDevelopmentCleartext)
{
if (!development || address is null || !IPAddress.IsLoopback(address))
errors.Add("Cleartext data transport requires Development and a literal loopback listener.");
}
else if (string.IsNullOrWhiteSpace(options.CertificatePath)) errors.Add("A data-plane TLS certificate is required.");
if (options.MaxMessageBytes is < 1024 or > 16_777_216 || options.MaxConcurrentCalls is < 1 or > 4096)
errors.Add("Data-plane parse and concurrency limits are outside supported bounds.");
if (options.MaxStreams is < 1 or > 4096 || options.MaxStreamsPerPrincipal <= 0 || options.MaxMonitoredItems <= 0
|| options.MaxPendingBytes <= 0 || options.MaxPendingBytes > options.MaxTransportBytes
|| options.MaxSessionLifetime <= TimeSpan.Zero || options.MaxSessionLifetime > TimeSpan.FromDays(1)
|| options.Hub is null || options.BundleRefreshInterval < TimeSpan.FromMilliseconds(100)
|| options.BundleRefreshInterval > TimeSpan.FromMinutes(1))
errors.Add("Data-plane retained work and refresh limits are invalid.");
if (options.UnaryTimeout <= TimeSpan.Zero || options.UnaryTimeout > TimeSpan.FromMinutes(5)
|| options.StreamCommandTimeout <= TimeSpan.Zero || options.StreamCommandTimeout > TimeSpan.FromMinutes(1))
errors.Add("Unary and stream-command timeouts must be finite and within supported limits.");
return errors;
}
}
@@ -0,0 +1,173 @@
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.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.");
services.TryAddSingleton<TimeProvider>(TimeProvider.System);
services.TryAddSingleton<DataWriteDispatchFence>();
services.TryAddSingleton<DataConnectionWarmRoleView>();
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>()));
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 = CaptureRole(role, warm);
var servingRole = settings.IsWarm && state.WarmRole != WarmRole.Active ? "Standby" : state.Role;
return new(identity.NodeId, identity.Incarnation, servingRole, 0, 0, state.Generation);
});
});
services.AddSingleton(sp => new PartitionedSampleHub(options.Hub, sp.GetRequiredService<TimeProvider>()));
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(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)));
});
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<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 = CaptureRole(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);
});
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;
}
private static (string Role, long Generation, WarmRole? WarmRole) CaptureRole(RedundancyRoleView role, DataConnectionWarmRoleView warm)
{
if (!ReferenceEquals(role.DispatchFence, warm.DispatchFence) || !role.DispatchFence.TryEnter(out var lease))
return ("Unknown", 0, null);
using (lease)
{
var observed = role.DataServingRole;
var primaryGeneration = role.PrimaryGeneration;
var verdict = warm.Snapshot;
if (primaryGeneration == long.MaxValue || verdict.Generation == long.MaxValue
|| primaryGeneration > long.MaxValue - verdict.Generation) return ("Unknown", long.MaxValue, null);
return (observed, primaryGeneration + verdict.Generation, verdict.Role);
}
}
private sealed class DeferredFactory(Func<IDataConnectionFactory> resolve) : IDataConnectionFactory
{
public IDataConnection Create(DataAuthenticatedContext context, DataTarget target) => resolve().Create(context, target);
}
}
@@ -0,0 +1,27 @@
using ZB.MOM.WW.Secrets.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Host.Configuration;
/// <summary>Dependency-free broadcaster composed with the existing secret invalidation chain.</summary>
public sealed class DataConnectionSecretChangeHandler
{
public event Action<SecretName>? SecretChanged;
public event Action<string>? ConnectionChanged;
public void NotifySecretChanged(SecretName name) => Broadcast(SecretChanged, name);
public void NotifyConnectionChanged(string connectionId) => Broadcast(ConnectionChanged, connectionId);
internal static void Broadcast<T>(Action<T>? handlers, T value)
{
List<Exception>? failures = null;
if (handlers is not null)
foreach (Action<T> handler in handlers.GetInvocationList())
try { handler(value); } catch (Exception ex) { (failures ??= []).Add(ex); }
if (failures is not null) throw new AggregateException(failures);
}
internal void NotifyConnectionsChanged(IEnumerable<string> connections)
{
List<Exception>? failures = null;
foreach (var connection in connections.Distinct(StringComparer.Ordinal))
try { NotifyConnectionChanged(connection); } catch (Exception ex) { (failures ??= []).Add(ex); }
if (failures is not null) throw new AggregateException(failures);
}
}
@@ -0,0 +1,218 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using ZB.MOM.WW.Secrets.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Host.Configuration;
/// <summary>A restricted, node-local credential bundle. Never serialize into deployment artifacts.</summary>
public sealed record DataConnectionCredentialBundle(string OwnerCluster, string ConsumerNode, long Version, IReadOnlyList<DataConnectionCredentialEntry> Entries, long ScopeVersion = 0);
/// <summary>A bundle entry, including an explicit deletion marker.</summary>
public sealed record DataConnectionCredentialEntry(string ConnectionId, string SecretReference, string? Value, bool Deleted)
{
public override string ToString() => $"Credential entry {ConnectionId} (redacted)";
}
internal sealed class DataCredentialState
{
public long ScopeVersion { get; set; }
public Dictionary<string, string> Scope { get; set; } = new(StringComparer.Ordinal);
public Dictionary<string, DataCredentialVersion> Versions { get; set; } = new(StringComparer.Ordinal);
public HashSet<string> PendingDeletes { get; set; } = new(StringComparer.Ordinal);
public HashSet<string> PendingNotices { get; set; } = new(StringComparer.Ordinal);
}
internal sealed class DataCredentialVersion
{
public long Version { get; set; }
public bool Deleted { get; set; }
public bool Pending { get; set; }
public string? PayloadHash { get; set; }
public long ScopeVersion { get; set; }
}
/// <summary>Imports local bundles into the encrypted local secret store with durable revocation state.</summary>
public sealed class DataConnectionSecretProvisioner
{
public const int MaximumReferences = 256;
internal static string PayloadHash(string? value, bool deleted) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(deleted ? "D" : "V" + value)));
internal static readonly SemaphoreSlim Gate = new(1, 1);
private readonly ISecretStore _store;
private readonly ISecretCipher _cipher;
private readonly ISecretCacheInvalidator _invalidator;
private readonly DataConnectionSecretChangeHandler _changes;
private readonly string _owner;
private readonly string _node;
internal readonly SecretName StateName;
public DataConnectionSecretProvisioner(ISecretStore store, ISecretCipher cipher, ISecretCacheInvalidator invalidator,
DataConnectionSecretChangeHandler changes, string ownerCluster, string consumerNode)
{
_store = store; _cipher = cipher; _invalidator = invalidator; _changes = changes;
_owner = NormalizeId(ownerCluster); _node = NormalizeId(consumerNode);
StateName = GetStateName(ownerCluster, consumerNode);
}
internal static string NormalizeId(string value) => !string.IsNullOrWhiteSpace(value)
? value.ToUpperInvariant() : throw new ArgumentException("Identity must be nonempty.", nameof(value));
internal static SecretName StoreName(string reference)
{
if (reference is null || !System.Text.RegularExpressions.Regex.IsMatch(reference, @"\Asecret:data/[a-z0-9][a-z0-9._/-]*\z", System.Text.RegularExpressions.RegexOptions.CultureInvariant)
|| reference.Contains("..", StringComparison.Ordinal))
throw new InvalidOperationException("Invalid canonical data secret reference.");
return new SecretName(reference["secret:".Length..]);
}
internal static SecretName GetStateName(string owner, string node) => new("data-connection/state/" +
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(NormalizeId(owner) + "\0" + NormalizeId(node)))).ToLowerInvariant());
internal static async Task<DataCredentialState> ReadStateAsync(ISecretStore store, ISecretCipher cipher, SecretName name, CancellationToken ct)
{
var row = await store.GetAsync(name, ct).ConfigureAwait(false);
return row is null ? new DataCredentialState() : JsonSerializer.Deserialize<DataCredentialState>(cipher.Decrypt(row))
?? throw new InvalidOperationException("Invalid data credential state.");
}
private Task SaveAsync(DataCredentialState state, CancellationToken ct) =>
_store.UpsertAsync(_cipher.Encrypt(StateName, JsonSerializer.Serialize(state), SecretContentType.Text), ct);
/// <summary>Persists current scope before retiring removed connections.</summary>
public async Task SetScopeAsync(long version, IReadOnlyDictionary<string, string> scope, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(scope);
if (version <= 0 || scope.Any(x => string.IsNullOrWhiteSpace(x.Key) || string.IsNullOrWhiteSpace(x.Value) || x.Value.StartsWith("data-connection/", StringComparison.Ordinal)))
throw new ArgumentException("Invalid scope.", nameof(scope));
var canonical = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var pair in scope)
{
_ = StoreName(pair.Value);
if (!canonical.TryAdd(NormalizeId(pair.Key), pair.Value)) throw new InvalidOperationException("Duplicate connection identity.");
}
scope = canonical;
if (scope.Count > MaximumReferences || scope.Values.Distinct(StringComparer.Ordinal).Count() > MaximumReferences)
throw new InvalidOperationException("Scope capacity exceeded.");
await Gate.WaitAsync(ct).ConfigureAwait(false);
try
{
var state = await ReadStateAsync(_store, _cipher, StateName, ct).ConfigureAwait(false);
if (version == state.ScopeVersion && scope.Count == state.Scope.Count &&
scope.All(pair => state.Scope.TryGetValue(pair.Key, out var existing) && existing == pair.Value))
{
await CompleteNoticesAsync(state, ct).ConfigureAwait(false);
await CompleteDeletesAsync(state, ct).ConfigureAwait(false);
return;
}
if (version <= state.ScopeVersion) throw new InvalidOperationException("Scope version must increase.");
var old = state.Scope;
state.Scope = new Dictionary<string, string>(scope, StringComparer.Ordinal);
state.ScopeVersion = version;
var orphaned = old.Values.Except(state.Scope.Values, StringComparer.Ordinal).ToArray();
foreach (var reference in orphaned)
if (state.Versions.TryGetValue(reference, out var retired)) { retired.Deleted = true; retired.Pending = false; }
foreach (var pair in old.Where(p => !state.Scope.TryGetValue(p.Key, out var reference) || reference != p.Value))
state.PendingNotices.Add(pair.Key);
foreach (var reference in orphaned) state.PendingDeletes.Add(reference);
if (state.PendingNotices.Count > MaximumReferences || state.PendingDeletes.Count > MaximumReferences)
throw new InvalidOperationException("Pending retirement capacity exceeded.");
// A reintroduced reference stays denied by its tombstone, but is no longer safe to delete.
state.PendingDeletes.ExceptWith(state.Scope.Values);
await SaveAsync(state, ct).ConfigureAwait(false);
await CompleteNoticesAsync(state, ct).ConfigureAwait(false);
await CompleteDeletesAsync(state, ct).ConfigureAwait(false);
}
finally { Gate.Release(); }
}
private async Task CompleteNoticesAsync(DataCredentialState state, CancellationToken ct)
{
if (state.PendingNotices.Count == 0) return;
_changes.NotifyConnectionsChanged(state.PendingNotices);
state.PendingNotices.Clear();
await SaveAsync(state, ct).ConfigureAwait(false);
}
private async Task CompleteDeletesAsync(DataCredentialState state, CancellationToken ct)
{
foreach (var reference in state.PendingDeletes.ToArray())
{
if (state.Scope.Values.Contains(reference, StringComparer.Ordinal)) continue;
await _store.DeleteAsync(StoreName(reference), "data-connection", ct).ConfigureAwait(false);
_invalidator.Invalidate(StoreName(reference));
state.PendingDeletes.Remove(reference);
state.Versions.Remove(reference);
await SaveAsync(state, ct).ConfigureAwait(false);
}
}
/// <summary>Validates node, scope and monotonic versions before importing a bundle.</summary>
public async Task ApplyAsync(DataConnectionCredentialBundle bundle, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(bundle);
if (NormalizeId(bundle.OwnerCluster) != _owner || NormalizeId(bundle.ConsumerNode) != _node || bundle.Version <= 0 || bundle.Entries is null)
throw new InvalidOperationException("Bundle scope is invalid.");
await Gate.WaitAsync(ct).ConfigureAwait(false);
try
{
var state = await ReadStateAsync(_store, _cipher, StateName, ct).ConfigureAwait(false);
if (bundle.ScopeVersion <= 0 || bundle.ScopeVersion != state.ScopeVersion) throw new InvalidOperationException("Bundle scope generation is stale.");
if (bundle.Entries.Count > MaximumReferences || state.Versions.Count + bundle.Entries.Count(e => !state.Versions.ContainsKey(e.SecretReference)) > MaximumReferences)
throw new InvalidOperationException("Credential history capacity exceeded.");
var seen = new HashSet<string>(StringComparer.Ordinal);
var pending = new List<DataConnectionCredentialEntry>();
foreach (var entry in bundle.Entries)
{
if (!seen.Add(entry.SecretReference) || !state.Scope.TryGetValue(NormalizeId(entry.ConnectionId), out var reference) || reference != entry.SecretReference ||
(!entry.Deleted && string.IsNullOrEmpty(entry.Value)))
throw new InvalidOperationException("Bundle entry is invalid or unauthorized.");
if (state.Versions.TryGetValue(reference, out var current) && bundle.Version <= current.Version)
{
if (bundle.Version != current.Version || current.ScopeVersion != bundle.ScopeVersion ||
current.Deleted != entry.Deleted || current.PayloadHash != PayloadHash(entry.Value, entry.Deleted))
throw new InvalidOperationException("Bundle entry is stale or differs from the committed version.");
if (!current.Pending)
{
var row = await _store.GetAsync(StoreName(reference), ct).ConfigureAwait(false);
if (entry.Deleted ? row is not null : row is null || PayloadHash(_cipher.Decrypt(row), false) != current.PayloadHash)
throw new InvalidOperationException("Committed credential no longer matches its version.");
continue;
}
}
pending.Add(entry);
}
if (pending.Count == 0) return;
// Persist denial first: interruption, encryption failure or partial writes cannot expose mixed state.
foreach (var entry in pending)
state.Versions[entry.SecretReference] = new DataCredentialVersion { Version = bundle.Version, Deleted = entry.Deleted, Pending = true, PayloadHash = PayloadHash(entry.Value, entry.Deleted), ScopeVersion = bundle.ScopeVersion };
await SaveAsync(state, ct).ConfigureAwait(false);
var changedReferences = pending.Select(e => e.SecretReference).ToHashSet(StringComparer.Ordinal);
_changes.NotifyConnectionsChanged(state.Scope.Where(p => changedReferences.Contains(p.Value)).Select(p => p.Key));
foreach (var entry in pending)
{
var name = StoreName(entry.SecretReference);
if (entry.Deleted) await _store.DeleteAsync(name, "data-connection", ct).ConfigureAwait(false);
else await _store.UpsertAsync(_cipher.Encrypt(name, entry.Value!, SecretContentType.Text) with
{ Description = "Node-local data connection credential", CreatedBy = "data-connection", UpdatedBy = "data-connection" }, ct).ConfigureAwait(false);
_invalidator.Invalidate(name);
}
foreach (var entry in pending) state.Versions[entry.SecretReference].Pending = false;
await SaveAsync(state, ct).ConfigureAwait(false);
}
finally { Gate.Release(); }
}
}
/// <summary>Reads one bounded, locally mounted JSON bundle; deployment artifacts do not contain its contents.</summary>
public sealed class DataConnectionBundleReader(string path)
{
public async Task<DataConnectionCredentialBundle> ReadAsync(CancellationToken ct)
{
const int maximumBytes = 1024 * 1024;
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, 4096, true);
if (stream.Length > maximumBytes) throw new InvalidDataException("Credential bundle exceeds the size limit.");
using var buffer = new MemoryStream();
var bytes = new byte[8192];
int count;
while ((count = await stream.ReadAsync(bytes, ct).ConfigureAwait(false)) != 0)
{
if (buffer.Length + count > maximumBytes) throw new InvalidDataException("Credential bundle exceeds the size limit.");
buffer.Write(bytes, 0, count);
}
return JsonSerializer.Deserialize<DataConnectionCredentialBundle>(buffer.GetBuffer().AsSpan(0, checked((int)buffer.Length)))
?? throw new InvalidDataException("Credential bundle is empty.");
}
}
@@ -0,0 +1,63 @@
using System.Collections.Concurrent;
using System.Globalization;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.Secrets.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Host.Configuration;
/// <summary>Adapts node-local credentials and trust to runtime channel security.</summary>
public sealed class DataConnectionSecurityProvider : IDataConnectionSecurityProvider, IDisposable
{
private readonly DataConnectionCredentialResolver _credentials;
private readonly DataConnectionTrustPolicyStore _trust;
private readonly DataConnectionSecretChangeHandler _changes;
private readonly ConcurrentDictionary<string, string> _observed = new(StringComparer.Ordinal);
private long _generation;
public DataConnectionSecurityProvider(DataConnectionCredentialResolver credentials, DataConnectionTrustPolicyStore trust, DataConnectionSecretChangeHandler changes)
{
_credentials = credentials; _trust = trust; _changes = changes;
changes.ConnectionChanged += OnConnectionChanged;
changes.SecretChanged += OnSecretChanged;
}
public event Action<string>? Changed;
internal Func<Task>? AfterEligibilityForTest { get; set; }
internal int ObservedCountForTest => _observed.Count;
public async ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken)
{
if (endpoint.Scheme != Uri.UriSchemeHttps) return null;
connectionId = DataConnectionSecretProvisioner.NormalizeId(connectionId);
long generation;
lock (_observed) generation = _generation;
if (!await _credentials.IsEligibleAsync(connectionId, cancellationToken).ConfigureAwait(false)) return null;
if (AfterEligibilityForTest is { } pause) await pause().ConfigureAwait(false);
var credential = await _credentials.ResolveAsync(connectionId, cancellationToken).ConfigureAwait(false);
var trust = await _trust.ResolveAsync(connectionId, cancellationToken).ConfigureAwait(false);
if (credential is null || trust is null) return null;
lock (_observed)
{
// Any scope, credential or trust signal during resolution invalidates the whole snapshot.
if (_generation != generation) return null;
if (!_observed.ContainsKey(connectionId) && _observed.Count >= DataConnectionSecretProvisioner.MaximumReferences) return null;
_observed[connectionId] = credential.SecretName;
}
return new DataConnectionSecurity(credential.Version.ToString(CultureInfo.InvariantCulture),
trust.Version.ToString(CultureInfo.InvariantCulture) + ":" + trust.Fingerprint, credential.Value, trust.CreateHandler);
}
private void OnConnectionChanged(string connectionId)
{
connectionId = DataConnectionSecretProvisioner.NormalizeId(connectionId);
lock (_observed) { checked { _generation++; } _observed.TryRemove(connectionId, out _); }
DataConnectionSecretChangeHandler.Broadcast(Changed, connectionId);
}
// Compare the physical name captured during resolution; never read the store in an invalidation callback.
private void OnSecretChanged(SecretName name)
{
string[] ids;
lock (_observed) { checked { _generation++; } ids = _observed.Where(pair => string.Equals(pair.Value, name.Value, StringComparison.Ordinal)).Select(pair => pair.Key).ToArray(); }
List<Exception>? failures = null;
foreach (var id in ids)
try { OnConnectionChanged(id); } catch (Exception ex) { (failures ??= []).Add(ex); }
if (failures is not null) throw new AggregateException(failures);
}
public void Dispose() { _changes.ConnectionChanged -= OnConnectionChanged; _changes.SecretChanged -= OnSecretChanged; }
}
@@ -0,0 +1,25 @@
using System.Security.Cryptography.X509Certificates;
namespace ZB.MOM.WW.OtOpcUa.Host.Configuration;
/// <summary>Loads the dedicated listener certificate once; server rotation uses a rolling restart.</summary>
internal static class DataConnectionServerCertificate
{
internal static X509Certificate2 Load(DataConnectionOptions options)
{
var path = options.CertificatePath ?? throw new InvalidOperationException("Missing data listener certificate.");
var certificate = Path.GetExtension(path).Equals(".pfx", StringComparison.OrdinalIgnoreCase)
|| Path.GetExtension(path).Equals(".p12", StringComparison.OrdinalIgnoreCase)
? X509CertificateLoader.LoadPkcs12FromFile(path, null)
: X509Certificate2.CreateFromPemFile(path, options.CertificateKeyPath ?? path);
try
{
if (!certificate.HasPrivateKey || certificate.NotBefore.ToUniversalTime() > DateTime.UtcNow
|| certificate.NotAfter.ToUniversalTime() <= DateTime.UtcNow
|| options.AllowedHosts.Any(host => !certificate.MatchesHostname(host.Trim('[', ']'), allowCommonName: false)))
throw new InvalidOperationException("Data listener certificate must have a current private key and SANs for every allowed host.");
return certificate;
}
catch { certificate.Dispose(); throw; }
}
}
@@ -0,0 +1,175 @@
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace ZB.MOM.WW.OtOpcUa.Host.Configuration;
/// <summary>Immutable custom-root trust for an outbound channel; hostname validation remains mandatory.</summary>
public sealed class DataConnectionTrustPolicy
{
private readonly X509Certificate2[] _roots;
public DataConnectionTrustPolicy(long version, IEnumerable<X509Certificate2> roots)
{
if (version <= 0) throw new ArgumentOutOfRangeException(nameof(version));
Version = version;
_roots = roots.Select(c => X509CertificateLoader.LoadCertificate(c.RawData)).ToArray();
if (_roots.Length == 0) throw new ArgumentException("At least one trust root is required.", nameof(roots));
var hashes = _roots.Select(c => Convert.ToHexString(SHA256.HashData(c.RawData))).Order(StringComparer.Ordinal);
Fingerprint = Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(string.Join(";", hashes))));
}
public long Version { get; }
public string Fingerprint { get; }
public HttpMessageHandler CreateHandler() => new HttpClientHandler { ServerCertificateCustomValidationCallback = Validate };
internal bool Validate(HttpRequestMessage request, X509Certificate2? certificate, X509Chain? suppliedChain, SslPolicyErrors errors)
{
if (certificate is null || (errors & (SslPolicyErrors.RemoteCertificateNameMismatch | SslPolicyErrors.RemoteCertificateNotAvailable)) != 0) return false;
if (request.RequestUri is null || !certificate.MatchesHostname(request.RequestUri.IdnHost, allowWildcards: true, allowCommonName: false)) return false;
using var chain = new X509Chain();
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.1"));
chain.ChainPolicy.CustomTrustStore.AddRange(_roots);
if (suppliedChain is not null)
foreach (var element in suppliedChain.ChainElements.Cast<X509ChainElement>().Skip(1)) chain.ChainPolicy.ExtraStore.Add(element.Certificate);
return chain.Build(certificate);
}
}
/// <summary>Persists independent per-connection trust versions and explicit removal markers.</summary>
public sealed class DataConnectionTrustPolicyStore(
ZB.MOM.WW.Secrets.Abstractions.ISecretStore store,
ZB.MOM.WW.Secrets.Abstractions.ISecretCipher cipher,
DataConnectionSecretChangeHandler changes, string ownerCluster, string consumerNode)
{
public const int MaximumConnections = 256;
public const int MaximumRootCertificates = 256;
public const long MaximumTrustBytes = 1024 * 1024;
private readonly ZB.MOM.WW.Secrets.Abstractions.SecretName _name = new("data-connection/trust/" +
Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(DataConnectionSecretProvisioner.NormalizeId(ownerCluster) + "\0" + DataConnectionSecretProvisioner.NormalizeId(consumerNode)))).ToLowerInvariant());
private sealed class Entry { public long Version { get; set; } public string[]? Roots { get; set; } public bool PendingNotice { get; set; } public bool Retired { get; set; } public long ScopeVersion { get; set; } }
private sealed class State
{
public long ScopeVersion { get; set; }
public HashSet<string> Scope { get; set; } = new(StringComparer.Ordinal);
public Dictionary<string, Entry> Entries { get; set; } = new(StringComparer.Ordinal);
public HashSet<string> PendingNotices { get; set; } = new(StringComparer.Ordinal);
}
private async Task<State> ReadAsync(CancellationToken ct)
{
var row = await store.GetAsync(_name, ct).ConfigureAwait(false);
return row is null ? new State() : System.Text.Json.JsonSerializer.Deserialize<State>(cipher.Decrypt(row))
?? throw new InvalidOperationException("Invalid trust state.");
}
private Task SaveAsync(State state, CancellationToken ct) => store.UpsertAsync(cipher.Encrypt(_name,
System.Text.Json.JsonSerializer.Serialize(state), ZB.MOM.WW.Secrets.Abstractions.SecretContentType.Text), ct);
private async Task CompleteScopeAsync(State state, CancellationToken ct)
{
if (state.PendingNotices.Count > 0) changes.NotifyConnectionsChanged(state.PendingNotices);
state.PendingNotices.Clear();
foreach (var id in state.Entries.Where(pair => pair.Value.Retired || !state.Scope.Contains(pair.Key)).Select(pair => pair.Key).ToArray()) state.Entries.Remove(id);
await SaveAsync(state, ct).ConfigureAwait(false);
}
/// <summary>Persist the authoritative applied scope revision before retiring old trust identities.</summary>
public async Task ApplyScopeAsync(long scopeVersion, IEnumerable<string> connectionIds, CancellationToken ct)
{
var scope = new HashSet<string>(StringComparer.Ordinal);
foreach (var id in connectionIds)
if (!scope.Add(DataConnectionSecretProvisioner.NormalizeId(id))) throw new InvalidOperationException("Duplicate connection identity.");
if (scopeVersion <= 0 || scope.Count > MaximumConnections || scope.Any(string.IsNullOrWhiteSpace)) throw new InvalidOperationException("Invalid trust scope.");
await DataConnectionSecretProvisioner.Gate.WaitAsync(ct).ConfigureAwait(false);
try
{
var state = await ReadAsync(ct).ConfigureAwait(false);
if (scopeVersion == state.ScopeVersion && scope.SetEquals(state.Scope)) { await CompleteScopeAsync(state, ct).ConfigureAwait(false); return; }
if (scopeVersion <= state.ScopeVersion) throw new InvalidOperationException("Trust scope version must increase.");
var removed = state.Scope.Except(scope).ToArray();
state.PendingNotices.UnionWith(removed);
foreach (var id in removed) if (state.Entries.TryGetValue(id, out var retired)) retired.Retired = true;
if (state.PendingNotices.Count > MaximumConnections) throw new InvalidOperationException("Trust retirement capacity exceeded.");
state.Scope = scope; state.ScopeVersion = scopeVersion;
await SaveAsync(state, ct).ConfigureAwait(false);
await CompleteScopeAsync(state, ct).ConfigureAwait(false);
}
finally { DataConnectionSecretProvisioner.Gate.Release(); }
}
/// <summary>Atomically updates trust, or persists a tombstone when roots is empty.</summary>
public Task SetAsync(string connectionId, long version, IEnumerable<X509Certificate2> roots, long scopeVersion, CancellationToken ct) =>
SetBundleCoreAsync([(connectionId, version, roots.ToArray())], scopeVersion, false, ct);
/// <summary>Atomically stages all trust changes before retiring channels and committing the batch.</summary>
public Task SetBundleAsync(IReadOnlyList<(string ConnectionId, long Version, X509Certificate2[] Roots)> entries, long scopeVersion, CancellationToken ct) =>
SetBundleCoreAsync(entries, scopeVersion, true, ct);
private async Task SetBundleCoreAsync(IReadOnlyList<(string ConnectionId, long Version, X509Certificate2[] Roots)> entries, long scopeVersion, bool allowCompletedReplay, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(entries);
if (entries.Count > MaximumConnections) throw new InvalidOperationException("Trust bundle capacity exceeded.");
var rootCount = 0; long totalBytes = 0;
foreach (var entry in entries)
{
ArgumentNullException.ThrowIfNull(entry.Roots);
foreach (var root in entry.Roots)
{
ArgumentNullException.ThrowIfNull(root);
rootCount = checked(rootCount + 1);
totalBytes = checked(totalBytes + root.RawData.Length);
if (rootCount > MaximumRootCertificates || totalBytes > MaximumTrustBytes)
throw new InvalidOperationException("Trust bundle capacity exceeded.");
}
}
var items = entries.Select(e => (ConnectionId: DataConnectionSecretProvisioner.NormalizeId(e.ConnectionId), e.Version,
Roots: e.Roots.Select(c => Convert.ToBase64String(c.RawData)).ToArray())).ToArray();
if (items.Any(e => e.Version <= 0) || items.Select(e => e.ConnectionId).Distinct(StringComparer.Ordinal).Count() != items.Length)
throw new InvalidOperationException("Invalid or duplicate trust entry.");
await DataConnectionSecretProvisioner.Gate.WaitAsync(ct).ConfigureAwait(false);
try
{
var state = await ReadAsync(ct).ConfigureAwait(false);
if (scopeVersion <= 0 || state.ScopeVersion != scopeVersion) throw new InvalidOperationException("Trust scope is stale.");
var pending = new List<(string ConnectionId, long Version, string[] Roots)>();
foreach (var item in items)
{
if (!state.Scope.Contains(item.ConnectionId) || state.PendingNotices.Contains(item.ConnectionId))
throw new InvalidOperationException("Trust scope is unavailable.");
if (state.Entries.TryGetValue(item.ConnectionId, out var old) && item.Version <= old.Version)
{
if (item.Version != old.Version || old.ScopeVersion != scopeVersion || old.Retired ||
old.Roots is null || !old.Roots.SequenceEqual(item.Roots, StringComparer.Ordinal))
throw new InvalidOperationException("Trust version is stale or differs from the committed version.");
if (!old.PendingNotice)
{
if (!allowCompletedReplay) throw new InvalidOperationException("Trust version must increase.");
continue;
}
}
pending.Add(item);
}
if (state.Entries.Count + pending.Count(e => !state.Entries.ContainsKey(e.ConnectionId)) > MaximumConnections)
throw new InvalidOperationException("Trust history capacity exceeded.");
if (pending.Count == 0) return;
foreach (var item in pending)
state.Entries[item.ConnectionId] = new Entry { Version = item.Version, Roots = item.Roots, PendingNotice = true, ScopeVersion = scopeVersion };
await SaveAsync(state, ct).ConfigureAwait(false);
changes.NotifyConnectionsChanged(pending.Select(x => x.ConnectionId));
foreach (var item in pending) state.Entries[item.ConnectionId].PendingNotice = false;
await SaveAsync(state, ct).ConfigureAwait(false);
}
finally { DataConnectionSecretProvisioner.Gate.Release(); }
}
public async Task<DataConnectionTrustPolicy?> ResolveAsync(string connectionId, CancellationToken ct)
{
connectionId = DataConnectionSecretProvisioner.NormalizeId(connectionId);
await DataConnectionSecretProvisioner.Gate.WaitAsync(ct).ConfigureAwait(false);
try
{
var state = await ReadAsync(ct).ConfigureAwait(false);
if (!state.Scope.Contains(connectionId) || state.PendingNotices.Contains(connectionId) || !state.Entries.TryGetValue(connectionId, out var entry) || entry.PendingNotice || entry.Retired || entry.Roots is not { Length: > 0 }) return null;
var roots = entry.Roots.Select(s => X509CertificateLoader.LoadCertificate(Convert.FromBase64String(s))).ToArray();
try { return new DataConnectionTrustPolicy(entry.Version, roots); }
finally { foreach (var root in roots) root.Dispose(); }
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
catch (Exception) { return null; }
finally { DataConnectionSecretProvisioner.Gate.Release(); }
}
}
@@ -12,7 +12,7 @@ namespace ZB.MOM.WW.OtOpcUa.Host.Configuration;
/// <param name="inner">The library's invalidator (the resolver cache).</param>
/// <param name="directory">The node's directory, or null on a node that runs no drivers.</param>
internal sealed class SecretChangeSignallingInvalidator(
ISecretCacheInvalidator inner, GalaxyAckIdentityDirectory? directory) : ISecretCacheInvalidator
ISecretCacheInvalidator inner, GalaxyAckIdentityDirectory? directory, DataConnectionSecretChangeHandler? dataChanges = null) : ISecretCacheInvalidator
{
/// <summary>Gets the decorated invalidator (test seam).</summary>
internal ISecretCacheInvalidator Inner => inner;
@@ -20,7 +20,10 @@ internal sealed class SecretChangeSignallingInvalidator(
/// <inheritdoc />
public void Invalidate(SecretName name)
{
inner.Invalidate(name);
directory?.NotifySecretChanged(name);
List<Exception>? failures = null;
try { inner.Invalidate(name); } catch (Exception ex) { (failures ??= []).Add(ex); }
try { directory?.NotifySecretChanged(name); } catch (Exception ex) { (failures ??= []).Add(ex); }
try { dataChanges?.NotifySecretChanged(name); } catch (Exception ex) { (failures ??= []).Add(ex); }
if (failures is not null) throw new AggregateException(failures);
}
}
@@ -101,6 +101,7 @@ public static class SecretsRegistration
(ISecretCacheInvalidator)(existing.ImplementationInstance
?? existing.ImplementationFactory?.Invoke(sp)
?? ActivatorUtilities.CreateInstance(sp, existing.ImplementationType!)),
sp.GetService<GalaxyAckIdentityDirectory>()));
sp.GetService<GalaxyAckIdentityDirectory>(),
sp.GetService<DataConnectionSecretChangeHandler>()));
}
}
@@ -0,0 +1,91 @@
using System.Runtime.CompilerServices;
using Google.Protobuf;
using Grpc.Core;
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
namespace ZB.MOM.WW.OtOpcUa.Host.Grpc;
/// <summary>Installs the publication marshaller on the actual generated data-service binding.</summary>
public static class DataConnectionGrpcBinding
{
// ASP.NET discovery passes null and resolves overrides against this generated base type.
public static void BindService(ServiceBinderBase binder, W.DataConnectionService.DataConnectionServiceBase service) =>
W.DataConnectionService.BindService(new PublicationBinder(binder), service);
private sealed class PublicationBinder(ServiceBinderBase inner) : ServiceBinderBase
{
private static Method<TRequest, TResponse> Wrap<TRequest, TResponse>(Method<TRequest, TResponse> method)
where TRequest : class where TResponse : class => new(method.Type, method.ServiceName, method.Name,
method.RequestMarshaller, new Marshaller<TResponse>((response, context) =>
DataConnectionPublication.Serialize((IMessage)response, context), method.ResponseMarshaller.ContextualDeserializer));
public override void AddMethod<TRequest, TResponse>(Method<TRequest, TResponse> method,
UnaryServerMethod<TRequest, TResponse>? handler) => inner.AddMethod(Wrap(method), handler is null ? null :
(request, context) => { context.WriteOptions = new(WriteFlags.NoCompress); return handler(request, context); });
public override void AddMethod<TRequest, TResponse>(Method<TRequest, TResponse> method,
DuplexStreamingServerMethod<TRequest, TResponse>? handler) => inner.AddMethod(Wrap(method), handler is null ? null :
(requests, responses, context) =>
{
context.WriteOptions = new(WriteFlags.NoCompress);
responses.WriteOptions = new(WriteFlags.NoCompress);
return handler(requests, responses, context);
});
}
}
/// <summary>Call-owned bounded preparation with one final synchronous transport-buffer handoff.</summary>
public static class DataConnectionPublication
{
private static readonly ConditionalWeakTable<IMessage, Publication> Pending = new();
/// <summary>The caller must retain and dispose this registration through HTTP completion or actual stream write.</summary>
public static IDisposable Register(IMessage response, Func<bool> canPublish, int maxBytes, byte[]? prepared = null)
=> Register(response, canPublish, maxBytes, prepared, null);
internal static IDisposable RegisterUnary(IMessage response, Func<bool> canPublish, int maxBytes,
DataConnectionUnaryLifetime deadline) => Register(response, canPublish, maxBytes, null, deadline);
private static IDisposable Register(IMessage response, Func<bool> canPublish, int maxBytes, byte[]? prepared,
DataConnectionUnaryLifetime? deadline)
{
ArgumentNullException.ThrowIfNull(response); ArgumentNullException.ThrowIfNull(canPublish);
if (maxBytes <= 0 || prepared is { Length: var length } && length > maxBytes) throw new ArgumentOutOfRangeException(nameof(maxBytes));
var publication = new Publication(response, canPublish, maxBytes, prepared, deadline);
Pending.Add(response, publication);
return publication;
}
internal static void Serialize(IMessage response, SerializationContext context)
{
if (!Pending.TryGetValue(response, out var publication)) throw Refused();
publication.Serialize(context);
}
private sealed class Publication(IMessage response, Func<bool> canPublish, int maximum, byte[]? prepared,
DataConnectionUnaryLifetime? deadline) : IDisposable
{
private int _state;
public void Serialize(SerializationContext context)
{
if (Interlocked.CompareExchange(ref _state, 1, 0) != 0) throw Refused();
try
{
// Never lend the protobuf serializer the real response pipe before authorization.
if (response.CalculateSize() > maximum) throw new RpcException(new Status(StatusCode.ResourceExhausted, "Data message exceeds transport limits."));
var payload = prepared ?? response.ToByteArray();
if (payload.Length > maximum) throw new RpcException(new Status(StatusCode.ResourceExhausted, "Data message exceeds transport limits."));
var allowed = canPublish();
if (!allowed || Volatile.Read(ref _state) != 1 || deadline is { IsActive: false }) throw Refused();
// The actual service path enforces NoCompress. This synchronous Complete is
// buffer handoff, not evidence of a network flush or a remote client's receipt.
context.Complete(payload);
Interlocked.CompareExchange(ref _state, 2, 1);
}
finally { Pending.Remove(response); }
}
public void Dispose() { Interlocked.Exchange(ref _state, 3); Pending.Remove(response); }
}
private static RpcException Refused() => new(new Status(StatusCode.Unavailable, "Data publication authority changed."));
}
@@ -0,0 +1,287 @@
using Google.Protobuf;
using Grpc.Core;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
namespace ZB.MOM.WW.OtOpcUa.Host.Grpc;
/// <summary>Dedicated authenticated transport over the caller-bound origin-local ports.</summary>
[BindServiceMethod(typeof(DataConnectionGrpcBinding), nameof(DataConnectionGrpcBinding.BindService))]
public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IOptions<DataConnectionOptions> options,
DataConnectionAuthenticator authenticator) : W.DataConnectionService.DataConnectionServiceBase
{
private readonly DataConnectionOptions _options = options.Value;
public override Task<W.CapabilitiesResponse> GetCapabilities(W.CapabilitiesRequest request, ServerCallContext context) =>
Execute(context, async (connection, caller, token) =>
{
if (request.ProtocolMajor != 1) throw new RpcException(new Status(StatusCode.Unimplemented, "Incompatible protocol major."));
var budget = new DataBudget(_options.UnaryTimeout, 1, _options.MaxMessageBytes);
var capabilities = await connection.GetCapabilitiesAsync(budget, token).ConfigureAwait(false);
var response = DataProtoMapper.EncodeCapabilities(capabilities with
{ ProtocolMinor = Math.Max(2, capabilities.ProtocolMinor), ResponseServingIdentity = true, SubscriptionAgeReadiness = true });
CheckSize(response);
var current = await connection.GetCapabilitiesAsync(budget, token).ConfigureAwait(false);
if (!authenticator.IsCurrent(caller) || current.Serving != capabilities.Serving
|| current.Readiness != capabilities.Readiness || current.Operations != capabilities.Operations)
throw Unavailable();
Register(context, response, () => authenticator.IsCurrent(caller)
&& !token.IsCancellationRequested
&& connection is IDataConnectionDiscoveryGate gate && gate.CanPublishCapabilities(capabilities));
return response;
});
public override Task<W.BrowseResponse> Browse(W.BrowseRequest request, ServerCallContext context) =>
Execute(context, async (connection, caller, token) =>
{
var caps = await Ready(connection, DataOperations.Browse, token).ConfigureAwait(false);
var decoded = DataProtoMapper.DecodeBrowseRequest(request, DecodeLimits(caps));
var result = await connection.BrowseAsync(decoded with { Budget = Clamp(decoded.Budget) }, token).ConfigureAwait(false);
var response = DataProtoMapper.EncodeBrowseResponse(result);
response.Serving = DataProtoMapper.EncodeServing(caps.Serving);
CheckSize(response);
Register(context, response, () => !token.IsCancellationRequested && CanPublish(connection, caller, caps.Serving));
return response;
});
public override Task<W.MetadataResponse> GetMetadata(W.MetadataRequest request, ServerCallContext context) =>
Execute(context, async (connection, caller, token) =>
{
var caps = await Ready(connection, DataOperations.Metadata, token).ConfigureAwait(false);
var decoded = DataProtoMapper.DecodeMetadataRequest(request, DecodeLimits(caps));
var result = await connection.GetMetadataAsync(decoded with { Budget = Clamp(decoded.Budget) }, token).ConfigureAwait(false);
var response = DataProtoMapper.EncodeMetadataResponse(result);
response.Serving = DataProtoMapper.EncodeServing(caps.Serving);
CheckSize(response);
Register(context, response, () => !token.IsCancellationRequested && CanPublish(connection, caller, caps.Serving));
return response;
});
public override Task<W.ReadResponse> Read(W.ReadRequest request, ServerCallContext context) =>
Execute(context, async (connection, caller, token) =>
{
var caps = await Ready(connection, DataOperations.Read, token).ConfigureAwait(false);
var decoded = DataProtoMapper.DecodeReadRequest(request, DecodeLimits(caps));
var results = await connection.ReadAsync(decoded with { Budget = Clamp(decoded.Budget) }, token).ConfigureAwait(false);
foreach (var result in results) context.GetHttpContext().Response.RegisterForDispose(result);
var response = DataProtoMapper.EncodeReadResponse(results);
response.Serving = DataProtoMapper.EncodeServing(caps.Serving);
CheckSize(response);
Register(context, response, () => !token.IsCancellationRequested
&& CanPublish(connection, caller, caps.Serving)
&& results.All(result => result.Sample is null || result.ResourceLease is IDataPublicationLease { IsValid: true }));
return response;
});
public override Task<W.WriteResponse> Write(W.WriteRequest request, ServerCallContext context) =>
Execute(context, async (connection, caller, token) =>
{
var caps = await connection.GetCapabilitiesAsync(DiscoveryBudget, token).ConfigureAwait(false);
var limits = DecodeLimits(caps);
var decoded = DataProtoMapper.DecodeWriteRequest(request, limits.MaxItems, limits.MaxBytes, limits.MaxValueElements);
try
{
var results = caps.Readiness == DataReadiness.Ready && caps.Operations.HasFlag(DataOperations.Write)
? await connection.WriteAsync(decoded with { Budget = Clamp(decoded.Budget) }, token).ConfigureAwait(false)
: decoded.Items.Select(item => new WriteItemResult(item.CorrelationId,
new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Write unavailable before dispatch."))).ToArray();
var serving = caps.Serving;
DataCapabilities? rejectionCaps = null;
if (results.All(result => result.Outcome.State == DataWriteState.RejectedBeforeDispatch))
{
var current = await connection.GetCapabilitiesAsync(DiscoveryBudget, token).ConfigureAwait(false);
if (current.Serving.NodeId != serving.NodeId || current.Serving.Incarnation != serving.Incarnation) throw Unavailable();
rejectionCaps = current; serving = current.Serving;
}
var response = DataProtoMapper.EncodeWriteResponse(results);
response.Serving = DataProtoMapper.EncodeServing(serving);
CheckSize(response);
Register(context, response, () => !token.IsCancellationRequested && authenticator.IsCurrent(caller)
&& (rejectionCaps is { } negative
? connection is IDataConnectionDiscoveryGate discovery && discovery.CanPublishCapabilities(negative)
: CanPublish(connection, caller, serving)));
return response;
}
finally { foreach (var item in decoded.Items) item.Value.Dispose(); }
});
private DataBudget DiscoveryBudget => new(_options.UnaryTimeout, 1, _options.MaxMessageBytes);
private DataBudget Clamp(DataBudget budget) => budget with
{ Timeout = budget.Timeout <= _options.UnaryTimeout ? budget.Timeout : _options.UnaryTimeout,
MaxBytes = Math.Min(budget.MaxBytes, _options.MaxMessageBytes) };
private DataDecodeLimits DecodeLimits(DataCapabilities caps) => new(caps.Limits.MaxBatchItems,
Math.Min(caps.Limits.MaxMessageBytes, _options.MaxMessageBytes), caps.Limits.MaxValueElements);
private async Task<DataCapabilities> Ready(IDataConnection connection, DataOperations operation, CancellationToken token)
{
var caps = await connection.GetCapabilitiesAsync(DiscoveryBudget, token).ConfigureAwait(false);
if (caps.Readiness != DataReadiness.Ready) throw Unavailable();
if (!caps.Operations.HasFlag(operation)) throw new RpcException(new Status(StatusCode.PermissionDenied, "Data operation denied."));
return caps;
}
private bool CanPublish(IDataConnection connection, DataAuthenticatedContext caller, ServingIdentity expected) =>
authenticator.IsCurrent(caller) && connection is IDataConnectionPublicationGate gate && gate.CanPublish(expected);
public override async Task Subscribe(IAsyncStreamReader<W.SubscriptionCommand> requests,
IServerStreamWriter<W.SubscriptionFrame> responses, ServerCallContext context)
{
try
{
context.WriteOptions = new(WriteFlags.NoCompress);
responses.WriteOptions = new(WriteFlags.NoCompress);
var (caller, target) = AuthenticateCall(context);
await using var connection = factory.Create(caller, target);
DataCapabilities caps;
IDataSubscription subscription;
using (var initial = CancellationTokenSource.CreateLinkedTokenSource(context.CancellationToken))
{
initial.CancelAfter(_options.UnaryTimeout);
caps = await Ready(connection, DataOperations.Subscribe, initial.Token).ConfigureAwait(false);
}
subscription = await connection.SubscribeAsync(context.CancellationToken).ConfigureAwait(false);
await using (subscription)
{
if (subscription is not IDataSubscriptionTransport transport)
throw new RpcException(new Status(StatusCode.Unavailable, "Subscription transport is unavailable."));
using var stop = CancellationTokenSource.CreateLinkedTokenSource(context.CancellationToken);
var sink = new GrpcDeliverySink(responses, context, caps, _options.MaxMessageBytes,
() => CanPublish(connection, caller, caps.Serving));
var delivery = transport.RunDeliveryAsync(sink, stop.Token);
var commands = ReceiveCommands();
try { await await Task.WhenAny(delivery, commands).ConfigureAwait(false); }
finally
{
await stop.CancelAsync().ConfigureAwait(false);
await subscription.DisposeAsync().ConfigureAwait(false);
try { await Task.WhenAll(delivery, commands).ConfigureAwait(false); }
catch (OperationCanceledException) when (stop.IsCancellationRequested) { }
}
async Task ReceiveCommands()
{
var limits = DecodeLimits(caps) with { MaxItems = caps.Limits.MaxMonitoredItems };
while (await requests.MoveNext(stop.Token).ConfigureAwait(false))
{
if (!CanPublish(connection, caller, caps.Serving)) throw Unavailable();
var command = DataProtoMapper.DecodeCommand(requests.Current, limits);
var ack = command.AcknowledgementTimeout <= _options.StreamCommandTimeout
? command.AcknowledgementTimeout : _options.StreamCommandTimeout;
command = command switch
{
OpenSubscription open => open with { AcknowledgementTimeout = ack, SnapshotBudget = Clamp(open.SnapshotBudget) },
AddSubscriptionItems add => add with { AcknowledgementTimeout = ack },
ModifySubscriptionItems modify => modify with { AcknowledgementTimeout = ack },
RemoveSubscriptionItems remove => remove with { AcknowledgementTimeout = ack },
_ => throw new ArgumentException("Unsupported stream command.")
};
using var commandDeadline = CancellationTokenSource.CreateLinkedTokenSource(stop.Token);
commandDeadline.CancelAfter(_options.StreamCommandTimeout);
await subscription.SendAsync(command, commandDeadline.Token).ConfigureAwait(false);
}
}
}
}
catch (RpcException) { throw; }
catch (UnauthorizedAccessException) { throw new RpcException(new Status(StatusCode.Unauthenticated, "Data authentication failed.")); }
catch (ArgumentException) { throw new RpcException(new Status(StatusCode.InvalidArgument, "Invalid stream command.")); }
catch (InvalidOperationException) { throw Unavailable(); }
catch (OperationCanceledException) { throw new RpcException(new Status(StatusCode.Cancelled, "Data stream canceled.")); }
}
private sealed class GrpcDeliverySink(IServerStreamWriter<W.SubscriptionFrame> writer, ServerCallContext context,
DataCapabilities caps, int maximumBytes, Func<bool> hostGuard) : IDataSubscriptionDeliverySink
{
public ValueTask<IDataPreparedSubscriptionDelivery> PrepareAsync(DataSubscriptionFrame frame, long reservedBytes,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Reserve conservatively before allocating protobuf payload copies or serialized bytes.
long charge = checked(2048L + 4L * frame.SubscriptionId.Length);
charge = frame switch
{
DataSubscriptionValues values => values.Items.Aggregate(charge, (sum, item) => checked(sum
+ 4 * item.Sample.Value.EstimatedRetainedBytes + 2048L)),
DataSubscriptionAck ack => ack.Items.Aggregate(charge, (sum, item) => checked(sum + 2048L
+ 4L * (item.ClientItemId.Length + (item.Diagnostic?.Length ?? 0)))),
DataSubscriptionControl control => checked(charge + 128L * control.Watermarks.Count + 4L * (control.Diagnostic?.Length ?? 0)),
_ => throw new ArgumentException("Unsupported subscription frame.")
};
if (charge > reservedBytes) throw new RpcException(new Status(StatusCode.ResourceExhausted, "Prepared frame exceeds its reservation."));
var wire = frame is DataSubscriptionValues valuesFrame
? DataProtoMapper.EncodeValues(valuesFrame, compactNegotiated: false, subscriptionAgeReadiness: true)
: DataProtoMapper.EncodeControlOrAck(frame);
wire.Serving = DataProtoMapper.EncodeServing(caps.Serving);
if (wire.CalculateSize() > maximumBytes) throw new RpcException(new Status(StatusCode.ResourceExhausted, "Stream message exceeds transport limits."));
var payload = wire.ToByteArray();
if (charge < payload.Length) throw new RpcException(new Status(StatusCode.ResourceExhausted, "Prepared frame exceeds its reservation."));
return ValueTask.FromResult<IDataPreparedSubscriptionDelivery>(new PreparedDataSubscription(wire, payload, charge,
maximumBytes, hostGuard, cancellationToken, () => !context.CancellationToken.IsCancellationRequested
&& context.WriteOptions is { Flags: var flags } && (flags & WriteFlags.NoCompress) != 0));
}
public async ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken) =>
await writer.WriteAsync(((PreparedDataSubscription)prepared).Frame, cancellationToken).ConfigureAwait(false);
}
private (DataAuthenticatedContext Caller, DataTarget Target) AuthenticateCall(ServerCallContext context)
{
var http = context.GetHttpContext();
if (!DataConnectionEndpoints.IsDataRequest(http, _options)
|| http.Items[typeof(DataAuthenticatedContext)] is not DataAuthenticatedContext caller
|| !authenticator.IsCurrent(caller))
throw new RpcException(new Status(StatusCode.Unauthenticated, "Data authentication failed."));
if (http.Items[typeof(DataTarget)] is not DataTarget target) throw new ArgumentException("Missing target policy.");
target.Validate();
return (caller, target);
}
private async Task<T> Execute<T>(ServerCallContext context,
Func<IDataConnection, DataAuthenticatedContext, CancellationToken, Task<T>> operation)
{
try
{
// ASP.NET discovers generated bindings with a null service instance and creates its
// invoker by reflection. The real execution path must own this flag, not a binder delegate.
context.WriteOptions = new(WriteFlags.NoCompress);
var http = context.GetHttpContext();
var (caller, target) = AuthenticateCall(context);
if (!http.Items.ContainsKey(typeof(DataConnectionUnaryLifetime)))
http.Items[typeof(DataConnectionUnaryLifetime)] = new DataConnectionUnaryLifetime(TimeProvider.System, _options.UnaryTimeout);
var timeout = new CancellationTokenSource(_options.UnaryTimeout);
http.Response.RegisterForDispose(timeout);
var linked = CancellationTokenSource.CreateLinkedTokenSource(context.CancellationToken, timeout.Token);
http.Response.RegisterForDispose(linked);
http.Items[typeof(DataConnectionGrpcService)] = linked.Token;
var connection = factory.Create(caller, target);
http.Response.RegisterForDisposeAsync(connection);
return await operation(connection, caller, linked.Token).ConfigureAwait(false);
}
catch (RpcException) { throw; }
catch (UnauthorizedAccessException) { throw new RpcException(new Status(StatusCode.Unauthenticated, "Data authentication failed.")); }
catch (ArgumentException) { throw new RpcException(new Status(StatusCode.InvalidArgument, "Invalid data request.")); }
catch (InvalidOperationException) { throw Unavailable(); }
catch (OperationCanceledException) { throw new RpcException(new Status(StatusCode.Cancelled, "Data request canceled.")); }
}
private void CheckSize(IMessage response)
{
if (response.CalculateSize() > _options.MaxMessageBytes)
throw new RpcException(new Status(StatusCode.ResourceExhausted, "Data response exceeds transport limits."));
}
private void Register(ServerCallContext context, IMessage response, Func<bool> guard)
{
var http = context.GetHttpContext();
var operationToken = http.Items[typeof(DataConnectionGrpcService)] is CancellationToken token ? token : context.CancellationToken;
var deadline = (DataConnectionUnaryLifetime)http.Items[typeof(DataConnectionUnaryLifetime)]!;
http.Response.RegisterForDispose(DataConnectionPublication.RegisterUnary(response, () =>
{
var allowed = guard();
// Publication validation may block; cancellation/deadline and compression flags are
// observed again afterwards, immediately before the marshaller's final state read.
return allowed && !operationToken.IsCancellationRequested && !context.CancellationToken.IsCancellationRequested
&& context.WriteOptions is { Flags: var flags } && (flags & WriteFlags.NoCompress) != 0;
}, _options.MaxMessageBytes, deadline));
}
private static RpcException Unavailable() => new(new Status(StatusCode.Unavailable, "Data serving identity or authority is unavailable."));
}
@@ -0,0 +1,8 @@
namespace ZB.MOM.WW.OtOpcUa.Host.Grpc;
/// <summary>Checks the server's own unary budget without relying on timer callback scheduling.</summary>
internal sealed class DataConnectionUnaryLifetime(TimeProvider clock, TimeSpan duration)
{
private readonly long _started = clock.GetTimestamp();
internal bool IsActive => clock.GetElapsedTime(_started) < duration;
}
@@ -0,0 +1,40 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
namespace ZB.MOM.WW.OtOpcUa.Host.Grpc;
/// <summary>Owned encoded frame whose final runtime proof is evaluated in the actual response marshaller.</summary>
internal sealed class PreparedDataSubscription : IDataPreparedSubscriptionPublication
{
private readonly IDisposable _registration;
private Func<bool>? _runtimeGuard;
private int _disposed;
internal PreparedDataSubscription(W.SubscriptionFrame frame, byte[] payload, long retainedBytes, int maximumBytes,
Func<bool> hostGuard, CancellationToken token, Func<bool>? finalTransportReady = null)
{
ArgumentNullException.ThrowIfNull(frame); ArgumentNullException.ThrowIfNull(payload); ArgumentNullException.ThrowIfNull(hostGuard);
if (retainedBytes < payload.Length) throw new ArgumentOutOfRangeException(nameof(retainedBytes));
Frame = frame; RetainedBytes = retainedBytes;
_registration = DataConnectionPublication.Register(frame, () =>
{
if (Volatile.Read(ref _disposed) != 0 || !hostGuard()) return false;
var runtime = Volatile.Read(ref _runtimeGuard);
if (runtime is null || !runtime()) return false;
return Volatile.Read(ref _disposed) == 0 && !token.IsCancellationRequested
&& (finalTransportReady is null || finalTransportReady());
}, maximumBytes, payload);
}
internal W.SubscriptionFrame Frame { get; }
public long RetainedBytes { get; }
public void SetPublicationGuard(Func<bool> guard)
{
ArgumentNullException.ThrowIfNull(guard);
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
if (Interlocked.CompareExchange(ref _runtimeGuard, guard, null) is not null)
throw new InvalidOperationException("A publication guard can be bound only once.");
}
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) == 0) _registration.Dispose();
}
}
+22 -1
View File
@@ -627,6 +627,7 @@ if (hasAdmin)
// Registered unconditionally: driver-role nodes resolve Layer-B DriverConfig secrets and have no auth/DP/AdminUI.
// Cluster replication is opt-in behind Secrets:Replication:Enabled (default false) — see SecretsRegistration.
builder.Services.AddOtOpcUaSecrets(builder.Configuration);
var dataConnectionOptions = builder.Services.AddOtOpcUaDataConnections(builder.Configuration, builder.Environment, hasDriver);
// hasAdmin gates the configdb probe: a driver-only node registers no ConfigDb factory (see above), so
// probing it would throw when the readiness endpoint resolves the factory. hasDriver adds the
@@ -668,6 +669,7 @@ if (hasDriver || hasAdmin)
o.Interceptors.Add<ConfigServeAuthInterceptor>();
o.Interceptors.Add<CentralCommandAuthInterceptor>();
}
if (dataConnectionOptions.Enabled) o.Interceptors.Add<DataConnectionAuthInterceptor>();
// Innermost (after every auth gate): ends open streaming calls — the peer's LocalDb sync stream
// above all — on ApplicationStopping instead of letting Kestrel's drain wait out ShutdownTimeout
// (lmxopcua#906), and refuses new streams once stopping has begun.
@@ -698,7 +700,11 @@ if (hasDriver || hasAdmin)
var syncListenPort = hasDriver ? LocalDbRegistration.SyncListenPort(builder.Configuration) : 0;
var configServeGrpcPort = hasAdmin ? builder.Configuration.GetValue<int>("ConfigServe:GrpcListenPort") : 0;
var telemetryListenPort = hasDriver ? builder.Configuration.GetValue<int>("Telemetry:GrpcListenPort") : 0;
if (syncListenPort > 0 || configServeGrpcPort > 0 || telemetryListenPort > 0)
var dataListenPort = dataConnectionOptions.Enabled ? dataConnectionOptions.ListenPort : 0;
System.Security.Cryptography.X509Certificates.X509Certificate2? dataServerCertificate = null;
if (dataListenPort > 0 && new[] { syncListenPort, configServeGrpcPort, telemetryListenPort }.Contains(dataListenPort))
throw new InvalidOperationException("DataConnections:ListenPort must be separate from every mesh listener.");
if (syncListenPort > 0 || configServeGrpcPort > 0 || telemetryListenPort > 0 || dataListenPort > 0)
{
// Mirror Kestrel's own source precedence: URLS wins; else the HTTP_PORTS/HTTPS_PORTS bare-port
// vars; else Kestrel's localhost:5000 default. Missing the HTTP_PORTS leg is not academic — the
@@ -745,6 +751,8 @@ if (syncListenPort > 0 || configServeGrpcPort > 0 || telemetryListenPort > 0)
// Kestrel takeover).
if (existingBindings.Any(b => b.IsSecure))
{
if (dataListenPort > 0)
throw new InvalidOperationException("The dedicated data listener cannot safely replay existing HTTPS URL bindings. Configure an HTTP UI/health binding and the dedicated data TLS certificate separately.");
Log.Error(
"A dedicated h2c listener is requested (LocalDb:SyncListenPort={SyncPort}, " +
"ConfigServe:GrpcListenPort={ConfigServePort}, Telemetry:GrpcListenPort={TelemetryPort}) but this " +
@@ -763,6 +771,10 @@ if (syncListenPort > 0 || configServeGrpcPort > 0 || telemetryListenPort > 0)
var syncPortToBind = syncListenPort;
var configServePortToBind = configServeGrpcPort;
var telemetryPortToBind = telemetryListenPort;
if (dataListenPort > 0 && existingBindings.Any(binding => binding.Port == dataListenPort))
throw new InvalidOperationException("DataConnections:ListenPort conflicts with an existing UI/health binding.");
if (dataListenPort > 0 && !dataConnectionOptions.AllowDevelopmentCleartext)
dataServerCertificate = DataConnectionServerCertificate.Load(dataConnectionOptions);
builder.WebHost.ConfigureKestrel(kestrel =>
{
foreach (var binding in existingBindings)
@@ -774,6 +786,12 @@ if (syncListenPort > 0 || configServeGrpcPort > 0 || telemetryListenPort > 0)
kestrel.ListenAnyIP(configServePortToBind, o => o.Protocols = HttpProtocols.Http2);
if (telemetryPortToBind > 0)
kestrel.ListenAnyIP(telemetryPortToBind, o => o.Protocols = HttpProtocols.Http2);
if (dataListenPort > 0)
kestrel.Listen(System.Net.IPAddress.Parse(dataConnectionOptions.ListenAddress), dataListenPort, listener =>
{
listener.Protocols = HttpProtocols.Http2;
if (dataServerCertificate is not null) listener.UseHttps(dataServerCertificate);
});
});
Log.Information(
@@ -785,6 +803,8 @@ if (syncListenPort > 0 || configServeGrpcPort > 0 || telemetryListenPort > 0)
}
var app = builder.Build();
if (dataServerCertificate is not null) app.Lifetime.ApplicationStopped.Register(dataServerCertificate.Dispose);
if (dataConnectionOptions.Enabled) app.UseDataConnectionAdmission();
// AddZbSerilog registers Serilog as the MEL logging provider but does NOT assign the static
// Serilog.Log.Logger. Set it from the DI root logger so (1) static Log.* calls like the startup
@@ -820,6 +840,7 @@ if (hasAdmin)
// file's remarks — archreview 03/S14).
app.MapOtOpcUaMeshGrpcServices(
hasAdmin, hasDriver, syncListenPort, configServeGrpcPort, telemetryListenPort);
if (dataConnectionOptions.Enabled) app.MapGrpcService<DataConnectionGrpcService>().AllowAnonymous();
app.MapOtOpcUaHealth();
app.MapOtOpcUaMetrics();
@@ -0,0 +1,20 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Admits only an authenticated capability response for the configured target.</summary>
public static class ClusterEndpointSelector
{
public static bool IsEligible(DataTarget target, DataCapabilities capabilities, bool forWrite)
{
target.Validate();
capabilities.Validate();
if (capabilities.ProtocolMajor != 1 || capabilities.Readiness != DataReadiness.Ready ||
!string.Equals(target.ExpectedClusterId, capabilities.ClusterId, StringComparison.OrdinalIgnoreCase)) return false;
if (target.Mode == DataTargetMode.Node &&
!string.Equals(target.ExpectedNodeId, capabilities.Serving.NodeId, StringComparison.OrdinalIgnoreCase)) return false;
return string.Equals(capabilities.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase) ||
target.Mode == DataTargetMode.Node && !forWrite && target.Consistency == DataConsistency.ReadyReplica &&
string.Equals(capabilities.Serving.Role, "Secondary", StringComparison.OrdinalIgnoreCase);
}
}
@@ -0,0 +1,498 @@
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>A node-effective artifact and the durable credential-scope floor it requires.</summary>
public sealed record DataConnectionDeploymentSnapshot(long ScopeVersion, string ArtifactRevision, IReadOnlyList<DataConnection> Connections,
RedundancyMode ConsumerMode = RedundancyMode.None);
/// <summary>Persists the node's current connection-to-secret allowlist before any route is made ready.</summary>
public interface IDataConnectionScopeActivator
{
Task SetScopeAsync(long version, IReadOnlyDictionary<string, string> allowlist, CancellationToken cancellationToken);
}
/// <summary>Owns configured connections and reconciles only the latest node-effective scope.</summary>
public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
{
private sealed record Spec(string Id, long Revision, DataTarget Target, Uri[] Endpoints, HashSet<string> EligibleNodes,
string Secret, DataOperations Operations, TimeSpan Timeout, int Batch, int Page, int MessageBytes,
int Streams, int Monitored, long PendingBytes);
private sealed record Desired(long ScopeVersion, string ArtifactRevision, long Generation, RedundancyMode ConsumerMode,
IReadOnlyDictionary<string, Spec> Specs, IReadOnlyDictionary<string, string> Allowlist);
private sealed class Entry(Spec spec, long generation, GrpcDataConnection connection, CancellationToken token)
{
internal readonly Spec Spec = spec;
internal readonly long Generation = generation;
internal readonly GrpcDataConnection Connection = connection;
internal readonly CancellationToken Token = token;
internal bool Ready;
internal int Leases;
}
private readonly object _sync = new();
private readonly string _node, _owner;
private readonly IDataConnectionSecurityProvider _security;
private readonly IDataConnectionScopeActivator _activator;
private readonly DataConnectionManager _manager;
private readonly int _maximum;
private readonly TimeProvider _clock;
private readonly Func<bool> _consumerMayAcquire;
private readonly CancellationTokenSource _stop = new();
private readonly ITimer _retryTimer;
private readonly Dictionary<string, Entry> _entries = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, long> _routeRevisions = new(StringComparer.OrdinalIgnoreCase);
private readonly HashSet<Task> _retirements = new();
private Desired? _desired;
private Task? _worker, _disposeTask;
private bool _wake, _scopeReady, _disposed, _attemptPending;
private string? _attemptRevision;
private long _generation, _securityGeneration, _retryGeneration, _retryNotBefore;
private int _retryFailures;
public DataConnectionDeploymentRuntime(string nodeId, string ownerCluster, IDataConnectionSecurityProvider security,
IDataConnectionScopeActivator scopeActivator, int maxConnections, TimeProvider? clock = null,
Func<bool>? consumerMayAcquire = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(nodeId); ArgumentException.ThrowIfNullOrWhiteSpace(ownerCluster);
if (maxConnections <= 0) throw new ArgumentOutOfRangeException(nameof(maxConnections));
_node = nodeId; _owner = ownerCluster; _security = security ?? throw new ArgumentNullException(nameof(security));
_activator = scopeActivator ?? throw new ArgumentNullException(nameof(scopeActivator)); _maximum = maxConnections;
_clock = clock ?? TimeProvider.System; _consumerMayAcquire = consumerMayAcquire ?? (() => true);
_retryTimer = _clock.CreateTimer(static state => ((DataConnectionDeploymentRuntime)state!).OnRetry(), this,
Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
_manager = new DataConnectionManager(nodeId, maxConnections);
_manager.AvailabilityChanged += OnAvailability;
_security.Changed += OnSecurityChanged;
}
/// <summary>True only after the current scope version and allowlist are durably accepted.</summary>
public bool CurrentScopeReady { get { lock (_sync) return !_disposed && _scopeReady; } }
/// <summary>Configured redundancy mode from the current validated artifact.</summary>
public RedundancyMode CurrentConsumerMode { get { lock (_sync) return _desired?.ConsumerMode ?? RedundancyMode.None; } }
/// <summary>Withdraws current routes before parsing or staging a different artifact.</summary>
public void BeginAttempt(string artifactRevision)
{
ArgumentException.ThrowIfNullOrWhiteSpace(artifactRevision);
lock (_sync)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (!_attemptPending && _scopeReady && _desired is { } accepted &&
string.Equals(accepted.ArtifactRevision, artifactRevision, StringComparison.Ordinal))
{ _attemptRevision = artifactRevision; return; }
if (_attemptPending && string.Equals(_attemptRevision, artifactRevision, StringComparison.Ordinal)) return;
_attemptRevision = artifactRevision; _attemptPending = true; _scopeReady = false; _wake = false;
DisarmRetryLocked();
var generation = checked(++_generation);
if (_desired is not null) _desired = _desired with { Generation = generation };
var old = _entries.Values.ToArray(); _entries.Clear();
_manager.ApplyScope(new Dictionary<string, DataConnectionScope>(StringComparer.OrdinalIgnoreCase));
foreach (var entry in old) Retire(entry);
}
}
/// <summary>Copies and validates desired data, synchronously denies old routes, and schedules reconciliation.</summary>
public void Apply(DataConnectionDeploymentSnapshot snapshot)
{
ArgumentNullException.ThrowIfNull(snapshot);
if (snapshot.ScopeVersion <= 0 || !Enum.IsDefined(snapshot.ConsumerMode)) throw new ArgumentOutOfRangeException(nameof(snapshot));
ArgumentException.ThrowIfNullOrWhiteSpace(snapshot.ArtifactRevision);
ArgumentNullException.ThrowIfNull(snapshot.Connections);
if (snapshot.Connections.Count > _maximum) throw new ArgumentException("Connection capacity exceeded.", nameof(snapshot));
var specs = new Dictionary<string, Spec>(StringComparer.OrdinalIgnoreCase);
var allow = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var item in snapshot.Connections)
{
ArgumentNullException.ThrowIfNull(item);
ArgumentException.ThrowIfNullOrWhiteSpace(item.DataConnectionId);
if (!item.Enabled) continue;
if (!string.Equals(item.ClusterId, _owner, StringComparison.OrdinalIgnoreCase) ||
item.ConsumerNodeIds is null || !item.ConsumerNodeIds.Contains(_node, StringComparer.OrdinalIgnoreCase) ||
!string.Equals(item.SecretScopeClusterId, _owner, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("Connection is not enabled for this consumer and owner.", nameof(snapshot));
ArgumentException.ThrowIfNullOrWhiteSpace(item.SecretReference);
var target = new DataTarget(item.TargetMode, item.ExpectedClusterId, item.ExpectedNodeId, item.Consistency); target.Validate();
if (item.Revision <= 0 || item.TimeoutMilliseconds <= 0 || item.MaxBatchItems <= 0 || item.MaxPageItems <= 0 ||
item.MaxMessageBytes <= 0 || item.MaxStreams <= 0 || item.MaxMonitoredItems <= 0 || item.MaxPendingBytes <= 0 ||
item.Endpoints is null || item.Endpoints.Count == 0 || item.Endpoints.Count > 32 || item.EligibleTargetNodeIds is null)
throw new ArgumentException("Connection limits or endpoints are invalid.", nameof(snapshot));
const DataOperations known = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe;
if ((item.AllowedOperations & ~known) != 0) throw new ArgumentException("Unknown operation.", nameof(snapshot));
var endpoints = item.Endpoints.Select(value => Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme == Uri.UriSchemeHttps
? uri : throw new ArgumentException("Only HTTPS endpoints are accepted.", nameof(snapshot))).Distinct().ToArray();
var eligible = new HashSet<string>(item.EligibleTargetNodeIds, StringComparer.OrdinalIgnoreCase);
if (target.Mode == DataTargetMode.Cluster && (eligible.Count == 0 || eligible.Any(string.IsNullOrWhiteSpace)))
throw new ArgumentException("Cluster target has no eligible nodes.", nameof(snapshot));
var spec = new Spec(item.DataConnectionId, item.Revision, target, endpoints, eligible, item.SecretReference,
item.AllowedOperations, TimeSpan.FromMilliseconds(item.TimeoutMilliseconds), item.MaxBatchItems,
item.MaxPageItems, item.MaxMessageBytes, item.MaxStreams, item.MaxMonitoredItems, item.MaxPendingBytes);
if (!specs.TryAdd(spec.Id, spec) || !allow.TryAdd(spec.Id, spec.Secret))
throw new ArgumentException("Duplicate connection identity.", nameof(snapshot));
}
Entry[] old;
lock (_sync)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_attemptRevision is not null && !string.Equals(_attemptRevision, snapshot.ArtifactRevision, StringComparison.Ordinal))
throw new InvalidOperationException("Artifact does not match the latest deployment attempt.");
if (_desired is { } previous)
{
if (snapshot.ScopeVersion < previous.ScopeVersion) throw new InvalidOperationException("Scope version moved backwards.");
if (snapshot.ScopeVersion == previous.ScopeVersion && !SameAllowlist(previous.Allowlist, allow))
throw new InvalidOperationException("A scope version cannot identify different allowlists.");
if (string.Equals(snapshot.ArtifactRevision, previous.ArtifactRevision, StringComparison.Ordinal))
{
if (snapshot.ScopeVersion != previous.ScopeVersion || snapshot.ConsumerMode != previous.ConsumerMode || !SameSpecs(previous.Specs, specs))
throw new InvalidOperationException("An artifact revision cannot identify different definitions.");
if (!_attemptPending) { if (!_scopeReady) DisarmRetryLocked(); WakeLocked(); return; }
}
}
_attemptPending = false; DisarmRetryLocked();
var generation = checked(++_generation);
_routeRevisions.Clear();
foreach (var id in specs.Keys) _routeRevisions.Add(id, generation);
_desired = new(snapshot.ScopeVersion, snapshot.ArtifactRevision, generation, snapshot.ConsumerMode, specs, allow);
_scopeReady = false;
old = _entries.Values.ToArray(); _entries.Clear();
ApplyManagerScopeLocked(_desired);
foreach (var entry in old) Retire(entry);
WakeLocked();
}
}
private static bool SameAllowlist(IReadOnlyDictionary<string, string> left, IReadOnlyDictionary<string, string> right) =>
left.Count == right.Count && left.All(x => right.TryGetValue(x.Key, out var value) && string.Equals(value, x.Value, StringComparison.Ordinal));
private static bool SameSpecs(IReadOnlyDictionary<string, Spec> left, IReadOnlyDictionary<string, Spec> right) =>
left.Count == right.Count && left.All(pair => right.TryGetValue(pair.Key, out var b) && SameSpec(pair.Value, b));
private static bool SameSpec(Spec a, Spec b) =>
string.Equals(a.Id, b.Id, StringComparison.OrdinalIgnoreCase) && a.Revision == b.Revision && a.Target == b.Target &&
a.Endpoints.SequenceEqual(b.Endpoints) && a.EligibleNodes.SetEquals(b.EligibleNodes) &&
string.Equals(a.Secret, b.Secret, StringComparison.Ordinal) && a.Operations == b.Operations && a.Timeout == b.Timeout &&
a.Batch == b.Batch && a.Page == b.Page && a.MessageBytes == b.MessageBytes && a.Streams == b.Streams &&
a.Monitored == b.Monitored && a.PendingBytes == b.PendingBytes;
private bool MayAcquire() { try { return _consumerMayAcquire(); } catch (Exception) { return false; } }
private void ApplyManagerScopeLocked(Desired desired)
{
// The manager owns configured-node scope and physical lifetime only. Role checks
// independently guard activation, acquisition, and each borrowed operation.
var scope = new Dictionary<string, DataConnectionScope>(StringComparer.OrdinalIgnoreCase);
foreach (var spec in desired.Specs.Values)
scope.Add(spec.Id, new DataConnectionScope(_routeRevisions[spec.Id], new HashSet<string>(StringComparer.OrdinalIgnoreCase) { _node }));
_manager.ApplyScope(scope);
}
/// <summary>Immediately drains routes on a local role change; called outside the role publication fence.</summary>
public void NotifyConsumerRoleChanged()
{
Entry[] old;
lock (_sync)
{
if (_disposed || _desired is null) return;
if (_attemptPending) return;
DisarmRetryLocked();
var generation = checked(++_generation);
_desired = _desired with { Generation = generation };
foreach (var id in _desired.Specs.Keys) _routeRevisions[id] = generation;
old = _entries.Values.ToArray(); _entries.Clear();
ApplyManagerScopeLocked(_desired);
foreach (var entry in old) Retire(entry);
WakeLocked();
}
}
private void OnAvailability() { lock (_sync) { if (!_disposed && !_attemptPending) WakeLocked(); } }
private void OnSecurityChanged(string id)
{
lock (_sync)
{
if (_disposed) return;
checked { _securityGeneration++; }
if (!_scopeReady) DisarmRetryLocked();
if (_desired is not null && _entries.Remove(id, out var entry))
{
var generation = checked(++_generation);
_desired = _desired with { Generation = generation };
_routeRevisions[id] = generation;
ApplyManagerScopeLocked(_desired);
Retire(entry);
}
if (!_attemptPending) WakeLocked();
}
}
private void DisarmRetryLocked()
{
_retryGeneration = 0; _retryNotBefore = 0; _retryFailures = 0;
_retryTimer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
}
private void ScheduleRetryLocked(long generation)
{
var power = _retryFailures;
_retryFailures = Math.Min(_retryFailures + 1, 7);
var delay = TimeSpan.FromMilliseconds(Math.Min(30_000, 250 * (1 << power)));
_retryGeneration = generation;
_retryNotBefore = checked(_clock.GetTimestamp() + (long)(delay.TotalSeconds * _clock.TimestampFrequency));
_retryTimer.Change(delay, Timeout.InfiniteTimeSpan);
}
private void OnRetry()
{
lock (_sync)
{
if (_disposed || _attemptPending || _retryGeneration == 0 || _desired?.Generation != _retryGeneration) return;
var now = _clock.GetTimestamp();
if (now < _retryNotBefore)
{
_retryTimer.Change(_clock.GetElapsedTime(now, _retryNotBefore), Timeout.InfiniteTimeSpan);
return;
}
_retryGeneration = 0;
WakeLocked();
}
}
private void WakeLocked()
{
_wake = true;
if (_worker is null) _worker = Task.Run(ReconcileAsync);
}
private async Task ReconcileAsync()
{
while (true)
{
Desired? desired;
bool floorAlreadyReady;
lock (_sync)
{
if (_disposed || !_wake) { _worker = null; return; }
_wake = false; desired = _attemptPending ? null : _desired; floorAlreadyReady = _scopeReady;
}
if (desired is null) continue;
if (!floorAlreadyReady)
{
try { await _activator.SetScopeAsync(desired.ScopeVersion, desired.Allowlist, _stop.Token).ConfigureAwait(false); }
catch (OperationCanceledException) when (_stop.IsCancellationRequested) { continue; }
catch (Exception)
{
lock (_sync)
if (!_disposed && !_attemptPending && !_scopeReady && _desired?.Generation == desired.Generation)
ScheduleRetryLocked(desired.Generation);
continue;
}
}
lock (_sync)
{
if (_disposed || _attemptPending || _desired?.Generation != desired.Generation) continue;
_scopeReady = true;
if (!MayAcquire())
{
if (desired.Specs.Count > 0) ScheduleRetryLocked(desired.Generation);
else DisarmRetryLocked();
continue;
}
// Reassert configured scope after a deferred physical retirement frees a slot.
ApplyManagerScopeLocked(desired);
}
var retryNeeded = false;
foreach (var spec in desired.Specs.Values)
{
Entry? existing;
long securityGeneration;
lock (_sync)
{
if (_disposed || _attemptPending || _desired?.Generation != desired.Generation) break;
if (!MayAcquire()) { retryNeeded = true; break; }
_entries.TryGetValue(spec.Id, out existing);
if (existing?.Ready == true) continue;
securityGeneration = _securityGeneration;
}
var available = false;
try
{
foreach (var endpoint in spec.Endpoints)
{
var security = await _security.ResolveAsync(spec.Id, endpoint, _stop.Token).ConfigureAwait(false);
if (security is not null && !string.IsNullOrWhiteSpace(security.Bearer) &&
!string.IsNullOrWhiteSpace(security.CredentialVersion) && !string.IsNullOrWhiteSpace(security.TrustFingerprint))
{ available = true; break; }
}
}
catch (OperationCanceledException) when (_stop.IsCancellationRequested) { break; }
catch (Exception) { }
if (!available) { retryNeeded = true; continue; }
lock (_sync)
{
if (_disposed || _attemptPending || _desired?.Generation != desired.Generation || _securityGeneration != securityGeneration) continue;
if (!MayAcquire()) { retryNeeded = true; break; }
if (_entries.TryGetValue(spec.Id, out existing)) { existing.Ready = true; continue; }
DataConnectionScopeLease scope;
try { scope = _manager.Acquire(spec.Id); }
catch (UnauthorizedAccessException) { continue; }
try
{
var connection = new GrpcDataConnection(spec.Id, spec.Target, spec.Endpoints, _security, scope,
spec.MessageBytes, spec.Endpoints.Length, _clock, spec.EligibleNodes,
spec.Streams, spec.Monitored, maxPendingCommandBytes: spec.PendingBytes);
_entries.Add(spec.Id, new Entry(spec, desired.Generation, connection, scope.CancellationToken) { Ready = true });
}
catch (Exception) { scope.Dispose(); retryNeeded = true; }
}
}
lock (_sync)
{
if (!_disposed && !_attemptPending && _desired?.Generation == desired.Generation)
{
if (retryNeeded) ScheduleRetryLocked(desired.Generation);
else DisarmRetryLocked();
}
}
}
}
private void Retire(Entry entry)
{
var task = entry.Connection.DisposeAsync().AsTask();
lock (_sync) _retirements.Add(task);
_ = ObserveRetirementAsync(task);
}
private async Task ObserveRetirementAsync(Task task)
{
try { await task.ConfigureAwait(false); } catch (Exception) { }
lock (_sync) { _retirements.Remove(task); if (!_disposed) WakeLocked(); }
}
/// <summary>Gets a non-owning, scope-bound connection lease when that individual credential is ready.</summary>
public bool TryAcquire(string id, out DataConnectionDeploymentLease? lease)
{
lock (_sync)
{
lease = null;
if (_disposed || !_scopeReady || !MayAcquire() || !_entries.TryGetValue(id, out var entry) || !entry.Ready ||
entry.Token.IsCancellationRequested || entry.Leases >= 1024) return false;
entry.Leases++;
lease = new DataConnectionDeploymentLease(entry.Connection, entry.Token, entry.Spec.Operations, entry.Spec.Timeout,
entry.Spec.Batch, entry.Spec.Page, entry.Spec.MessageBytes, entry.Spec.Streams, entry.Spec.Monitored, entry.Spec.PendingBytes,
() => { lock (_sync) return !_disposed && _scopeReady && MayAcquire() && entry.Ready &&
_entries.TryGetValue(id, out var current) && ReferenceEquals(entry, current); },
() => { lock (_sync) entry.Leases--; });
return true;
}
}
public ValueTask DisposeAsync()
{
lock (_sync)
{
if (_disposeTask is not null) return new(_disposeTask);
_disposed = true; _scopeReady = false; DisarmRetryLocked(); _security.Changed -= OnSecurityChanged; _manager.AvailabilityChanged -= OnAvailability;
_ = _stop.CancelAsync();
_manager.Dispose();
var old = _entries.Values.ToArray(); _entries.Clear();
foreach (var entry in old) Retire(entry);
_disposeTask = FinishDisposeAsync(_worker, _retirements.ToArray());
return new(_disposeTask);
}
}
private async Task FinishDisposeAsync(Task? worker, Task[] retirements)
{
if (worker is not null) try { await worker.ConfigureAwait(false); } catch (Exception) { }
try { await Task.WhenAll(retirements).ConfigureAwait(false); } catch (Exception) { }
_retryTimer.Dispose(); _stop.Dispose();
}
}
/// <summary>A non-owning handle with the deployed operation and resource policy.</summary>
public sealed class DataConnectionDeploymentLease : IDataConnection, IDisposable
{
private readonly IDataConnection _inner;
private readonly CancellationToken _scope;
private readonly DataOperations _allowed;
private readonly TimeSpan _timeout;
private readonly int _batch, _page, _bytes, _streams, _monitored;
private readonly long _pendingBytes;
private readonly Func<bool> _current;
private readonly Action _release;
private int _disposed;
internal DataConnectionDeploymentLease(IDataConnection inner, CancellationToken scope, DataOperations allowed, TimeSpan timeout,
int batch, int page, int bytes, int streams, int monitored, long pendingBytes, Func<bool> current, Action release)
{
_inner = inner; _scope = scope; _allowed = allowed; _timeout = timeout; _batch = batch; _page = page; _bytes = bytes;
_streams = streams; _monitored = monitored; _pendingBytes = pendingBytes; _current = current; _release = release;
}
public IDataConnection Connection => this;
public CancellationToken CancellationToken => _scope;
public DataTarget Target => _inner.Target;
public TimeProvider Clock => _inner.Clock;
private void Check(DataOperations operation = DataOperations.None)
{
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
_scope.ThrowIfCancellationRequested();
if (!_current()) throw new InvalidOperationException("Connection is no longer ready in the current scope.");
if (operation != DataOperations.None && (_allowed & operation) != operation) throw new UnauthorizedAccessException("Operation is not enabled for this connection.");
}
private DataBudget Limit(DataBudget budget, int maxItems)
{
budget.Validate();
return new(budget.Timeout < _timeout ? budget.Timeout : _timeout, Math.Min(budget.MaxItems, maxItems),
Math.Min(Math.Min(budget.MaxBytes, _bytes), _pendingBytes));
}
public async Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken)
{
Check(); var result = await _inner.GetCapabilitiesAsync(Limit(budget, _batch), cancellationToken).ConfigureAwait(false); Check();
var l = result.Limits;
var limits = l with { MaxPageItems = Math.Min(l.MaxPageItems, _page), MaxBatchItems = Math.Min(l.MaxBatchItems, _batch),
MaxMessageBytes = Math.Min(l.MaxMessageBytes, _bytes), MaxStreams = Math.Min(l.MaxStreams, _streams),
MaxMonitoredItems = Math.Min(l.MaxMonitoredItems, _monitored), MaxPendingBytes = Math.Min(l.MaxPendingBytes, _pendingBytes) };
return result with { Operations = result.Operations & _allowed, Limits = limits };
}
public async Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken)
{
Check(DataOperations.Browse); var value = await _inner.BrowseAsync(request with { Budget = Limit(request.Budget, _page) }, cancellationToken).ConfigureAwait(false);
Check(DataOperations.Browse); return value;
}
public async Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
{
Check(DataOperations.Metadata); if (request.Views.Count > _batch) throw new ArgumentOutOfRangeException(nameof(request));
var value = await _inner.GetMetadataAsync(request with { Budget = Limit(request.Budget, _batch) }, cancellationToken).ConfigureAwait(false);
Check(DataOperations.Metadata); return value;
}
public async Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken)
{
Check(DataOperations.Read); if (request.Items.Count > _batch) throw new ArgumentOutOfRangeException(nameof(request));
var value = await _inner.ReadAsync(request with { Budget = Limit(request.Budget, _batch) }, cancellationToken).ConfigureAwait(false);
try { Check(DataOperations.Read); return value; }
catch { foreach (var item in value) item.Dispose(); throw; }
}
public async Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken)
{
Check(DataOperations.Write); if (request.Items.Count > _batch) throw new ArgumentOutOfRangeException(nameof(request));
var value = await _inner.WriteAsync(request with { Budget = Limit(request.Budget, _batch) }, cancellationToken).ConfigureAwait(false);
try { Check(DataOperations.Write); return value; }
catch (Exception ex) when (ex is OperationCanceledException or InvalidOperationException or UnauthorizedAccessException)
{ return request.Items.Select(x => new WriteItemResult(x.CorrelationId, new(DataWriteState.OutcomeUnknown, 0x800A0000u, "Write outcome unknown after scope change."))).ToArray(); }
}
public async Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
{
Check(DataOperations.Subscribe); var stream = await _inner.SubscribeAsync(cancellationToken).ConfigureAwait(false);
try { Check(DataOperations.Subscribe); return new ScopedSubscription(this, stream); }
catch { await stream.DisposeAsync().ConfigureAwait(false); throw; }
}
private sealed class ScopedSubscription(DataConnectionDeploymentLease owner, IDataSubscription inner) : IDataSubscription
{
public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
{
owner.Check(DataOperations.Subscribe);
var count = command switch { OpenSubscription o => o.Items.Count, AddSubscriptionItems a => a.Items.Count,
ModifySubscriptionItems m => m.Items.Count, RemoveSubscriptionItems r => r.Items.Count, _ => owner._monitored + 1 };
if (count > owner._monitored) throw new ArgumentOutOfRangeException(nameof(command));
if (command is OpenSubscription open) command = open with { SnapshotBudget = owner.Limit(open.SnapshotBudget, owner._monitored) };
return inner.SendAsync(command, cancellationToken);
}
public async IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken)
{
await foreach (var frame in inner.ReadAllAsync(cancellationToken).ConfigureAwait(false))
{
try { owner.Check(DataOperations.Subscribe); }
catch { if (frame is IDisposable owned) owned.Dispose(); throw; }
yield return frame;
}
}
public ValueTask DisposeAsync() => inner.DisposeAsync();
}
public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) _release(); }
public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; }
}
@@ -0,0 +1,138 @@
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Deployed revision and permitted consumer nodes for a connection.</summary>
public sealed record DataConnectionScope(long Revision, IReadOnlySet<string> ConsumerNodeIds);
/// <summary>Node-scoped connection lifetimes. Removing scope cancels all handles from that epoch.</summary>
public sealed class DataConnectionManager : IDisposable
{
private sealed class State(long epoch, long revision, CancellationTokenSource cancellation)
{
internal readonly long Epoch = epoch, Revision = revision;
internal readonly CancellationTokenSource Cancellation = cancellation;
internal int Leases;
internal bool Retired, CancellationCompleted;
}
private readonly object _sync = new();
private readonly string _node;
private readonly int _maximum;
private readonly Dictionary<string, State> _active = new(StringComparer.OrdinalIgnoreCase);
private long _epoch;
private int _retiring;
private readonly HashSet<string> _retiringIds = new(StringComparer.OrdinalIgnoreCase);
private Dictionary<string, long> _desired = new(StringComparer.OrdinalIgnoreCase);
private bool _disposed;
/// <summary>Signals that a retired slot finished cleanup and desired scope may be acquired.</summary>
public event Action? AvailabilityChanged;
public DataConnectionManager(string nodeId, int maximumConnections)
{
ArgumentException.ThrowIfNullOrWhiteSpace(nodeId);
if (maximumConnections <= 0) throw new ArgumentOutOfRangeException(nameof(maximumConnections));
_node = nodeId; _maximum = maximumConnections;
}
public void ApplyScope(IReadOnlyDictionary<string, IReadOnlySet<string>> scope) =>
ApplyScope(scope.ToDictionary(x => x.Key, x => new DataConnectionScope(1, x.Value), StringComparer.OrdinalIgnoreCase));
public void ApplyScope(IReadOnlyDictionary<string, DataConnectionScope> scope)
{
ArgumentNullException.ThrowIfNull(scope);
var allowed = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
foreach (var (id, entry) in scope)
{
ArgumentException.ThrowIfNullOrWhiteSpace(id);
ArgumentNullException.ThrowIfNull(entry);
ArgumentNullException.ThrowIfNull(entry.ConsumerNodeIds);
if (entry.Revision <= 0) throw new ArgumentOutOfRangeException(nameof(scope));
if (entry.ConsumerNodeIds.Contains(_node, StringComparer.OrdinalIgnoreCase) && !allowed.TryAdd(id, entry.Revision))
throw new ArgumentException("Duplicate connection identity.", nameof(scope));
}
if (allowed.Count > _maximum) throw new ArgumentException("Connection scope exceeds capacity.", nameof(scope));
lock (_sync)
{
ObjectDisposedException.ThrowIf(_disposed, this);
foreach (var (id, revision) in allowed)
if (_desired.TryGetValue(id, out var prior) && revision < prior)
throw new InvalidOperationException("Connection revision cannot move backwards.");
_desired = allowed;
foreach (var id in _active.Keys.Where(id => !allowed.TryGetValue(id, out var revision) || revision != _active[id].Revision).ToArray())
{
var state = _active[id]; _active.Remove(id); state.Retired = true; _retiring++; _retiringIds.Add(id);
// CancelAsync marks the token immediately; callbacks complete without holding the lock.
var cancellation = state.Cancellation.CancelAsync();
_ = FinishRetirementAsync(id, state, cancellation);
}
FillLocked();
}
}
private void FillLocked()
{
if (_disposed) return;
foreach (var (id, revision) in _desired)
{
if (_active.Count + _retiring >= _maximum) break;
if (!_active.ContainsKey(id) && !_retiringIds.Contains(id))
_active.Add(id, new(checked(++_epoch), revision, new()));
}
}
private async Task FinishRetirementAsync(string id, State state, Task cancellation)
{
// Force asynchronous continuation even if there are no callbacks; callers must never run cleanup under the lock.
await Task.Yield();
try { await cancellation.ConfigureAwait(false); }
catch (Exception) { /* callbacks cannot keep quota forever after completion */ }
finally
{
lock (_sync)
{
state.CancellationCompleted = true;
ReleaseRetiredLocked(id, state);
}
}
}
private void ReleaseRetiredLocked(string id, State state)
{
if (!state.Retired || !state.CancellationCompleted || state.Leases != 0) return;
state.Retired = false; state.Cancellation.Dispose(); _retiring--; _retiringIds.Remove(id); FillLocked();
var handlers = AvailabilityChanged;
if (handlers is not null) ThreadPool.QueueUserWorkItem(static action =>
{
foreach (var subscriber in action.GetInvocationList().Cast<Action>())
try { subscriber(); } catch (Exception) { }
}, handlers, preferLocal: false);
}
public DataConnectionScopeLease Acquire(string connectionId)
{
lock (_sync)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (!_active.TryGetValue(connectionId, out var state)) throw new UnauthorizedAccessException("Connection is outside this node's scope.");
state.Leases++;
return new(state.Epoch, state.Cancellation.Token, () =>
{
lock (_sync) { state.Leases--; ReleaseRetiredLocked(connectionId, state); }
});
}
}
public void Dispose()
{
lock (_sync)
{
if (_disposed) return;
_disposed = true; _desired.Clear();
foreach (var (id, state) in _active)
{
state.Retired = true; _retiring++; _retiringIds.Add(id);
_ = FinishRetirementAsync(id, state, state.Cancellation.CancelAsync());
}
_active.Clear();
}
}
}
/// <summary>A snapshot of one authorized connection scope epoch.</summary>
public sealed class DataConnectionScopeLease(long epoch, CancellationToken cancellationToken, Action release) : IDisposable
{
private int _disposed;
public long Epoch { get; } = epoch;
public CancellationToken CancellationToken { get; } = cancellationToken;
public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) release(); }
}
@@ -0,0 +1,28 @@
using Akka.Actor;
using Akka.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Selects the node's registered publisher dependencies for the production actor.</summary>
internal static class DataConnectionPublisherProps
{
internal static Props Create(IDependencyResolver services, IOpcUaAddressSpaceSink sink, IServiceLevelPublisher serviceLevel,
NodeId localNode, IDbContextFactory<OtOpcUaConfigDbContext>? dbFactory, AddressSpaceApplier applier, IActorRef? dbHealthProbe)
{
var redundancy = services.GetService<WarmRedundancySettings>() ?? WarmRedundancySettings.Unset;
return OpcUaPublishActor.Props(sink: sink, serviceLevel: serviceLevel, localNode: localNode,
dbFactory: dbFactory, applier: applier, dbHealthProbe: dbHealthProbe, dbLess: dbFactory is null,
dataPlaneAuthority: services.GetService<IDataPlaneAuthoritySink>(),
endpointState: services.GetService<IOpcUaEndpointState>(), redundancy: redundancy,
standbyProjection: redundancy.IsWarm ? services.GetService<DeferredStandbyProjection>() : null,
dataCatalog: services.GetService<CatalogActivation>(), catalogCoordinator: services.GetService<LocalCatalogCoordinator>(),
dataWarmRole: services.GetService<DataConnectionWarmRoleView>(), dataConnections: services.GetService<DataConnectionDeploymentRuntime>());
}
}
@@ -0,0 +1,18 @@
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Adapts existing local redundancy verdicts to import activation, without electing a role.</summary>
public static class DataConnectionRoleAdapter
{
public static bool MayAcquire(RedundancyMode mode, WarmRole? warmRole, RedundancyRole? role) => mode switch
{
RedundancyMode.Warm => warmRole == WarmRole.Active,
RedundancyMode.Hot => role is RedundancyRole.Primary or RedundancyRole.Secondary,
RedundancyMode.None => role == RedundancyRole.Primary,
_ => false
};
public static bool MayWrite(RedundancyRole? role) => role == RedundancyRole.Primary;
}
@@ -0,0 +1,66 @@
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>An immutable Warm verdict and its process-local change generation.</summary>
public sealed record DataConnectionWarmRoleSnapshot(WarmRole? Role, long Generation);
/// <summary>Publishes the active OPC UA publisher's actual Warm verdict under the shared dispatch fence.</summary>
public sealed class DataConnectionWarmRoleView
{
private sealed record State(long Owner, DataConnectionWarmRoleSnapshot Snapshot);
private State _state = new(0, new(null, 0));
private long _nextOwner;
private bool _poisoned;
public DataConnectionWarmRoleView(DataWriteDispatchFence dispatchFence) =>
DispatchFence = dispatchFence ?? throw new ArgumentNullException(nameof(dispatchFence));
public DataWriteDispatchFence DispatchFence { get; }
public DataConnectionWarmRoleSnapshot Snapshot => Volatile.Read(ref _state).Snapshot;
public WarmRole? CurrentRole => Snapshot.Role;
public long Generation => Snapshot.Generation;
/// <summary>Replaces the publisher owner and immediately withdraws the old verdict.</summary>
public long RegisterOwner()
{
using (DispatchFence.Enter())
{
var current = _state;
if (_poisoned || _nextOwner == long.MaxValue || current.Snapshot.Generation == long.MaxValue)
{ Poison(); throw new InvalidOperationException("Warm role generation exhausted."); }
var owner = ++_nextOwner;
Volatile.Write(ref _state, new State(owner, new(null, current.Snapshot.Generation + 1)));
return owner;
}
}
/// <summary>Publishes only for the current owner; returns true when the verdict changes.</summary>
public bool Publish(long owner, WarmRole role)
{
if (!Enum.IsDefined(role)) throw new ArgumentOutOfRangeException(nameof(role));
using (DispatchFence.Enter())
{
var current = _state;
if (_poisoned || owner == 0 || current.Owner != owner || current.Snapshot.Role == role) return false;
if (current.Snapshot.Generation == long.MaxValue) { Poison(); return true; }
Volatile.Write(ref _state, new State(owner, new(role, current.Snapshot.Generation + 1)));
return true;
}
}
/// <summary>Withdraws a current owner's verdict; a superseded owner cannot affect its successor.</summary>
public bool RetireOwner(long owner)
{
using (DispatchFence.Enter())
{
var current = _state;
if (_poisoned || owner == 0 || current.Owner != owner) return false;
if (current.Snapshot.Generation == long.MaxValue) { Poison(); return true; }
Volatile.Write(ref _state, new State(0, new(null, current.Snapshot.Generation + 1)));
return true;
}
}
private void Poison()
{
_poisoned = true;
Volatile.Write(ref _state, new State(0, new(null, long.MaxValue)));
}
}
@@ -1165,6 +1165,8 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
prepared = await sink.PrepareAsync(frame, _limits.MaxPendingBytes, cancellationToken).ConfigureAwait(false);
if (prepared is null || prepared.RetainedBytes < 0 || prepared.RetainedBytes > _limits.MaxPendingBytes)
{ if (!pending.IsObsolete()) Stop(); return; }
if (prepared is IDataPreparedSubscriptionPublication publication)
publication.SetPublicationGuard(pending.Gate);
if (!pending.IsEligible()) return;
var rate = pending.ConsumeSnapshot(prepared.RetainedBytes);
if (!rate.Accepted) { CloseWithReset($"Snapshot pacing; retry after {rate.Retry.TotalMilliseconds:F0} ms."); return; }
@@ -47,8 +47,10 @@ internal sealed class DataWriteDispatchGate
{
// These are immutable reads only. Writers acquire their own state lock first, then this fence.
var utcNow = clock.GetUtcNow();
var liveServing = coordinator.Serving;
if (!ReferenceEquals(snapshot, authority.Current) || !ReferenceEquals(activationSnapshot, activation.Current)
|| !coordinator.IsPublished(catalog) || !activationSnapshot.IsReady
|| proof.Serving is null || catalog.Serving != proof.Serving || liveServing != proof.Serving
|| admission.AuthorityEpoch != snapshot.GenerationId || admission.CatalogRevision != activationSnapshot.CatalogEpoch
|| admission.ServingIncarnation != catalog.Serving.Incarnation
|| !role.ShouldActAsPrimary || role.PrimaryGeneration <= 0 || role.PrimaryGeneration != proof.PrimaryGeneration
@@ -119,7 +119,7 @@ internal sealed class DataWriteExecutor(DataAuthenticatedContext context, Func<L
expiration, context.ApiKeyId, context.CredentialExpiresUtc, context.CredentialVersion);
var scope = new FrozenWriteScope(node.Scope.ClusterId, node.Scope.Kind, node.Scope.Segments.ToImmutableArray());
var proof = new WriteRouteProof(admission, scope, node.EntityKind, node.EntityId, node.Source,
target.DriverInstanceId, target.DriverReference, target.RouteGeneration, target.PrimaryGeneration);
target.DriverInstanceId, target.DriverReference, target.RouteGeneration, target.PrimaryGeneration, current.Serving);
ticket = new WriteAdmissionTicket(proof, item.Value.Retain(), issued, lease);
}
catch
@@ -0,0 +1,774 @@
using System.Runtime.CompilerServices;
using Google.Protobuf;
using Grpc.Core;
using Grpc.Net.Client;
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
using ZB.MOM.WW.OtOpcUa.Commons.Protos;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Versioned security material supplied by the consuming host.</summary>
public sealed record DataConnectionSecurity(string CredentialVersion, string TrustFingerprint, string Bearer,
Func<HttpMessageHandler> CreateHandler)
{
public override string ToString() => $"DataConnectionSecurity {{ CredentialVersion = {CredentialVersion}, TrustFingerprint = {TrustFingerprint}, Bearer = [redacted] }}";
}
public interface IDataConnectionSecurityProvider
{
ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken);
event Action<string>? Changed;
}
public sealed record DataConnectionChannelIdentity(string ConnectionId, Uri Endpoint, string CredentialVersion, string TrustFingerprint);
/// <summary>Caller-bound remote facade. All channels and requests are bounded by configured local limits.</summary>
public sealed class GrpcDataConnection : IDataConnection
{
private sealed class ChannelEntry(DataConnectionChannelIdentity identity, GrpcChannel channel, string bearer)
{
internal readonly DataConnectionChannelIdentity Identity = identity;
internal readonly GrpcChannel Channel = channel;
internal readonly W.DataConnectionService.DataConnectionServiceClient Client = new(channel);
internal readonly string Bearer = bearer;
internal readonly CancellationTokenSource Retired = new();
}
private sealed record Selected(ChannelEntry Channel, DataCapabilities Capabilities);
private readonly object _sync = new();
private readonly string _id;
private readonly Uri[] _endpoints;
private readonly HashSet<string>? _eligibleNodeIds;
private readonly IDataConnectionSecurityProvider _security;
private readonly DataConnectionScopeLease _scope;
private readonly int _maxMessageBytes, _maxChannels, _maxStreams, _maxMonitoredItems, _maxPendingCommands;
private readonly TimeSpan _maxCommandTimeout;
private readonly SemaphoreSlim _unaryCapacity;
private readonly CommandStateBudget _commandBudget;
private readonly Dictionary<DataConnectionChannelIdentity, ChannelEntry> _channels = new();
private bool _disposed;
private long _securityGeneration;
private int _activeStreams, _retiringChannels, _activeWork;
private readonly HashSet<RemoteSubscription> _streams = new();
private readonly CancellationTokenSource _shutdown = new();
private readonly TaskCompletionSource _drained = new(TaskCreationOptions.RunContinuationsAsynchronously);
private Task? _disposeTask, _shutdownCancellation;
private long _nextProbeTimestamp;
private int _probeFailures;
private readonly Dictionary<string, long> _streamEpochs = new(StringComparer.Ordinal);
private long _streamEpochBytes;
internal Func<Task>? BeforeStreamInstallForTests { get; set; }
internal Action<WeakReference>? PendingIdentityObserverForTests { get; set; }
internal Func<Task>? AfterTimerCancelledForTests { get; set; }
public DataTarget Target { get; }
public TimeProvider Clock { get; }
public GrpcDataConnection(string connectionId, DataTarget target, IEnumerable<Uri> endpoints,
IDataConnectionSecurityProvider security, DataConnectionScopeLease scope, int maxMessageBytes,
int maxChannels, TimeProvider? clock = null, IReadOnlySet<string>? eligibleNodeIds = null,
int maxStreams = 16, int maxMonitoredItems = 10_000, int maxPendingCommands = 256,
int maxConcurrentUnaryCalls = 64, TimeSpan? maxCommandTimeout = null, long maxPendingCommandBytes = 4 * 1024 * 1024)
{
ArgumentException.ThrowIfNullOrWhiteSpace(connectionId);
ArgumentNullException.ThrowIfNull(target); target.Validate();
ArgumentNullException.ThrowIfNull(endpoints);
_endpoints = endpoints.Distinct().ToArray();
if (_endpoints.Length == 0 || _endpoints.Any(x => !x.IsAbsoluteUri || x.Scheme != Uri.UriSchemeHttps))
throw new ArgumentException("Only configured HTTPS endpoints are accepted.", nameof(endpoints));
if (maxMessageBytes <= 0 || maxChannels <= 0 || _endpoints.Length > maxChannels || maxStreams <= 0 ||
maxMonitoredItems <= 0 || maxPendingCommands <= 0 || maxConcurrentUnaryCalls <= 0 || maxPendingCommandBytes <= 0)
throw new ArgumentOutOfRangeException(nameof(maxChannels));
_maxCommandTimeout = maxCommandTimeout ?? TimeSpan.FromSeconds(30);
if (_maxCommandTimeout <= TimeSpan.Zero || _maxCommandTimeout > TimeSpan.FromDays(1)) throw new ArgumentOutOfRangeException(nameof(maxCommandTimeout));
_maxStreams = maxStreams; _maxMonitoredItems = maxMonitoredItems; _maxPendingCommands = maxPendingCommands;
_unaryCapacity = new(maxConcurrentUnaryCalls, maxConcurrentUnaryCalls);
_commandBudget = new CommandStateBudget(Math.Min(maxPendingCommandBytes, 4L * 1024 * 1024));
if (target.Mode == DataTargetMode.Cluster && (eligibleNodeIds is null || eligibleNodeIds.Count == 0 || eligibleNodeIds.Any(string.IsNullOrWhiteSpace)))
throw new ArgumentException("Cluster targets require configured eligible node identities.", nameof(eligibleNodeIds));
_eligibleNodeIds = eligibleNodeIds is null ? null : new(eligibleNodeIds, StringComparer.OrdinalIgnoreCase);
_id = connectionId; Target = target; _security = security ?? throw new ArgumentNullException(nameof(security));
_scope = scope ?? throw new ArgumentNullException(nameof(scope)); _maxMessageBytes = maxMessageBytes; _maxChannels = maxChannels;
Clock = clock ?? TimeProvider.System;
_security.Changed += SecurityChanged;
}
public static int[] RetryableWriteIndexes(IReadOnlyList<WriteItemResult> outcomes) => outcomes
.Select((item, index) => (item, index)).Where(x => x.item.Outcome.State == DataWriteState.RejectedBeforeDispatch)
.Select(x => x.index).ToArray();
private sealed class CommandStateBudget(long maximum)
{
private readonly object _gate = new();
private long _used;
internal bool TryReserve(long amount)
{
lock (_gate) { if (amount < 0 || amount > maximum - _used) return false; _used += amount; return true; }
}
internal void Release(long amount) { lock (_gate) { _used -= amount; } }
}
private void SecurityChanged(string connectionId)
{
if (!string.Equals(_id, connectionId, StringComparison.OrdinalIgnoreCase)) return;
lock (_sync) { _nextProbeTimestamp = 0; _probeFailures = 0; }
RetireAll();
}
private bool ProbeAllowed() { lock (_sync) return _nextProbeTimestamp == 0 || Clock.GetTimestamp() >= _nextProbeTimestamp; }
private void ProbeSucceeded() { lock (_sync) { _probeFailures = 0; _nextProbeTimestamp = 0; } }
private void ProbeFailed()
{
lock (_sync)
{
var power = _probeFailures;
_probeFailures = Math.Min(_probeFailures + 1, 7);
var milliseconds = Math.Min(30_000d, 250d * (1 << power)) * (0.8 + Random.Shared.NextDouble() * 0.4);
_nextProbeTimestamp = checked(Clock.GetTimestamp() + (long)(milliseconds / 1000d * Clock.TimestampFrequency));
}
}
private bool ClaimStreamEpoch(string id, long epoch)
{
lock (_sync)
{
if (_disposed || string.IsNullOrWhiteSpace(id) || epoch <= 0 ||
_streamEpochs.TryGetValue(id, out var previous) && epoch <= previous) return false;
if (!_streamEpochs.ContainsKey(id))
{
var charge = checked(64L + 2L * id.Length);
if (_streamEpochs.Count >= 100_000 || _streamEpochBytes + charge > 4 * 1024 * 1024) return false;
_streamEpochBytes += charge;
}
_streamEpochs[id] = epoch; return true;
}
}
private void RetireAll()
{
lock (_sync)
{
_securityGeneration++;
foreach (var item in _channels.Values)
{
_retiringChannels++;
var cancelled = item.Retired.CancelAsync();
_ = FinishChannelRetirementAsync(item, cancelled);
}
_channels.Clear();
}
}
private async Task FinishChannelRetirementAsync(ChannelEntry item, Task cancelled)
{
// Physical Dispose and arbitrary cancellation callbacks may block. Keep quota charged until both end.
await Task.Yield();
try { await Task.WhenAll(cancelled, Task.Run(item.Channel.Dispose)).ConfigureAwait(false); }
catch (Exception) { }
finally
{
item.Retired.Dispose();
lock (_sync) { _retiringChannels--; CheckDrainedLocked(); }
}
}
private void EnterWork()
{
lock (_sync) { Check(); _activeWork++; }
}
private void ExitWork()
{
lock (_sync) { _activeWork--; CheckDrainedLocked(); }
}
private void CheckDrainedLocked()
{
if (_disposed && _activeWork == 0 && _retiringChannels == 0 && _activeStreams == 0) _drained.TrySetResult();
}
private void Check() { ObjectDisposedException.ThrowIf(_disposed, this); _scope.CancellationToken.ThrowIfCancellationRequested(); }
private async Task<ChannelEntry> ChannelAsync(Uri endpoint, CancellationToken ct)
{
long generation;
lock (_sync) { Check(); generation = _securityGeneration; }
var security = await _security.ResolveAsync(_id, endpoint, ct).ConfigureAwait(false)
?? throw new UnauthorizedAccessException("Connection credential or trust unavailable.");
ArgumentException.ThrowIfNullOrWhiteSpace(security.CredentialVersion);
ArgumentException.ThrowIfNullOrWhiteSpace(security.TrustFingerprint);
ArgumentException.ThrowIfNullOrWhiteSpace(security.Bearer);
var key = new DataConnectionChannelIdentity(_id, endpoint, security.CredentialVersion, security.TrustFingerprint);
lock (_sync)
{
Check();
if (generation != _securityGeneration) throw new InvalidOperationException("Security changed while resolving.");
if (_channels.TryGetValue(key, out var existing)) return existing;
if (_channels.Count + _retiringChannels >= _maxChannels) throw new InvalidOperationException("Channel capacity exhausted.");
var handler = security.CreateHandler();
try
{
var channel = GrpcChannel.ForAddress(endpoint, new GrpcChannelOptions { HttpHandler = handler,
DisposeHttpClient = true, DisableResolverServiceConfig = true,
MaxReceiveMessageSize = _maxMessageBytes, MaxSendMessageSize = _maxMessageBytes });
var entry = new ChannelEntry(key, channel, security.Bearer);
_channels.Add(key, entry); return entry;
}
catch { handler.Dispose(); throw; }
}
}
private Metadata Headers(ChannelEntry channel)
{
var headers = new Metadata { { "authorization", "Bearer " + channel.Bearer },
{ "x-data-target-mode", Target.Mode.ToString() }, { "x-data-consistency", Target.Consistency.ToString() },
{ "x-data-cluster-id", Target.ExpectedClusterId } };
if (Target.Mode == DataTargetMode.Node) headers.Add("x-data-node-id", Target.ExpectedNodeId!);
return headers;
}
private TimeSpan Remaining(long start, DataBudget budget)
{
var remaining = budget.Timeout - Clock.GetElapsedTime(start);
if (remaining <= TimeSpan.Zero) throw new TimeoutException("Original data request budget expired.");
return remaining;
}
private CallOptions Options(ChannelEntry channel, long start, DataBudget budget, CancellationToken ct) =>
new(Headers(channel), DateTime.UtcNow + Remaining(start, budget), ct);
private DataDecodeLimits Limits(DataBudget budget, DataCapabilities caps) => new(Math.Min(budget.MaxItems, caps.Limits.MaxBatchItems),
(int)Math.Min(Math.Min(budget.MaxBytes, _maxMessageBytes), caps.Limits.MaxMessageBytes), caps.Limits.MaxValueElements);
private async Task<Selected> SelectAsync(Uri endpoint, long start, DataBudget budget, bool write, CancellationToken ct)
{
var channel = await ChannelAsync(endpoint, ct).ConfigureAwait(false);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _scope.CancellationToken, channel.Retired.Token, _shutdown.Token);
var response = await channel.Client.GetCapabilitiesAsync(new W.CapabilitiesRequest { ProtocolMajor = 1, ProtocolMinor = 2 },
Options(channel, start, budget, linked.Token)).ResponseAsync.ConfigureAwait(false);
var caps = DataProtoMapper.DecodeCapabilities(response, new DataDecodeLimits(budget.MaxItems, _maxMessageBytes));
if (!caps.ResponseServingIdentity || caps.Serving.ServingGeneration <= 0 || !ClusterEndpointSelector.IsEligible(Target, caps, write) ||
Target.Mode == DataTargetMode.Cluster && !_eligibleNodeIds!.Contains(caps.Serving.NodeId))
throw new InvalidOperationException("Endpoint is not an authenticated ready target.");
linked.Token.ThrowIfCancellationRequested();
return new(channel, caps);
}
private static void Verify(W.Serving? serving, Selected selected)
{
if (serving is null || DataProtoMapper.DecodeServing(serving) != selected.Capabilities.Serving)
throw new InvalidOperationException("Response serving identity changed.");
selected.Channel.Retired.Token.ThrowIfCancellationRequested();
}
private async Task<T> QueryAsync<T>(DataBudget budget, Func<Selected, DataBudget, CallOptions, Task<T>> call, CancellationToken ct)
{
budget.Validate(); var start = Clock.GetTimestamp(); Exception? failure = null;
EnterWork();
var admitted = false;
try
{
using var admission = CancellationTokenSource.CreateLinkedTokenSource(ct, _scope.CancellationToken, _shutdown.Token);
admitted = await _unaryCapacity.WaitAsync(0, admission.Token).ConfigureAwait(false);
if (!admitted) throw new InvalidOperationException("Unary capacity exhausted.");
if (!ProbeAllowed()) throw new InvalidOperationException("Data endpoint discovery is backing off.");
foreach (var endpoint in _endpoints)
{
Check();
try
{
var selected = await SelectAsync(endpoint, start, budget, false, ct).ConfigureAwait(false);
ProbeSucceeded();
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _scope.CancellationToken, selected.Channel.Retired.Token, _shutdown.Token);
var remaining = budget with { Timeout = Remaining(start, budget) };
var result = await call(selected, remaining, Options(selected.Channel, start, budget, linked.Token)).ConfigureAwait(false);
try { linked.Token.ThrowIfCancellationRequested(); return result; }
catch { if (result is IEnumerable<ReadResult> reads) foreach (var item in reads) item.Dispose(); throw; }
}
catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException)
{ failure = ex; }
}
ProbeFailed();
throw new InvalidOperationException("No ready authenticated data endpoint.", failure);
}
finally { if (admitted) _unaryCapacity.Release(); ExitWork(); }
}
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) =>
QueryAsync(budget, (selected, _, _) => Task.FromResult(selected.Capabilities), cancellationToken);
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) =>
QueryAsync(request.Budget, async (selected, budget, options) =>
{
var wire = await selected.Channel.Client.BrowseAsync(DataProtoMapper.EncodeBrowseRequest(request with { Budget = budget }), options).ResponseAsync.ConfigureAwait(false);
Verify(wire.Serving, selected); var result = DataProtoMapper.DecodeBrowseResponse(wire, Limits(budget, selected.Capabilities));
if (result.Lease is { } lease && (lease.CatalogEpoch != selected.Capabilities.Serving.CatalogEpoch ||
lease.AuthorityEpoch != selected.Capabilities.Serving.AuthorityEpoch || lease.Duration > selected.Capabilities.Limits.MaxMetadataLease))
throw new InvalidOperationException("Browse lease has unexpected authority or duration.");
if (result.Parent != request.Parent || result.Items.Any(x => !string.Equals(x.View.Address.OriginClusterId, selected.Capabilities.ClusterId, StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException("Browse response has unexpected provenance.");
Verify(wire.Serving, selected); return result;
}, cancellationToken);
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) =>
QueryAsync(request.Budget, async (selected, budget, options) =>
{
var wire = await selected.Channel.Client.GetMetadataAsync(DataProtoMapper.EncodeMetadataRequest(request with { Budget = budget }), options).ResponseAsync.ConfigureAwait(false);
Verify(wire.Serving, selected); var result = DataProtoMapper.DecodeMetadataResponse(wire, Limits(budget, selected.Capabilities));
if (result.Count != request.Views.Count || result.Where((x, i) => x.CorrelationId != i.ToString(System.Globalization.CultureInfo.InvariantCulture) ||
x.Value is not null && x.Value.View.Address != request.Views[i].Address).Any())
throw new InvalidOperationException("Metadata response has unexpected items.");
Verify(wire.Serving, selected); return result;
}, cancellationToken);
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken)
{
var start = Clock.GetTimestamp();
return QueryAsync(request.Budget, async (selected, budget, options) =>
{
var wire = await selected.Channel.Client.ReadAsync(DataProtoMapper.EncodeReadRequest(request with { Budget = budget }), options).ResponseAsync.ConfigureAwait(false);
Verify(wire.Serving, selected);
var result = DataProtoMapper.DecodeReadResponse(wire, Limits(budget, selected.Capabilities), Clock.GetElapsedTime(start));
try
{
if (result.Count != request.Items.Count || !result.Select(x => x.CorrelationId).SequenceEqual(request.Items.Select(x => x.CorrelationId)) ||
result.Any(x => x.Sample is not null && x.Sample.Serving != selected.Capabilities.Serving))
throw new InvalidOperationException("Read response has unexpected items or serving identity.");
Verify(wire.Serving, selected); return result;
}
catch { foreach (var item in result) item.Dispose(); throw; }
}, cancellationToken);
}
public async Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken)
{
request.Budget.Validate();
var admissionStart = Clock.GetTimestamp();
EnterWork();
var admitted = false;
try
{
using var admission = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken, _shutdown.Token);
admitted = await _unaryCapacity.WaitAsync(0, admission.Token).ConfigureAwait(false);
if (!admitted) return request.Items.Select(x => new WriteItemResult(x.CorrelationId,
new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Unary capacity exhausted."))).ToArray();
var elapsed = Clock.GetElapsedTime(admissionStart);
var remaining = Remaining(admissionStart, request.Budget);
var reduced = request with { Budget = request.Budget with { Timeout = remaining },
Items = request.Items.Select(x => x with { RemainingBudget = x.RemainingBudget - elapsed }).ToArray() };
return await WriteCoreAsync(reduced, cancellationToken).ConfigureAwait(false);
}
finally { if (admitted) _unaryCapacity.Release(); ExitWork(); }
}
private async Task<IReadOnlyList<WriteItemResult>> WriteCoreAsync(WriteBatch request, CancellationToken cancellationToken)
{
request.Budget.Validate();
ArgumentNullException.ThrowIfNull(request.Items);
var start = Clock.GetTimestamp();
var results = request.Items.Select(x => new WriteItemResult(x.CorrelationId,
new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "No ready endpoint."))).ToArray();
if (!ProbeAllowed()) return results;
var eligible = Enumerable.Range(0, request.Items.Count).ToArray();
var attempted = false;
foreach (var endpoint in _endpoints)
{
if (eligible.Length == 0) break;
cancellationToken.ThrowIfCancellationRequested();
Selected selected;
try { selected = await SelectAsync(endpoint, start, request.Budget, true, cancellationToken).ConfigureAwait(false); ProbeSucceeded(); }
catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException or TimeoutException)
{ continue; }
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken, selected.Channel.Retired.Token, _shutdown.Token);
var items = eligible.Select(i => request.Items[i]).ToArray();
if (attempted)
{
// A retry needs fresh, authenticated metadata from the new primary. Never infer a
// catalog revision from its serving epoch or reuse the old node incarnation.
try
{
var remaining = Remaining(start, request.Budget);
var budget = request.Budget with { Timeout = remaining };
var metadataRequest = new MetadataRequest(items.Select(x => x.View).ToArray(), budget);
var wireMetadata = await selected.Channel.Client.GetMetadataAsync(DataProtoMapper.EncodeMetadataRequest(metadataRequest),
Options(selected.Channel, start, request.Budget, linked.Token)).ResponseAsync.ConfigureAwait(false);
Verify(wireMetadata.Serving, selected);
var metadata = DataProtoMapper.DecodeMetadataResponse(wireMetadata, Limits(budget, selected.Capabilities));
if (metadata.Count != items.Length || metadata.Where((x, i) => x.CorrelationId != i.ToString(System.Globalization.CultureInfo.InvariantCulture) ||
x.Status != DataItemStatus.Good || x.Value is null || x.Value.View.Address != items[i].View.Address ||
!x.Value.Writable || (x.Value.AllowedOperations & DataOperations.Write) == 0).Any()) continue;
linked.Token.ThrowIfCancellationRequested(); Verify(wireMetadata.Serving, selected);
items = items.Select((x, i) => x with { ExpectedCatalogRevision = metadata[i].Value!.CatalogRevision,
ExpectedServingIncarnation = selected.Capabilities.Serving.Incarnation }).ToArray();
}
catch (Exception ex) when (ex is RpcException or InvalidOperationException or ArgumentException or TimeoutException or OperationCanceledException)
{ if (cancellationToken.IsCancellationRequested || _scope.CancellationToken.IsCancellationRequested) break; continue; }
}
var elapsed = Clock.GetElapsedTime(start);
var live = Enumerable.Range(0, items.Length).Where(i => items[i].RemainingBudget > elapsed).ToArray();
foreach (var i in Enumerable.Range(0, items.Length).Except(live))
results[eligible[i]] = new(request.Items[eligible[i]].CorrelationId,
new(DataWriteState.RejectedBeforeDispatch, 0x800A0000u, "Item budget expired before dispatch."));
eligible = live.Select(i => eligible[i]).ToArray();
items = live.Select(i => items[i] with { RemainingBudget = items[i].RemainingBudget - elapsed }).ToArray();
if (eligible.Length == 0) break;
var dispatchStarted = false;
try
{
var remaining = Remaining(start, request.Budget);
var batch = new WriteBatch(items.Select(x => x with { RemainingBudget = x.RemainingBudget < remaining ? x.RemainingBudget : remaining }).ToArray(),
request.Budget with { Timeout = remaining });
var options = Options(selected.Channel, start, request.Budget, linked.Token);
var encoded = DataProtoMapper.EncodeWriteRequest(batch);
linked.Token.ThrowIfCancellationRequested();
dispatchStarted = true;
var wire = await selected.Channel.Client.WriteAsync(encoded, options).ResponseAsync.ConfigureAwait(false);
var decoded = DataProtoMapper.DecodeWriteResponse(wire, Limits(batch.Budget, selected.Capabilities));
if (decoded.Count != items.Length || !decoded.Select(x => x.CorrelationId).SequenceEqual(items.Select(x => x.CorrelationId)))
throw new InvalidOperationException("Invalid write result sequence.");
VerifyWriteEnvelope(wire.Serving, selected, decoded);
linked.Token.ThrowIfCancellationRequested();
for (var i = 0; i < eligible.Length; i++) results[eligible[i]] = decoded[i];
eligible = eligible.Where((_, i) => decoded[i].Outcome.State == DataWriteState.RejectedBeforeDispatch).ToArray();
attempted = true;
}
catch (Exception ex) when (ex is RpcException or HttpRequestException or OperationCanceledException or InvalidOperationException or ArgumentException or TimeoutException)
{
if (dispatchStarted)
foreach (var index in eligible) results[index] = new(request.Items[index].CorrelationId,
new(DataWriteState.OutcomeUnknown, 0x800A0000u, "Write outcome unknown."));
break;
}
}
if (!attempted && eligible.Length > 0) ProbeFailed();
return results;
}
private static void VerifyWriteEnvelope(W.Serving? serving, Selected selected, IReadOnlyList<WriteItemResult> results)
{
if (serving is null) throw new InvalidOperationException("Missing write serving identity.");
var actual = DataProtoMapper.DecodeServing(serving);
var expected = selected.Capabilities.Serving;
if (!AcceptWriteServing(expected, actual, results))
throw new InvalidOperationException("Write serving identity changed.");
selected.Channel.Retired.Token.ThrowIfCancellationRequested();
}
internal static bool AcceptWriteServing(ServingIdentity expected, ServingIdentity actual, IReadOnlyList<WriteItemResult> results) =>
actual == expected || actual.NodeId == expected.NodeId && actual.Incarnation == expected.Incarnation &&
results.Count > 0 && results.All(x => x.Outcome.State == DataWriteState.RejectedBeforeDispatch);
public async Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
{
EnterWork();
var reserved = false;
try
{
if (!ProbeAllowed()) throw new InvalidOperationException("Data endpoint discovery is backing off.");
while (true)
{
var count = Volatile.Read(ref _activeStreams);
if (count >= _maxStreams) throw new InvalidOperationException("Stream capacity exhausted.");
if (Interlocked.CompareExchange(ref _activeStreams, count + 1, count) == count) { reserved = true; break; }
}
var budget = new DataBudget(TimeSpan.FromSeconds(5), 1000, _maxMessageBytes);
var start = Clock.GetTimestamp(); Exception? failure = null;
foreach (var endpoint in _endpoints)
{
try
{
var selected = await SelectAsync(endpoint, start, budget, false, cancellationToken).ConfigureAwait(false);
if ((selected.Capabilities.Operations & DataOperations.Subscribe) == 0 ||
Volatile.Read(ref _activeStreams) > selected.Capabilities.Limits.MaxStreams)
throw new InvalidOperationException("Subscriptions unavailable or peer stream capacity exhausted.");
ProbeSucceeded();
var lifetime = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken, selected.Channel.Retired.Token, _shutdown.Token);
RemoteSubscription? subscription = null;
var transferred = false;
try
{
var call = selected.Channel.Client.Subscribe(Headers(selected.Channel), cancellationToken: lifetime.Token);
subscription = new RemoteSubscription(call, selected, lifetime, _maxMessageBytes,
Math.Min(_maxMonitoredItems, selected.Capabilities.Limits.MaxMonitoredItems), _maxPendingCommands,
_maxCommandTimeout, _commandBudget, ClaimStreamEpoch, PendingIdentityObserverForTests, AfterTimerCancelledForTests, () => { lock (_sync) { _streams.Remove(subscription!); Interlocked.Decrement(ref _activeStreams); CheckDrainedLocked(); } });
if (BeforeStreamInstallForTests is { } pause) await pause().ConfigureAwait(false);
lock (_sync)
{
_streams.Add(subscription); reserved = false; transferred = true;
if (_disposed) throw new ObjectDisposedException(nameof(GrpcDataConnection));
}
subscription.ObserveLifetime();
return subscription;
}
catch
{
if (subscription is null) lifetime.Dispose();
else
{
// Once a call exists, even a failed install owns a raw-send receipt.
// Transfer its slot first; cleanup and the receipt run outside this lock.
if (!transferred)
{
lock (_sync) { _streams.Add(subscription); reserved = false; }
}
_ = subscription.DisposeAsync();
}
throw;
}
}
catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException)
{ failure = ex; }
}
ProbeFailed();
throw new InvalidOperationException("No ready subscription endpoint.", failure);
}
finally
{
if (reserved) { lock (_sync) { Interlocked.Decrement(ref _activeStreams); CheckDrainedLocked(); } }
ExitWork();
}
}
private sealed class RemoteSubscription(
AsyncDuplexStreamingCall<W.SubscriptionCommand, W.SubscriptionFrame> call, Selected selected,
CancellationTokenSource lifetime, int maxBytes, int maxItems, int maxPendingCommands,
TimeSpan maxCommandTimeout, CommandStateBudget commandBudget, Func<string, long, bool> claimEpoch, Action<WeakReference>? observePending,
Func<Task>? afterTimerCancelled, Action release) : IDataSubscription
{
private readonly SemaphoreSlim _send = new(1, 1);
private readonly Task _headersReceipt = call.ResponseHeadersAsync;
private Dictionary<ulong, DataItemHandle> _handles = new();
private Dictionary<string, ulong> _clientHandles = new(StringComparer.Ordinal);
private HashSet<ulong> _usedHandles = new();
private Dictionary<ulong, long> _versions = new();
private sealed record PendingCommand(string Id, string[]? ClientIds, DataItemHandle[]? Removed,
bool IsModify, TimeSpan Timeout, long Bytes, CancellationTokenSource Timer);
private readonly Dictionary<string, PendingCommand> _pending = new(StringComparer.Ordinal);
private long _pendingBytes, _usedCommandBytes;
private readonly HashSet<string> _usedCommands = new(StringComparer.Ordinal);
private string? _id;
private long _epoch, _sequence;
private int _disposed, _reading, _operations;
private bool _physicalClosed, _released;
private readonly object _lifecycle = new();
private readonly TaskCompletionSource _closed = new(TaskCreationOptions.RunContinuationsAsynchronously);
private CancellationTokenRegistration _retirementRegistration;
internal void ObserveLifetime() => _retirementRegistration = lifetime.Token.Register(() => { _ = Task.Run(async () => await DisposeAsync()); });
private void EnterOperation()
{
lock (_lifecycle) { ObjectDisposedException.ThrowIf(_disposed != 0, this); _operations++; }
}
private void ExitOperation()
{
bool finish;
lock (_lifecycle) { _operations--; finish = TryFinishLocked(); }
if (finish) Finish();
}
private bool TryFinishLocked()
{
if (_disposed == 0 || !_physicalClosed || _operations != 0 || _released) return false;
_released = true; return true;
}
private void Finish()
{
_retirementRegistration.Dispose();
lock (_pending)
{
foreach (var pending in _pending.Values) { pending.Timer.Cancel(); pending.Timer.Dispose(); }
_pending.Clear();
commandBudget.Release(checked(_pendingBytes + _usedCommandBytes));
_pendingBytes = 0; _usedCommandBytes = 0;
}
lifetime.Dispose(); release(); _closed.TrySetResult();
}
public async Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
{
EnterOperation();
try
{
ArgumentNullException.ThrowIfNull(command);
if (command.AcknowledgementTimeout <= TimeSpan.Zero || command.AcknowledgementTimeout > maxCommandTimeout)
throw new ArgumentOutOfRangeException(nameof(command));
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, lifetime.Token);
linked.CancelAfter(command.AcknowledgementTimeout);
if (!await _send.WaitAsync(0, linked.Token).ConfigureAwait(false)) throw new InvalidOperationException("A command is already being sent.");
try
{
if (_id is null)
{
if (command is not OpenSubscription) throw new InvalidOperationException("First command must open the stream.");
if (!claimEpoch(command.SubscriptionId, command.StreamEpoch))
throw new InvalidOperationException("Subscription epoch was already used or history capacity exhausted.");
_id = command.SubscriptionId; _epoch = command.StreamEpoch;
}
if (command.SubscriptionId != _id || command.StreamEpoch != _epoch || command.StreamEpoch <= 0)
throw new InvalidOperationException("Command belongs to another stream epoch.");
var count = command switch { OpenSubscription o => o.Items.Count, AddSubscriptionItems a => a.Items.Count,
ModifySubscriptionItems m => m.Items.Count, RemoveSubscriptionItems r => r.Items.Count, _ => maxItems + 1 };
if (count > maxItems) throw new InvalidOperationException("Command item capacity exceeded.");
var encoded = DataProtoMapper.EncodeCommand(command);
if (encoded.CalculateSize() > Math.Min(maxBytes, selected.Capabilities.Limits.MaxMessageBytes))
throw new InvalidOperationException("Command byte capacity exceeded.");
string[]? ids = command switch
{
OpenSubscription => encoded.Open.Items.Select(x => x.ClientItemId).ToArray(),
AddSubscriptionItems => encoded.Add.Items.Select(x => x.ClientItemId).ToArray(),
ModifySubscriptionItems => encoded.Modify.Items.Select(x => x.ClientItemId).ToArray(),
_ => null
};
var removed = command is RemoveSubscriptionItems ? encoded.Remove.Items.Select(DataProtoMapper.DecodeHandle).ToArray() : null;
long charge = checked(256L + 2L * encoded.CommandId.Length + (ids?.Sum(x => 64L + 2L * x.Length) ?? 0L) +
(removed?.Sum(x => 96L + 2L * x.SubscriptionId.Length) ?? 0L));
var pending = new PendingCommand(encoded.CommandId, ids, removed, command is ModifySubscriptionItems,
command.AcknowledgementTimeout, charge, CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token));
lock (_pending)
{
var commandLimit = (int)Math.Min(100_000L, Math.Max(1024L, 4L * maxItems));
long usedCharge = checked(64L + 2L * pending.Id.Length);
if (_pending.Count >= maxPendingCommands || _usedCommands.Count >= commandLimit || _usedCommands.Contains(pending.Id) ||
!commandBudget.TryReserve(checked(charge + usedCharge)))
{ pending.Timer.Dispose(); throw new InvalidOperationException("Command capacity or duplicate command."); }
_usedCommands.Add(pending.Id); _pending.Add(pending.Id, pending);
_pendingBytes += charge; _usedCommandBytes += usedCharge;
}
if (pending.ClientIds is not null) observePending?.Invoke(new WeakReference(pending.ClientIds));
_ = ExpireUnacknowledgedAsync(pending.Id, pending.Timeout, pending.Timer);
try { await call.RequestStream.WriteAsync(encoded, linked.Token).ConfigureAwait(false); }
catch { await lifetime.CancelAsync().ConfigureAwait(false); throw; }
}
finally { _send.Release(); }
}
finally { ExitOperation(); }
}
private async Task ExpireUnacknowledgedAsync(string commandId, TimeSpan timeout, CancellationTokenSource timer)
{
try
{
await Task.Delay(timeout, timer.Token).ConfigureAwait(false);
Task? cancellation = null;
lock (_pending)
if (_pending.TryGetValue(commandId, out var current) && ReferenceEquals(current.Timer, timer))
cancellation = lifetime.CancelAsync();
if (cancellation is not null) await cancellation.ConfigureAwait(false);
}
catch (OperationCanceledException) { if (afterTimerCancelled is not null) await afterTimerCancelled().ConfigureAwait(false); }
catch (ObjectDisposedException) { }
}
public async IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
if (Interlocked.Exchange(ref _reading, 1) != 0) throw new InvalidOperationException("A stream has one reader.");
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, lifetime.Token);
try
{
while (true)
{
bool more;
EnterOperation();
try { more = await call.ResponseStream.MoveNext(linked.Token).ConfigureAwait(false); }
finally { ExitOperation(); }
if (!more) break;
var wire = call.ResponseStream.Current;
Verify(wire.Serving, selected);
if (_id is null || wire.SubscriptionId != _id || wire.StreamEpoch != _epoch || wire.Sequence != _sequence + 1)
throw new InvalidOperationException("Unexpected stream epoch or sequence.");
DataSubscriptionFrame frame;
if (wire.Values is not null || wire.CompactValues is not null)
frame = DataProtoMapper.DecodeValues(wire, _handles, maxItems,
Math.Min(maxBytes, selected.Capabilities.Limits.MaxMessageBytes), selected.Capabilities.Serving,
selected.Capabilities.Limits.MaxValueElements, selected.Capabilities.SubscriptionAgeReadiness);
else frame = DataProtoMapper.DecodeControlOrAck(wire, new DataDecodeLimits(maxItems,
Math.Min(maxBytes, selected.Capabilities.Limits.MaxMessageBytes), selected.Capabilities.Limits.MaxValueElements));
try
{
Verify(wire.Serving, selected); linked.Token.ThrowIfCancellationRequested();
if (frame is DataSubscriptionAck ack)
{
PendingCommand pending;
lock (_pending)
{
if (!_pending.TryGetValue(ack.CommandId, out pending!)) throw new InvalidOperationException("Unknown acknowledgement.");
}
var requested = pending.ClientIds ?? pending.Removed!.Select(_ => (string?)null).ToArray();
if (ack.Items.Count != requested.Length) throw new InvalidOperationException("Unexpected acknowledgement count.");
var next = new Dictionary<ulong, DataItemHandle>(_handles);
var nextClients = new Dictionary<string, ulong>(_clientHandles, StringComparer.Ordinal);
var nextUsed = new HashSet<ulong>(_usedHandles);
var nextVersions = new Dictionary<ulong, long>(_versions);
for (var i = 0; i < ack.Items.Count; i++)
{
var item = ack.Items[i];
if (requested[i] is { } clientId && item.ClientItemId != clientId)
throw new InvalidOperationException("Unexpected acknowledgement item.");
if (item.Status != DataItemStatus.Good) continue;
var handle = item.Handle ?? throw new InvalidOperationException("Successful acknowledgement has no handle.");
if (pending.Removed is { } removedItems)
{
if (removedItems[i] != handle || !next.Remove(handle.Handle) ||
!nextClients.Remove(item.ClientItemId, out var removed) || removed != handle.Handle)
throw new InvalidOperationException("Unexpected removed handle.");
nextVersions.Remove(handle.Handle);
}
else
{
DataItemHandle? prior = null;
if (pending.IsModify)
{
if (!nextClients.TryGetValue(item.ClientItemId, out var previous) || !next.Remove(previous, out prior))
throw new InvalidOperationException("Unknown modified item.");
if (previous != handle.Handle) nextVersions.Remove(previous);
}
else if (nextClients.ContainsKey(item.ClientItemId)) throw new InvalidOperationException("Duplicate item.");
var unchanged = prior == handle;
if ((!unchanged && nextUsed.Contains(handle.Handle)) || next.Count >= maxItems || next.ContainsKey(handle.Handle))
throw new InvalidOperationException("Handle capacity or identity conflict.");
if (!unchanged && nextUsed.Count >= Math.Min(100_000L, Math.Max(1024L, 4L * maxItems)))
throw new InvalidOperationException("Handle history capacity exhausted; reset the stream.");
nextUsed.Add(handle.Handle); next[handle.Handle] = handle;
nextClients[item.ClientItemId] = handle.Handle;
}
}
Verify(wire.Serving, selected); linked.Token.ThrowIfCancellationRequested();
lock (_pending)
{
linked.Token.ThrowIfCancellationRequested();
if (!_pending.Remove(ack.CommandId)) throw new InvalidOperationException("Acknowledgement expired.");
_pendingBytes -= pending.Bytes; commandBudget.Release(pending.Bytes);
pending.Timer.Cancel(); pending.Timer.Dispose();
_handles = next; _clientHandles = nextClients; _usedHandles = nextUsed; _versions = nextVersions;
}
}
if (frame is DataSubscriptionValues values)
{
var nextVersions = new Dictionary<ulong, long>(_versions);
var seen = new HashSet<ulong>();
foreach (var item in values.Items)
{
if (!seen.Add(item.Handle.Handle) || nextVersions.TryGetValue(item.Handle.Handle, out var previous) && item.Sample.Version < previous)
throw new InvalidOperationException("Duplicate handle or sample version regression.");
nextVersions[item.Handle.Handle] = item.Sample.Version;
}
Verify(wire.Serving, selected); linked.Token.ThrowIfCancellationRequested(); _versions = nextVersions;
}
_sequence = wire.Sequence;
}
catch { if (frame is IDisposable owned) owned.Dispose(); throw; }
yield return frame;
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Reset })
{ await lifetime.CancelAsync().ConfigureAwait(false); yield break; }
}
}
finally { await DisposeAsync().ConfigureAwait(false); }
}
public ValueTask DisposeAsync()
{
lock (_lifecycle)
{
if (_disposed == 0) { _disposed = 1; _ = ClosePhysicalAsync(); }
return new(_closed.Task);
}
}
private async Task ClosePhysicalAsync()
{
await Task.Yield();
try { await Task.Run(() => { lifetime.Cancel(); call.Dispose(); }).ConfigureAwait(false); }
catch (Exception) { }
// Unlike MoveNext's pre-header task, this receipt settles only after the raw HTTP send does.
try { await _headersReceipt.ConfigureAwait(false); } catch (Exception) { }
bool finish;
lock (_lifecycle) { _physicalClosed = true; finish = TryFinishLocked(); }
if (finish) Finish();
}
}
public ValueTask DisposeAsync()
{
lock (_sync)
{
if (_disposeTask is not null) return new(_disposeTask);
_disposed = true;
_security.Changed -= SecurityChanged;
_shutdownCancellation = _shutdown.CancelAsync();
RetireAll();
foreach (var stream in _streams.ToArray()) _ = stream.DisposeAsync();
CheckDrainedLocked();
_disposeTask = FinishDisposeAsync();
return new(_disposeTask);
}
}
private async Task FinishDisposeAsync()
{
await _drained.Task.ConfigureAwait(false);
try { if (_shutdownCancellation is not null) await _shutdownCancellation.ConfigureAwait(false); }
finally { _scope.Dispose(); _shutdown.Dispose(); }
}
}
@@ -51,14 +51,16 @@ public sealed class LocalCatalogCoordinator
if (catalog is null || !catalog.IsActive) return null;
var current = _serving();
if (current.NodeId != catalog.Serving.NodeId || current.Incarnation != catalog.Serving.Incarnation) return null;
if (current.Role == catalog.Serving.Role)
if (current.Role == catalog.Serving.Role && current.ServingGeneration == catalog.Serving.ServingGeneration)
{
var verified = _serving();
if (verified.NodeId != catalog.Serving.NodeId || verified.Incarnation != catalog.Serving.Incarnation) return null;
if (verified.Role != catalog.Serving.Role || !ReferenceEquals(Volatile.Read(ref _published), catalog)) continue;
if (verified.Role != catalog.Serving.Role || verified.ServingGeneration != catalog.Serving.ServingGeneration
|| !ReferenceEquals(Volatile.Read(ref _published), catalog)) continue;
return catalog.IsActive ? catalog : null;
}
var adjusted = catalog.WithServingRole(catalog.Serving with { Role = current.Role });
var adjusted = catalog.WithServingRole(catalog.Serving with
{ Role = current.Role, ServingGeneration = current.ServingGeneration });
// Acquisition callers must not wait behind a write-commit or authority publisher.
// Serving will return provisional zero epochs if the role wrapper cannot be refreshed.
if (!DispatchFence.TryEnter(out var lease)) return null;
@@ -3,7 +3,7 @@ using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Strictly caller-bound local data facade; it creates no namespace projection.</summary>
public sealed class LocalDataConnection : IDataConnection, IDataConnectionPublicationGate
public sealed class LocalDataConnection : IDataConnection, IDataConnectionPublicationGate, IDataConnectionDiscoveryGate
{
private readonly LocalDataServices _services;
private readonly DataAuthenticatedContext _context;
@@ -12,16 +12,18 @@ public sealed class LocalDataConnection : IDataConnection, IDataConnectionPublic
{ _services = services; _context = context; Target = target; }
public DataTarget Target { get; }
public TimeProvider Clock => _services.Clock;
public bool CanPublish(ServingIdentity expectedServing) => Volatile.Read(ref _disposed) == 0 && _services.CanPublish(_context, expectedServing);
public bool CanPublish(ServingIdentity expectedServing) => Volatile.Read(ref _disposed) == 0 && _services.CanPublish(_context, expectedServing, Target);
public bool CanPublishCapabilities(DataCapabilities expected) => Volatile.Read(ref _disposed) == 0
&& _services.CanPublishCapabilities(_context, Target, expected);
private void Check() => ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken)
{ Check(); return _services.GetCapabilitiesAsync(_context, Target, budget, cancellationToken); }
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken)
{ Check(); return _services.BrowseAsync(_context, Target, request, cancellationToken); }
{ Check(); _services.RequireTargetRole(Target); return _services.BrowseAsync(_context, Target, request, cancellationToken); }
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
{ Check(); return _services.GetMetadataAsync(_context, Target, request, cancellationToken); }
{ Check(); _services.RequireTargetRole(Target); return _services.GetMetadataAsync(_context, Target, request, cancellationToken); }
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken)
{ Check(); return _services.ReadAsync(_context, request, cancellationToken); }
{ Check(); _services.RequireTargetRole(Target); return _services.ReadAsync(_context, Target, request, cancellationToken); }
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken)
{ Check(); return _services.WriteAsync(_context, request, cancellationToken); }
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
@@ -0,0 +1,42 @@
using Akka.Actor;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Bounds shared physical demand and downstream subscription resources for one process.</summary>
public sealed record LocalDataRuntimeLimits(int MaxDrivers, int MaxInterests, int MaxOperations,
int MaxOperationsPerPrincipal, long MaxTransportBytes, int MaxCommands, int MaxPendingFrames,
long MaxPendingBytes, TimeSpan MaxSessionLifetime, TimeSpan DriverAskTimeout);
/// <summary>Owns the local caller-bound services and the one shared physical-demand bridge.</summary>
public sealed class LocalDataRuntimeComposition : IDisposable
{
private readonly DriverHostSubscriptionDemandSource _demand;
private int _disposed;
public LocalDataRuntimeComposition(LocalCatalogCoordinator catalog, PartitionedSampleHub hub,
DataOperationPolicy policy, DataCapabilitiesProvider capabilities, TimeProvider clock, DataWriteRuntime writes,
IActorRef host, SubscriptionAcquisitionCapacity acquisitionCapacity, LocalDataRuntimeLimits limits)
{
ArgumentNullException.ThrowIfNull(catalog); ArgumentNullException.ThrowIfNull(hub);
ArgumentNullException.ThrowIfNull(policy); ArgumentNullException.ThrowIfNull(capabilities);
ArgumentNullException.ThrowIfNull(clock); ArgumentNullException.ThrowIfNull(writes);
ArgumentNullException.ThrowIfNull(host); ArgumentNullException.ThrowIfNull(acquisitionCapacity);
ArgumentNullException.ThrowIfNull(limits);
if (!ReferenceEquals(hub.Clock, clock)) throw new ArgumentException("Local hub and services must share one clock.", nameof(clock));
var sessionLimits = new SubscriptionSessionLimits(limits.MaxCommands, limits.MaxPendingFrames, limits.MaxPendingBytes, limits.MaxSessionLifetime);
sessionLimits.Validate();
var registry = new UpstreamDemandRegistry(limits.MaxInterests, limits.MaxInterests);
var capacity = new SubscriptionTransportCapacity(limits.MaxOperations, limits.MaxOperationsPerPrincipal, limits.MaxTransportBytes, clock);
_demand = new DriverHostSubscriptionDemandSource(host, registry, limits.MaxDrivers, limits.MaxInterests, limits.DriverAskTimeout, acquisitionCapacity);
AcquisitionCapacity = acquisitionCapacity;
LocalDataServices? services = null;
services = new LocalDataServices(() => catalog.Current, hub, policy, capabilities, clock,
writes: context => writes.ForCaller(context, () => host),
targetSubscriptions: (context, target) => new LocalSubscriptionService(services!, context, target, _demand, sessionLimits, capacity));
Services = services;
}
public LocalDataServices Services { get; }
public SubscriptionAcquisitionCapacity AcquisitionCapacity { get; }
public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) _demand.Dispose(); }
}
@@ -48,17 +48,44 @@ public sealed class LocalDataServices : IDataConnectionFactory
private DataCallerIdentity Caller(DataAuthenticatedContext context) => _callers.GetValue(context, static value =>
new(value.PrincipalId, value.ApiKeyId, value.CredentialVersion, value.CredentialExpiresUtc));
internal bool CanPublish(DataAuthenticatedContext context, ServingIdentity expectedServing)
internal bool CanPublish(DataAuthenticatedContext context, ServingIdentity expectedServing, DataTarget? target = null)
{
var catalog = _catalog();
return catalog is not null && Ready(catalog) && catalog.Serving == expectedServing
&& context.AuthorityEpoch == catalog.AuthorityEpoch
&& (target is null || RoleAllows(target, catalog.Serving))
&& _policy.IsCallerUsable(Caller(context));
}
private static bool RoleAllows(DataTarget target, ServingIdentity serving) =>
string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)
|| target.Mode == DataTargetMode.Node && target.Consistency == DataConsistency.ReadyReplica
&& string.Equals(serving.Role, "Secondary", StringComparison.OrdinalIgnoreCase);
internal void RequireTargetRole(DataTarget target)
{
if (!RoleAllows(target, _capabilities.Serving))
throw new InvalidOperationException("The requested target cannot serve the required consistency.");
}
internal bool CanPublishCapabilities(DataAuthenticatedContext context, DataTarget target, DataCapabilities expected)
{
var catalog = _catalog();
if (!_policy.IsCallerUsable(Caller(context)) || context.AuthorityEpoch != _policy.AuthorityEpoch
|| _capabilities.Serving != expected.Serving) return false;
var ready = catalog is not null && Ready(catalog) && context.AuthorityEpoch == catalog.AuthorityEpoch
&& RoleAllows(target, catalog.Serving);
var operations = ready ? catalog!.ExportOperations(context.PrincipalId) & Implemented(target) : DataOperations.None;
if (!string.Equals(expected.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)) operations &= ~DataOperations.Write;
return expected.Readiness == (ready ? DataReadiness.Ready : DataReadiness.Unavailable)
&& expected.Operations == operations && _capabilities.Serving == expected.Serving
&& _policy.IsCallerUsable(Caller(context)) && context.AuthorityEpoch == _policy.AuthorityEpoch;
}
private sealed class PublicationReadLease(CachedSourceRead read, Func<bool> gate) : IDataPublicationLease
{
private int _disposed;
public bool IsValid => Volatile.Read(ref _disposed) == 0 && read.IsValid && gate();
public bool IsValid => gate() && Volatile.Read(ref _disposed) == 0 && read.IsValid;
public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) read.Dispose(); }
}
@@ -104,6 +131,7 @@ public sealed class LocalDataServices : IDataConnectionFactory
view.Validate(); target.Validate();
var catalog = _catalog();
if (catalog is null || !Ready(catalog)) return DataItemStatus.Unavailable;
if (!RoleAllows(target, catalog.Serving)) return DataItemStatus.Unavailable;
if (context.AuthorityEpoch != catalog.AuthorityEpoch) return DataItemStatus.Denied;
if (!string.Equals(target.ExpectedClusterId, catalog.ClusterId, StringComparison.OrdinalIgnoreCase) ||
target.Mode == DataTargetMode.Node && !string.Equals(target.ExpectedNodeId, catalog.Serving.NodeId, StringComparison.OrdinalIgnoreCase))
@@ -143,6 +171,7 @@ public sealed class LocalDataServices : IDataConnectionFactory
{
var catalog = _catalog();
return catalog is not null && Ready(catalog) && context.AuthorityEpoch == catalog.AuthorityEpoch &&
RoleAllows(target, catalog.Serving) &&
(expected is null || catalog.Serving == expected) && _policy.IsCallerUsable(Caller(context)) &&
string.Equals(target.ExpectedClusterId, catalog.ClusterId, StringComparison.OrdinalIgnoreCase) &&
(target.Mode != DataTargetMode.Node || string.Equals(target.ExpectedNodeId, catalog.Serving.NodeId, StringComparison.OrdinalIgnoreCase));
@@ -183,7 +212,8 @@ public sealed class LocalDataServices : IDataConnectionFactory
if (!_policy.IsCallerUsable(Caller(context))) throw new UnauthorizedAccessException();
var capabilities = _capabilities.Get(catalog is null ? DataOperations.None : catalog.ExportOperations(context.PrincipalId) & Implemented(target),
catalog is null ? _capabilities.Limits : Limits(catalog, context));
if (catalog is null || !Ready(catalog)) capabilities = capabilities with { Readiness = DataReadiness.Unavailable, Operations = DataOperations.None };
if (catalog is null || !Ready(catalog) || context.AuthorityEpoch != catalog.AuthorityEpoch || !RoleAllows(target, catalog.Serving))
capabilities = capabilities with { Readiness = DataReadiness.Unavailable, Operations = DataOperations.None };
return Task.FromResult(capabilities);
}
@@ -226,7 +256,7 @@ public sealed class LocalDataServices : IDataConnectionFactory
return Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(results);
}
internal Task<IReadOnlyList<ReadResult>> ReadAsync(DataAuthenticatedContext context, ReadRequest request, CancellationToken cancellationToken)
internal Task<IReadOnlyList<ReadResult>> ReadAsync(DataAuthenticatedContext context, DataTarget target, ReadRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request.Items);
var catalog = _catalog();
@@ -274,7 +304,7 @@ public sealed class LocalDataServices : IDataConnectionFactory
if (!Allowed(catalog, context, node, DataOperations.Read)
|| !_hub.TryGetCurrentTicket(key, out current) || current != ticket)
{ exposed.Dispose(); read.Dispose(); results.Add(Empty(DataItemStatus.Denied)); continue; }
var publication = new PublicationReadLease(read, () => CanPublish(context, exposed.Serving)
var publication = new PublicationReadLease(read, () => CanPublish(context, exposed.Serving, target)
&& !Expired(start, request.Budget));
results.Add(new(item.CorrelationId, item.MaximumAge is { } max && age > max ? DataItemStatus.Stale : DataItemStatus.Good,
DataReadiness.Ready, age, exposed, null, publication, new DataAgeBounds(age, age)));
@@ -334,11 +364,18 @@ public sealed class LocalDataServices : IDataConnectionFactory
bytes += size; page.Add(metadata);
}
if (!Allowed(catalog, context, parent, DataOperations.Browse)) return Task.FromResult(Empty(DataItemStatus.Denied));
var leaseDuration = limits.MaxMetadataLease;
if (context.CredentialExpiresUtc is { } expiry)
{
var remaining = expiry - Clock.GetUtcNow();
if (remaining <= TimeSpan.Zero) return Task.FromResult(Empty(DataItemStatus.Denied));
if (remaining < leaseDuration) leaseDuration = remaining;
}
var complete = offset == children.Count;
var token = complete ? null : EncodeContinuation(new(request.Parent, request.Filter, offset, context.PrincipalId,
context.ApiKeyId, context.CredentialVersion, catalog.Serving, start, limits.MaxMetadataLease.Ticks));
context.ApiKeyId, context.CredentialVersion, catalog.Serving, start, leaseDuration.Ticks));
return Task.FromResult(new DataBrowseBranch(request.Parent, DataItemStatus.Good, page, complete, token,
new MetadataLease(catalog.Serving.CatalogEpoch, catalog.Serving.AuthorityEpoch, limits.MaxMetadataLease)));
new MetadataLease(catalog.Serving.CatalogEpoch, catalog.Serving.AuthorityEpoch, leaseDuration)));
}
internal async Task<IReadOnlyList<WriteItemResult>> WriteAsync(DataAuthenticatedContext context, WriteBatch request, CancellationToken cancellationToken)
@@ -9,7 +9,7 @@ internal sealed record WriteRouteTarget(string DriverInstanceId, string DriverRe
long RouteGeneration, long PrimaryGeneration);
internal sealed record WriteRouteProof(DataWriteAdmission Admission, FrozenWriteScope Scope, string EntityKind,
string EntityId, BackingSourceKey? Source, string DriverInstanceId, string DriverReference,
long RouteGeneration, long PrimaryGeneration);
long RouteGeneration, long PrimaryGeneration, ServingIdentity? Serving = null);
/// <summary>Owns the value and its byte charge until rejection or actual driver completion.</summary>
internal sealed class WriteAdmissionTicket : IDisposable
@@ -6,6 +6,12 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
public static partial class DeploymentArtifact
{
/// <summary>Reads the durable central scope generation independently of whether this node still has imports.</summary>
public static long ParseDataConnectionScopeVersion(ReadOnlySpan<byte> blob)
{
using var parsed = Open(blob.ToArray());
return parsed.ParseDataConnectionScopeVersion();
}
/// <summary>Read the node-effective data connections from an artifact.</summary>
public static IReadOnlyList<DataConnection> ParseDataConnections(
ReadOnlySpan<byte> blob,
@@ -36,6 +42,13 @@ public static partial class DeploymentArtifact
internal sealed partial class ParsedDeploymentArtifact
{
internal long ParseDataConnectionScopeVersion()
{
if (!Root.TryGetProperty("DataConnectionScopeVersion", out var value)) return 0;
if (!value.TryGetInt64(out var version) || version <= 0)
throw new InvalidOperationException("Data connection scope generation is invalid.");
return version;
}
/// <summary>Materialize this node's eligible catalog inputs while the artifact document is alive.</summary>
internal DraftSnapshot? ParseLocalCatalogSnapshot(string nodeId) => ReadDataProjection(nodeId)?.Snapshot;
@@ -492,6 +492,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// snapshot proves this node is Primary (archreview 03/S4 — closes the dual-primary boot window).
/// </summary>
private RedundancyRole? _localRole;
private RedundancyRole? _observedDataServingRole;
private readonly long _dataServingOwner;
private readonly DataConnectionDeploymentRuntime? _dataConnections;
/// <summary>Test seam (archreview 03/S4): overrides the count of Up <c>driver</c>-role cluster members
/// the Primary gate reads while the role is unknown. Null ⇒ read the live cluster state (0 on a
@@ -839,7 +842,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null,
DataWriteRuntime? dataWriteRuntime = null,
SubscriptionAcquisitionCapacity? acquisitionCapacity = null) =>
SubscriptionAcquisitionCapacity? acquisitionCapacity = null,
DataConnectionDeploymentRuntime? dataConnections = null) =>
// WARNING: this forwarding list is POSITIONAL, and Props.Create compiles it into an
// expression tree. Six IActorRef? parameters and several interface-typed ones mean a
// mis-ordered argument is usually type-compatible and therefore compiles clean, then binds
@@ -854,7 +858,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
sharesHistorizationScopeWithLocal, applyWedgeTimeout, reprovisionBackoff, commsRecoveryAuditDelay,
sharesAlarmQueueWithLocal, applyOutcomeTimeout, captureWhilePrimaryUnreachable, historyUpdateRoleView,
scripting, ackPreflightView, writeBounds, writeClock, scriptedAlarmRunner, childShutdownTimeout,
enforceSnapshotOrdering, sourcePublisher, catalogCoordinator, dataWriteRuntime, acquisitionCapacity));
enforceSnapshotOrdering, sourcePublisher, catalogCoordinator, dataWriteRuntime, acquisitionCapacity, dataConnections));
/// <summary>Initializes a new DriverHostActor with the specified dependencies.</summary>
/// <param name="dbFactory">Database context factory for configuration database access.</param>
@@ -994,9 +998,11 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null,
DataWriteRuntime? dataWriteRuntime = null,
SubscriptionAcquisitionCapacity? acquisitionCapacity = null)
SubscriptionAcquisitionCapacity? acquisitionCapacity = null,
DataConnectionDeploymentRuntime? dataConnections = null)
{
_dataWriteRuntime = dataWriteRuntime;
_dataConnections = dataConnections;
_acquisitionCapacity = acquisitionCapacity;
_acquisitionHostGeneration = acquisitionCapacity?.NextControlGeneration() ?? 0;
_sourcePublisher = sourcePublisher;
@@ -1023,6 +1029,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
_deploymentArtifactCache = deploymentArtifactCache;
_redundancyRoleView = redundancyRoleView;
_primaryRoleSource = primaryRoleSource;
_dataServingOwner = (primaryRoleSource as ZB.MOM.WW.OtOpcUa.Runtime.Redundancy.RedundancyRoleView)?.RegisterDataServingOwner() ?? 0;
_replicationPeerHost = replicationPeerHost;
_fetchAndCacheMode = fetchAndCacheMode;
_artifactFetcher = artifactFetcher;
@@ -1151,7 +1158,15 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
{
var verdict = ShouldServiceAsPrimary();
_lastPublishedPrimaryVerdict = verdict;
_primaryRoleSource.PublishPrimaryRole(verdict);
if (_primaryRoleSource is ZB.MOM.WW.OtOpcUa.Runtime.Redundancy.RedundancyRoleView observed)
{
var generation = observed.PrimaryGeneration;
var role = observed.DataServingRole;
observed.PublishDataServingRole(_dataServingOwner, _observedDataServingRole, verdict);
if (generation != observed.PrimaryGeneration || role != observed.DataServingRole)
_dataConnections?.NotifyConsumerRoleChanged();
}
else _primaryRoleSource.PublishPrimaryRole(verdict);
}
PublishHistoryUpdateVerdict();
}
@@ -1228,6 +1243,14 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// <inheritdoc />
protected override void PostStop()
{
if (_primaryRoleSource is ZB.MOM.WW.OtOpcUa.Runtime.Redundancy.RedundancyRoleView observed)
{
var generation = observed.PrimaryGeneration;
var role = observed.DataServingRole;
observed.RetireDataServingOwner(_dataServingOwner);
if (generation != observed.PrimaryGeneration || role != observed.DataServingRole)
_dataConnections?.NotifyConsumerRoleChanged();
}
if (_subscribedToMemberEvents || _subscribedToReachabilityEvents)
{
try { Akka.Cluster.Cluster.Get(Context.System).Unsubscribe(Self); }
@@ -2705,6 +2728,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
_redundancySnapshotReceived = true;
var local = msg.Nodes.FirstOrDefault(n => n.NodeId == _localNode);
_observedDataServingRole = local?.Role;
if (local is not null)
{
_localRole = local.Role;
@@ -3574,9 +3598,10 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
private void BeginCatalogAttempt(byte[]? blob)
{
if (_catalogCoordinator is null) return;
var revision = blob is { Length: > 0 }
? Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(blob)) : "unavailable";
_dataConnections?.BeginAttempt(revision);
if (_catalogCoordinator is null) return;
_catalogAttempt = _catalogCoordinator.BeginAttempt(revision);
}
@@ -3602,6 +3627,16 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
return;
}
var snapshot = parsed.ParseLocalCatalogSnapshot(_localNode.Value);
if (_dataConnections is not null)
{
var owner = snapshot?.ClusterNodes.FirstOrDefault(node =>
string.Equals(node.NodeId, _localNode.Value, StringComparison.OrdinalIgnoreCase))?.ClusterId;
var mode = snapshot?.ServerClusters.FirstOrDefault(cluster =>
string.Equals(cluster.ClusterId, owner, StringComparison.OrdinalIgnoreCase))?.RedundancyMode
?? ZB.MOM.WW.OtOpcUa.Configuration.Enums.RedundancyMode.None;
_dataConnections.Apply(new(parsed.ParseDataConnectionScopeVersion(), _catalogAttempt.Revision,
parsed.ParseDataConnections(_localNode.Value), mode));
}
if (snapshot is not null) _catalogCoordinator.Stage(_catalogAttempt, snapshot, _localNode.Value);
}
catch (Exception ex)
@@ -338,7 +338,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
WarmRedundancySettings? redundancy = null,
IStandbyProjection? standbyProjection = null,
DataConnections.CatalogActivation? dataCatalog = null,
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null) =>
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null,
DataConnections.DataConnectionWarmRoleView? dataWarmRole = null,
DataConnections.DataConnectionDeploymentRuntime? dataConnections = null) =>
Akka.Actor.Props.Create(() => new OpcUaPublishActor(
sink ?? NullOpcUaAddressSpaceSink.Instance,
serviceLevel ?? NullServiceLevelPublisher.Instance,
@@ -355,7 +357,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
utcNow,
endpointState,
redundancy,
standbyProjection, dataCatalog, catalogCoordinator)).WithDispatcher(DispatcherId);
standbyProjection, dataCatalog, catalogCoordinator, dataWarmRole, dataConnections)).WithDispatcher(DispatcherId);
/// <summary>Test-only Props that omits the pinned-dispatcher requirement and skips the
/// DPS subscribe so unit tests can spin up the actor on a vanilla TestKit cluster.</summary>
@@ -403,7 +405,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
WarmRedundancySettings? redundancy = null,
IStandbyProjection? standbyProjection = null,
DataConnections.CatalogActivation? dataCatalog = null,
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null) =>
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null,
DataConnections.DataConnectionWarmRoleView? dataWarmRole = null,
DataConnections.DataConnectionDeploymentRuntime? dataConnections = null) =>
Akka.Actor.Props.Create(() => new OpcUaPublishActor(
sink ?? NullOpcUaAddressSpaceSink.Instance,
serviceLevel ?? NullServiceLevelPublisher.Instance,
@@ -420,7 +424,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
utcNow,
endpointState,
redundancy,
standbyProjection, dataCatalog, catalogCoordinator));
standbyProjection, dataCatalog, catalogCoordinator, dataWarmRole, dataConnections));
/// <summary>Test-only Props exposing the deferred-write bound and the plan-step seams.</summary>
internal static Props PropsForTests(
@@ -430,13 +434,15 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
int deferredWriteCapacity = DefaultDeferredWriteCapacity,
NodeId? localNode = null,
IDataPlaneAuthoritySink? dataPlaneAuthority = null,
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null) =>
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null,
DataConnections.DataConnectionWarmRoleView? dataWarmRole = null,
DataConnections.DataConnectionDeploymentRuntime? dataConnections = null) =>
// CreateBy, not Create(expression): Akka's expression path activates through a PUBLIC constructor, and the
// seam-carrying constructor is internal so the test seams stay off the public API (review M3).
Akka.Actor.Props.CreateBy(new TestProducer(() => new OpcUaPublishActor(
sink, NullServiceLevelPublisher.Instance, false, localNode, null, applier, null, null, null, null,
false, dataPlaneAuthority, null, deferredWriteCapacity, hooks, endpointState: null,
catalogCoordinator: catalogCoordinator)));
catalogCoordinator: catalogCoordinator, dataWarmRole: dataWarmRole, dataConnections: dataConnections)));
/// <summary>Produces the actor through its internal (seam-carrying) constructor, for <see cref="PropsForTests(IOpcUaAddressSpaceSink, AddressSpaceApplier?, TestHooks?, int, NodeId?, IDataPlaneAuthoritySink?)"/>.</summary>
private sealed class TestProducer(Func<OpcUaPublishActor> create) : IIndirectActorProducer
@@ -487,10 +493,12 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
WarmRedundancySettings? redundancy = null,
IStandbyProjection? standbyProjection = null,
DataConnections.CatalogActivation? dataCatalog = null,
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null)
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null,
DataConnections.DataConnectionWarmRoleView? dataWarmRole = null,
DataConnections.DataConnectionDeploymentRuntime? dataConnections = null)
: this(sink, serviceLevel, subscribeRedundancyTopic, localNode, dbFactory, applier, dbHealthProbe, staleWindow,
probeFreshnessWindow, healthTickInterval, dbLess, dataPlaneAuthority, utcNow, DefaultDeferredWriteCapacity, hooks: null,
endpointState, redundancy, standbyProjection, dataCatalog, catalogCoordinator)
endpointState, redundancy, standbyProjection, dataCatalog, catalogCoordinator, dataWarmRole, dataConnections)
{
}
@@ -518,9 +526,12 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
WarmRedundancySettings? redundancy = null,
IStandbyProjection? standbyProjection = null,
DataConnections.CatalogActivation? dataCatalog = null,
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null)
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null,
DataConnections.DataConnectionWarmRoleView? dataWarmRole = null,
DataConnections.DataConnectionDeploymentRuntime? dataConnections = null)
{
_redundancy = redundancy ?? WarmRedundancySettings.Unset;
_dataWarmRole = dataWarmRole; _dataConnections = dataConnections;
_standbyProjection = standbyProjection;
_deferred = new DeferredWrites(Math.Max(1, deferredWriteCapacity));
_hooks = hooks;
@@ -598,6 +609,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// <inheritdoc />
protected override void PostStop()
{
if (_dataWarmRole is not null && _dataWarmRole.RetireOwner(_dataWarmOwner))
_dataConnections?.NotifyConsumerRoleChanged();
_dataWarmOwner = 0;
if (_redundancy.IsWarm)
{
try { _cluster.Unsubscribe(Self); }
@@ -617,6 +631,11 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
if (_redundancy.IsWarm)
{
if (_dataWarmRole is not null)
{
_dataWarmOwner = _dataWarmRole.RegisterOwner();
_dataConnections?.NotifyConsumerRoleChanged();
}
OtOpcUaTelemetry.SetWarmRole(0);
try
{
@@ -1834,6 +1853,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
private sealed class WarmRetry { public static readonly WarmRetry Instance = new(); private WarmRetry() { } }
private readonly WarmRedundancySettings _redundancy;
private readonly DataConnections.DataConnectionWarmRoleView? _dataWarmRole;
private readonly DataConnections.DataConnectionDeploymentRuntime? _dataConnections;
private long _dataWarmOwner;
private readonly IStandbyProjection? _standbyProjection;
private readonly SnapshotRevisionGate _revisionGate = new();
/// <summary>The latest ACCEPTED revisioned snapshot — the only one the Warm verdict reads (spec §4.2).</summary>
@@ -2008,10 +2030,13 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// </summary>
private void ApplyWarmTransition(WarmRole target, byte level, string reason)
{
// A real Standby verdict must close imports before any projection or publisher callback.
if (_acceptedSnapshot is not null && target == WarmRole.Standby) PublishDataWarmRole(target);
if (target == _warmRole)
{
if (!TryPublishServiceLevel(level) && target == WarmRole.Active) ScheduleWarmRetry();
else if (target == WarmRole.Active) _promotionLevelPending = false;
if (_acceptedSnapshot is not null && target == WarmRole.Active) PublishDataWarmRole(target);
return;
}
@@ -2024,6 +2049,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
projection?.SetAlarmSuppression(false); // 4. new alarm events delivered
projection?.RefreshAllEventItems(); // 5. promotion refresh on every live event item
_warmRole = WarmRole.Active;
if (_acceptedSnapshot is not null) PublishDataWarmRole(WarmRole.Active);
if (TryPublishServiceLevel(level)) // 6. Active ServiceLevel, last
{
_promotionLevelPending = false;
@@ -2054,6 +2080,13 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
target == WarmRole.Active ? "promotion" : "demotion", _warmRole, reason, _revisionGate.LastAccepted, level);
}
private void PublishDataWarmRole(WarmRole role)
{
// Publish holds the dispatch fence only for the immutable state swap; notify after it exits.
if (_dataWarmRole is not null && _dataWarmRole.Publish(_dataWarmOwner, role))
_dataConnections?.NotifyConsumerRoleChanged();
}
/// <summary>
/// Gitea #717 spec §3 deploy-time cross-check: under <c>None</c> or <c>Warm</c>, an artifact whose cluster
/// <c>RedundancyMode</c> disagrees with the local mode (<c>Hot</c> included, owner answer Q5) logs an Error and
@@ -1,6 +1,7 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
@@ -116,9 +117,13 @@ public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRole
{
public RedundancyRoleView(DataWriteDispatchFence? dispatchFence = null) => DispatchFence = dispatchFence ?? new();
public DataWriteDispatchFence DispatchFence { get; }
private sealed record PrimaryVerdict(bool Allowed, long Generation);
private PrimaryVerdict _primaryVerdict = new(PrimaryGatePolicy.ShouldServiceAsPrimary(null, 1), 0);
private sealed record PrimaryVerdict(bool Allowed, long Generation, string ServingRole);
private PrimaryVerdict _primaryVerdict = new(PrimaryGatePolicy.ShouldServiceAsPrimary(null, 1), 0, "Unknown");
private long _nextDataOwner, _dataOwner;
private bool _rolePoisoned;
public long PrimaryGeneration => Volatile.Read(ref _primaryVerdict).Generation;
/// <summary>The actual observed role, independent of the existing primary policy's boot fallback.</summary>
public string DataServingRole => Volatile.Read(ref _primaryVerdict).ServingRole;
// seeded CLOSED, unlike the data-plane verdict. HistoryUpdate waits for a real redundancy verdict
// (PrimaryGatePolicy.ShouldServeHistoryUpdate); a node that never publishes here is not a driver node with a
// redundancy manager, and such a node does not register this view as its gate source.
@@ -162,12 +167,61 @@ public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRole
/// <inheritdoc/>
public void PublishPrimaryRole(bool shouldActAsPrimary)
=> PublishPrimaryVerdict(shouldActAsPrimary, null);
/// <summary>Publishes actual serving provenance with the existing primary verdict under their shared fence.</summary>
public void PublishDataServingRole(RedundancyRole? role, bool shouldActAsPrimary)
{
if (role is { } observed && !Enum.IsDefined(observed)) throw new ArgumentOutOfRangeException(nameof(role));
PublishPrimaryVerdict(shouldActAsPrimary, role?.ToString() ?? "Unknown");
}
internal long RegisterDataServingOwner()
{
using (DispatchFence.Enter())
{
var current = _primaryVerdict;
if (current.Generation == 0 || current.Allowed != shouldActAsPrimary)
Volatile.Write(ref _primaryVerdict, new(shouldActAsPrimary, checked(current.Generation + 1)));
if (_rolePoisoned || _nextDataOwner == long.MaxValue || current.Generation == long.MaxValue)
{ PoisonRole(); throw new InvalidOperationException("Serving role generation exhausted."); }
_dataOwner = ++_nextDataOwner;
Volatile.Write(ref _primaryVerdict, new(current.Allowed, current.Generation + 1, "Unknown"));
return _dataOwner;
}
}
internal void PublishDataServingRole(long owner, RedundancyRole? role, bool shouldActAsPrimary) =>
PublishPrimaryVerdict(shouldActAsPrimary, role?.ToString() ?? "Unknown", owner);
internal void RetireDataServingOwner(long owner)
{
using (DispatchFence.Enter())
{
if (owner == 0 || _dataOwner != owner) return;
var current = _primaryVerdict;
_dataOwner = 0;
if (current.Generation == long.MaxValue) { PoisonRole(); return; }
Volatile.Write(ref _primaryVerdict, new(false, current.Generation + 1, "Unknown"));
}
}
private void PoisonRole()
{
_rolePoisoned = true; _dataOwner = 0;
Volatile.Write(ref _primaryVerdict, new(false, long.MaxValue, "Unknown"));
}
private void PublishPrimaryVerdict(bool shouldActAsPrimary, string? observedRole, long? owner = null)
{
using (DispatchFence.Enter())
{
var current = _primaryVerdict;
if (_rolePoisoned || owner is { } expected && (expected == 0 || expected != _dataOwner)) return;
var role = observedRole ?? current.ServingRole;
if (current.Generation == 0 || current.Allowed != shouldActAsPrimary || current.ServingRole != role)
{
if (current.Generation == long.MaxValue) { PoisonRole(); return; }
Volatile.Write(ref _primaryVerdict, new(shouldActAsPrimary, current.Generation + 1, role));
}
}
}
@@ -32,6 +32,8 @@ using ZB.MOM.WW.OtOpcUa.Runtime.Telemetry;
using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
using ZB.MOM.WW.LocalDb;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime;
public static class ServiceCollectionExtensions
@@ -559,31 +561,15 @@ public static class ServiceCollectionExtensions
loggerFactory.CreateLogger<AddressSpaceApplier>(),
provisioning: provisioning,
historizedSubscriptions: historizedSubscriptions);
// the sink that receives each applied artifact's API keys + ACL grants, so OPC
// UA session activation can authenticate. Optional: GetService (not GetRequiredService), because
// a node with no driver role never registers it and test harnesses build this graph without it;
// the actor treats null as "nothing consumes authorization inputs" and skips the decode.
var dataPlaneAuthority = resolver.GetService<IDataPlaneAuthoritySink>();
// lmxopcua#762: the "did the OPC UA SDK start?" fact the Host's OtOpcUaServerHostedService maintains.
// Optional: a harness that builds this graph without the hosted service registers none, and both
// consumers then behave as if the endpoint were listening (the pre-#762 behaviour).
var endpointState = resolver.GetService<IOpcUaEndpointState>();
// Gitea #717: OpcUa:Redundancy (registered by the Host from the validated OpcUa options). Absent in harnesses ⇒
// Unset ⇒ today's behaviour. The standby projection is late-bound like the ServiceLevel publisher.
var redundancy = resolver.GetService<WarmRedundancySettings>() ?? WarmRedundancySettings.Unset;
// The same production factory selects authority, catalog and Warm publications in tests.
var publishActor = system.ActorOf(
OpcUaPublishActor.Props(
sink: addressSpaceSink,
serviceLevel: serviceLevel,
localNode: roleInfo.LocalNode,
dbFactory: dbFactory,
applier: applier,
dbHealthProbe: dbHealth,
dbLess: dbFactory is null,
dataPlaneAuthority: dataPlaneAuthority,
endpointState: endpointState,
redundancy: redundancy,
standbyProjection: redundancy.IsWarm ? resolver.GetService<DeferredStandbyProjection>() : null),
DataConnectionPublisherProps.Create(resolver, addressSpaceSink, serviceLevel,
roleInfo.LocalNode, dbFactory, applier, dbHealth),
OpcUaPublishActorName);
registry.Register<OpcUaPublishActorKey>(publishActor);
@@ -679,7 +665,13 @@ public static class ServiceCollectionExtensions
scriptedAlarmRunner: resolver.GetService<ZB.MOM.WW.OtOpcUa.Core.Scripting.IScriptRunnerProvider>()
?.ForSeam(ZB.MOM.WW.OtOpcUa.Core.Scripting.ScriptSeam.ScriptedAlarm),
// Gitea #717 spec §4.2: drop older redundancy snapshots under Warm only.
enforceSnapshotOrdering: redundancy.IsWarm),
enforceSnapshotOrdering: redundancy.IsWarm,
sourcePublisher: resolver.GetService<ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher>(),
catalogCoordinator: resolver.GetService<ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator>(),
dataWriteRuntime: resolver.GetService<ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.DataWriteRuntime>(),
acquisitionCapacity: resolver.GetService<SubscriptionAcquisitionCapacity>(),
writeClock: resolver.GetService<TimeProvider>(),
dataConnections: resolver.GetService<ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.DataConnectionDeploymentRuntime>()),
DriverHostActorName);
registry.Register<DriverHostActorKey>(driverHost);