test: validate grpc data connections with local docker and opcua cli
This commit is contained in:
+86
-11
@@ -8,6 +8,9 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
public sealed record DataConnectionDeploymentSnapshot(long ScopeVersion, string ArtifactRevision, IReadOnlyList<DataConnection> Connections,
|
||||
RedundancyMode ConsumerMode = RedundancyMode.None);
|
||||
|
||||
/// <summary>Host-effective role eligibility and the continuity epoch observed under its role fence.</summary>
|
||||
public sealed record DataConnectionConsumerRoleSnapshot(RedundancyMode Mode, bool Eligible, long Epoch);
|
||||
|
||||
/// <summary>Persists the node's current connection-to-secret allowlist before any route is made ready.</summary>
|
||||
public interface IDataConnectionScopeActivator
|
||||
{
|
||||
@@ -22,12 +25,17 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
|
||||
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)
|
||||
private sealed class Entry(Spec spec, long generation, GrpcDataConnection connection, CancellationToken token,
|
||||
RedundancyMode artifactMode, DataConnectionConsumerRoleSnapshot? role)
|
||||
{
|
||||
internal readonly Spec Spec = spec;
|
||||
internal readonly long Generation = generation;
|
||||
internal readonly GrpcDataConnection Connection = connection;
|
||||
internal readonly CancellationToken Token = token;
|
||||
internal readonly object RouteIdentity = new();
|
||||
internal readonly RedundancyMode ArtifactMode = artifactMode;
|
||||
internal readonly DataConnectionConsumerRoleSnapshot? Role = role;
|
||||
internal volatile bool Live = true;
|
||||
internal bool Ready;
|
||||
internal int Leases;
|
||||
}
|
||||
@@ -39,6 +47,8 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
|
||||
private readonly int _maximum;
|
||||
private readonly TimeProvider _clock;
|
||||
private readonly Func<bool> _consumerMayAcquire;
|
||||
private readonly Func<RedundancyMode, DataConnectionConsumerRoleSnapshot?>? _consumerRoleSnapshot;
|
||||
private readonly bool _useCompactBatches;
|
||||
private readonly CancellationTokenSource _stop = new();
|
||||
private readonly ITimer _retryTimer;
|
||||
private readonly Dictionary<string, Entry> _entries = new(StringComparer.OrdinalIgnoreCase);
|
||||
@@ -53,13 +63,15 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
|
||||
|
||||
public DataConnectionDeploymentRuntime(string nodeId, string ownerCluster, IDataConnectionSecurityProvider security,
|
||||
IDataConnectionScopeActivator scopeActivator, int maxConnections, TimeProvider? clock = null,
|
||||
Func<bool>? consumerMayAcquire = null)
|
||||
Func<bool>? consumerMayAcquire = null, bool useCompactBatches = true,
|
||||
Func<RedundancyMode, DataConnectionConsumerRoleSnapshot?>? consumerRoleSnapshot = 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);
|
||||
_clock = clock ?? TimeProvider.System; _consumerMayAcquire = consumerMayAcquire ?? (() => true); _useCompactBatches = useCompactBatches;
|
||||
_consumerRoleSnapshot = consumerRoleSnapshot;
|
||||
_retryTimer = _clock.CreateTimer(static state => ((DataConnectionDeploymentRuntime)state!).OnRetry(), this,
|
||||
Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
|
||||
_manager = new DataConnectionManager(nodeId, maxConnections);
|
||||
@@ -190,6 +202,16 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
|
||||
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 DataConnectionConsumerRoleSnapshot? CaptureRole(RedundancyMode mode)
|
||||
{ try { return _consumerRoleSnapshot?.Invoke(mode); } catch (Exception) { return null; } }
|
||||
private bool RouteCurrent(Entry entry)
|
||||
{
|
||||
if (!entry.Live || entry.Token.IsCancellationRequested) return false;
|
||||
if (entry.Role is not { Eligible: true, Epoch: > 0 and < long.MaxValue } captured)
|
||||
return true;
|
||||
var current = CaptureRole(entry.ArtifactMode);
|
||||
return current is { Eligible: true, Epoch: > 0 and < long.MaxValue } && current.Mode == captured.Mode && current.Epoch == captured.Epoch;
|
||||
}
|
||||
private void ApplyManagerScopeLocked(Desired desired)
|
||||
{
|
||||
// The manager owns configured-node scope and physical lifetime only. Role checks
|
||||
@@ -207,6 +229,15 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
|
||||
{
|
||||
if (_disposed || _desired is null) return;
|
||||
if (_attemptPending) return;
|
||||
if (_consumerRoleSnapshot is not null && _entries.Count > 0)
|
||||
{
|
||||
var snapshots = _entries.Values.Select(entry => (Entry: entry, Current: CaptureRole(entry.ArtifactMode))).ToArray();
|
||||
if (snapshots.All(x => x.Entry.Role is { Mode: RedundancyMode.Hot, Eligible: true, Epoch: > 0 and < long.MaxValue }) &&
|
||||
snapshots.Any(x => x.Current is not { Epoch: > 0 })) return;
|
||||
if (snapshots.All(x => x.Entry.Role is { Mode: RedundancyMode.Hot, Eligible: true, Epoch: > 0 and < long.MaxValue } captured &&
|
||||
x.Current is { Mode: RedundancyMode.Hot, Eligible: true, Epoch: > 0 and < long.MaxValue } current && captured.Epoch == current.Epoch))
|
||||
{ WakeLocked(); return; }
|
||||
}
|
||||
DisarmRetryLocked();
|
||||
var generation = checked(++_generation);
|
||||
_desired = _desired with { Generation = generation };
|
||||
@@ -312,6 +343,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
|
||||
{
|
||||
Entry? existing;
|
||||
long securityGeneration;
|
||||
DataConnectionConsumerRoleSnapshot? beforeRole;
|
||||
lock (_sync)
|
||||
{
|
||||
if (_disposed || _attemptPending || _desired?.Generation != desired.Generation) break;
|
||||
@@ -319,6 +351,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
|
||||
_entries.TryGetValue(spec.Id, out existing);
|
||||
if (existing?.Ready == true) continue;
|
||||
securityGeneration = _securityGeneration;
|
||||
beforeRole = CaptureRole(desired.ConsumerMode);
|
||||
}
|
||||
var available = false;
|
||||
try
|
||||
@@ -339,6 +372,12 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
|
||||
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; }
|
||||
var role = CaptureRole(desired.ConsumerMode);
|
||||
if (_consumerRoleSnapshot is not null && (role is null || !role.Eligible || role.Epoch <= 0 || role.Epoch == long.MaxValue))
|
||||
{ retryNeeded = true; continue; }
|
||||
if (_consumerRoleSnapshot is not null && (beforeRole is null || !beforeRole.Eligible || beforeRole.Epoch <= 0 ||
|
||||
beforeRole.Epoch == long.MaxValue || beforeRole.Mode != role!.Mode || beforeRole.Epoch != role.Epoch))
|
||||
{ retryNeeded = true; continue; }
|
||||
DataConnectionScopeLease scope;
|
||||
try { scope = _manager.Acquire(spec.Id); }
|
||||
catch (UnauthorizedAccessException) { continue; }
|
||||
@@ -346,8 +385,8 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
|
||||
{
|
||||
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 });
|
||||
spec.Streams, spec.Monitored, maxPendingCommandBytes: spec.PendingBytes, enableCompactBatches: _useCompactBatches);
|
||||
_entries.Add(spec.Id, new Entry(spec, desired.Generation, connection, scope.CancellationToken, desired.ConsumerMode, role) { Ready = true });
|
||||
}
|
||||
catch (Exception) { scope.Dispose(); retryNeeded = true; }
|
||||
}
|
||||
@@ -364,6 +403,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
|
||||
}
|
||||
private void Retire(Entry entry)
|
||||
{
|
||||
entry.Live = false;
|
||||
var task = entry.Connection.DisposeAsync().AsTask();
|
||||
lock (_sync) _retirements.Add(task);
|
||||
_ = ObserveRetirementAsync(task);
|
||||
@@ -379,14 +419,27 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
|
||||
lock (_sync)
|
||||
{
|
||||
lease = null;
|
||||
if (_disposed || !_scopeReady || !MayAcquire() || !_entries.TryGetValue(id, out var entry) || !entry.Ready ||
|
||||
if (!_disposed && _desired is { } desired && _entries.TryGetValue(id, out var stale) &&
|
||||
stale.Role is { Eligible: true, Epoch: > 0 and < long.MaxValue } captured &&
|
||||
CaptureRole(stale.ArtifactMode) is { Epoch: > 0 and < long.MaxValue } observed &&
|
||||
(observed.Mode != captured.Mode || !observed.Eligible || observed.Epoch != captured.Epoch))
|
||||
{
|
||||
_entries.Remove(id);
|
||||
var generation = checked(++_generation);
|
||||
_desired = desired with { Generation = generation };
|
||||
_routeRevisions[id] = generation;
|
||||
ApplyManagerScopeLocked(_desired);
|
||||
Retire(stale);
|
||||
if (!_attemptPending) WakeLocked();
|
||||
}
|
||||
if (_disposed || !_scopeReady || !MayAcquire() || !_entries.TryGetValue(id, out var entry) || !entry.Ready || !RouteCurrent(entry) ||
|
||||
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 &&
|
||||
() => { lock (_sync) return !_disposed && _scopeReady && MayAcquire() && entry.Ready && RouteCurrent(entry) &&
|
||||
_entries.TryGetValue(id, out var current) && ReferenceEquals(entry, current); },
|
||||
() => { lock (_sync) entry.Leases--; });
|
||||
() => { lock (_sync) entry.Leases--; }, () => RouteCurrent(entry), entry.RouteIdentity);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -423,13 +476,18 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDisposable
|
||||
private readonly long _pendingBytes;
|
||||
private readonly Func<bool> _current;
|
||||
private readonly Action _release;
|
||||
private readonly Func<bool> _routeCurrent;
|
||||
internal object? RouteIdentity { get; }
|
||||
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)
|
||||
int batch, int page, int bytes, int streams, int monitored, long pendingBytes, Func<bool> current, Action release, Func<bool>? routeCurrent = null, object? routeIdentity = null)
|
||||
{
|
||||
_inner = inner; _scope = scope; _allowed = allowed; _timeout = timeout; _batch = batch; _page = page; _bytes = bytes;
|
||||
_streams = streams; _monitored = monitored; _pendingBytes = pendingBytes; _current = current; _release = release;
|
||||
_routeCurrent = routeCurrent ?? (() => !scope.IsCancellationRequested);
|
||||
RouteIdentity = routeIdentity;
|
||||
}
|
||||
internal Func<bool> RouteCurrent => _routeCurrent;
|
||||
public IDataConnection Connection => this;
|
||||
public CancellationToken CancellationToken => _scope;
|
||||
public DataTarget Target => _inner.Target;
|
||||
@@ -495,14 +553,31 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDisposable
|
||||
{
|
||||
public ServingIdentity Serving { get; } = serving;
|
||||
}
|
||||
private class ScopedSubscription(DataConnectionDeploymentLease owner, IDataSubscription inner) : IDataSubscription
|
||||
private class ScopedSubscription(DataConnectionDeploymentLease owner, IDataSubscription inner) : IDataSubscription, IDataSubscriptionFreshnessSupport
|
||||
{
|
||||
public bool SupportsFreshnessChallenges => inner is IDataSubscriptionFreshnessSupport { SupportsFreshnessChallenges: true };
|
||||
public int FreshnessMaxItems => inner is IDataSubscriptionFreshnessSupport support && support.SupportsFreshnessChallenges
|
||||
? Math.Min(support.FreshnessMaxItems, Math.Min(owner._batch, owner._monitored)) : 0;
|
||||
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 };
|
||||
ModifySubscriptionItems m => m.Items.Count, RemoveSubscriptionItems r => r.Items.Count,
|
||||
ChallengeSubscriptionFreshness c => c.Items.Count, _ => owner._monitored + 1 };
|
||||
if (count > owner._monitored) throw new ArgumentOutOfRangeException(nameof(command));
|
||||
if (command is ChallengeSubscriptionFreshness challenge)
|
||||
{
|
||||
if (!SupportsFreshnessChallenges) throw new InvalidOperationException("Peer did not negotiate freshness challenges.");
|
||||
if (count <= 0 || count > FreshnessMaxItems) throw new ArgumentOutOfRangeException(nameof(command));
|
||||
// Conservative preflight before any wire encoding, including UTF-8 expansion and per-handle overhead.
|
||||
var bytes = 128L + 4L * (challenge.SubscriptionId?.Length ?? 0) + 4L * (challenge.CommandId?.Length ?? 0);
|
||||
foreach (var handle in challenge.Items)
|
||||
{
|
||||
if (handle is null) throw new ArgumentException("Invalid challenge handle.", nameof(command));
|
||||
bytes = checked(bytes + 128L + 4L * (handle.SubscriptionId?.Length ?? 0));
|
||||
}
|
||||
if (bytes > Math.Min(owner._bytes, owner._pendingBytes)) 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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user