b9bd7960de
ProjectedDataAccess gets a test-only IProjectedPublishProbe (null in production) over six synchronous sections: the stream pump, the frame queue, the cohort loop's dispatch, a value's build, its publication and the frame's release. The perf harness prints them and the remainder against the process-wide figure. Release, 10k cohort, 5 runs: the ~600-650 B/value that #1094 left unattributed is Pump 84-209 (the LINQ Sum's boxed enumerator plus SemaphoreSlim.WaitAsync under a full frame window), Queue 40 (FrameEvent), Build 184 (DataValueSnapshot + ProjectedValueUpdate), Publish 208 (the latest-sample cache re-wrapping the update in two identical records, plus the one-element list), Release 55-88 (enumerators boxed by the frame disposes); 15-51 B/value stays unattributed (other threads).
281 lines
16 KiB
C#
281 lines
16 KiB
C#
using System.Collections.Concurrent;
|
|
using Opc.Ua;
|
|
using Shouldly;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
|
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
|
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
|
|
|
/// <summary>
|
|
/// #994 (R-2/R-7/R-13): a consumer <see cref="ProjectedDataAccess"/> holding <c>N</c> projected demands, every one
|
|
/// subscribed through ONE cohort onto a REAL origin <see cref="DataSubscriptionSession"/> (real
|
|
/// <see cref="SubscriptionTransportCapacity"/>, default 128 commands/s per principal) — the end-to-end path the
|
|
/// per-item command loop broke. Values are counted per local identifier as they reach the publisher.
|
|
/// </summary>
|
|
internal sealed class CohortScaleFixture : IFederatedProjectionCatalog, IProjectedNodeLookup, IGrpcDataAdapterConnectionSource,
|
|
IProjectedValuePublisher, IDisposable
|
|
{
|
|
internal readonly LocalDataFixture Origin;
|
|
internal readonly SubscriptionTransportCapacity Capacity;
|
|
internal readonly DeferredSubscriptionDemand OriginDemand = new();
|
|
private readonly DataOperationPolicy _policy;
|
|
internal readonly RoleCarryingUserIdentity Caller;
|
|
internal readonly NodeId[] NodeIds;
|
|
private readonly Dictionary<NodeId, ProjectedVariableDefinition> _definitions = new();
|
|
private readonly Dictionary<string, ProjectedNodeProof> _proofs = new(StringComparer.Ordinal);
|
|
internal readonly ConcurrentDictionary<string, int> Baselines = new(StringComparer.Ordinal);
|
|
internal readonly ConcurrentDictionary<string, long> Latest = new(StringComparer.Ordinal);
|
|
internal int Retired, Publishes, Opens;
|
|
/// <summary>#1094: per-thread allocation attribution for the publish path. Off unless a harness sets it before the stream opens.</summary>
|
|
internal bool MeasureAllocations;
|
|
internal readonly PublishAllocations Allocations = new();
|
|
/// <summary>#1094: when non-zero, the sink counts items whose latest delivered version reaches it (a poll reads a counter, not a copy).</summary>
|
|
internal long TargetVersion;
|
|
internal int AtTargetVersion;
|
|
/// <summary>When set, TryPublish answers false (a capacity-refusing sink).</summary>
|
|
#pragma warning disable CS0649 // set by individual tests
|
|
internal volatile bool RefusePublish;
|
|
internal Func<ProjectedValueUpdate, bool>? PublishGate;
|
|
#pragma warning restore CS0649
|
|
internal readonly ConcurrentQueue<DataSubscriptionCommand> Commands = new();
|
|
private readonly ConcurrentQueue<IDataSubscription> _streams = new();
|
|
private DataSubscriptionSession? _session;
|
|
internal DataSubscriptionSession? Session => Volatile.Read(ref _session);
|
|
|
|
internal readonly int MaxBatchItems;
|
|
internal CohortScaleFixture(int items, int maxCommandsPerSecond = 128, int maxBatchItems = 100)
|
|
{
|
|
MaxBatchItems = maxBatchItems;
|
|
Capacity = new SubscriptionTransportCapacity(64, 16, 256L * 1024 * 1024, maxCommandsPerSecond: maxCommandsPerSecond);
|
|
var limits = new SubscriptionSessionLimits(128, 64, 1024 * 1024, TimeSpan.FromMinutes(5));
|
|
LocalDataFixture? peer = null;
|
|
Origin = new LocalDataFixture(additionalRawNodes: items, servingGeneration: 1, maxMonitoredItems: items + 16,
|
|
maxBatchItems: maxBatchItems, maxMessageBytes: 64 * 1024 * 1024, subscriptionFreshnessChallenges: true, hubBytes: 256L * 1024 * 1024,
|
|
targetSubscriptions: (context, target) => new CapturingService(this,
|
|
new LocalSubscriptionService(peer!.Services, context, target, OriginDemand, limits, Capacity)));
|
|
peer = Origin;
|
|
OriginDemand.Accept();
|
|
Origin.Publish(42);
|
|
_policy = new(Origin.Authority, new TriePermissionEvaluator(Origin.Authority.Tries, Origin.Clock), Origin.Clock);
|
|
Caller = new(new AnonymousIdentityToken(), [], Origin.Context.PrincipalId, Origin.Context.ApiKeyId,
|
|
Origin.Context.CredentialVersion, Origin.Context.CredentialExpiresUtc);
|
|
var serving = Origin.Serving;
|
|
var lease = new MetadataAuthorityLease(serving, new(1, 1, TimeSpan.FromSeconds(15)), Origin.Clock.GetTimestamp(),
|
|
TimeSpan.FromSeconds(15), TimeSpan.Zero, Origin.Clock);
|
|
var authority = Origin.Activation.CaptureAuthority();
|
|
NodeIds = new NodeId[items];
|
|
for (var i = 0; i < items; i++)
|
|
{
|
|
var origin = Origin.Raw with { Address = Origin.Raw.Address with { Identifier = Origin.Raw.Address.Identifier + i }, Subject = Origin.Raw.Subject + i };
|
|
var mapped = origin with { MappingId = "mapping", MappingRevision = 1, Subject = "Plant/branch/Speed" + i };
|
|
var subject = new MappedNamespaceSubject(mapped, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw,
|
|
Segments = ["Plant", "branch", "Speed" + i] }, ["folder"], serving, DataOperations.Subscribe, false);
|
|
var metadata = new DataMetadata(mapped, "Speed" + i, "Variable", DataValueKind.Int32, -1, [], false, DataOperations.Subscribe, 1, null, null, false, Serving: serving);
|
|
var proof = new ProjectedNodeProof(ProjectedDataIds.Identifier("mapping", origin.Address), metadata, subject,
|
|
new([subject], 1, authority), lease, 1, metadata with { View = origin }, TimeSpan.FromSeconds(30));
|
|
var nodeId = new NodeId("projected-" + i, 2);
|
|
NodeIds[i] = nodeId;
|
|
_proofs[proof.LocalIdentifier] = proof;
|
|
_definitions[nodeId] = new(DataRealm.Raw, proof.LocalIdentifier, new NodeId("parent", 2), metadata, 1, () => true);
|
|
}
|
|
}
|
|
|
|
internal ProjectedDataAccess Create(int maxDemands) =>
|
|
new(this, this, this, _ => "link", _policy, this, Origin.Clock, new(maxDemands, 8, 64L * 1024 * 1024, 4))
|
|
{ PublishProbeForTests = MeasureAllocations ? Allocations : null };
|
|
|
|
internal IProjectedDemandLease[] AcquireAll(ProjectedDataAccess access)
|
|
{
|
|
var demands = new IProjectedDemandLease[NodeIds.Length];
|
|
for (var i = 0; i < NodeIds.Length; i++)
|
|
{
|
|
access.TryAcquire(NodeIds[i], Caller, DataOperations.Subscribe, out var demand).ShouldBeTrue();
|
|
demands[i] = demand!;
|
|
}
|
|
return demands;
|
|
}
|
|
|
|
internal async Task WaitForAsync(Func<bool> condition, TimeSpan timeout, string because)
|
|
{
|
|
var deadline = DateTime.UtcNow + timeout;
|
|
while (!condition())
|
|
{
|
|
if (DateTime.UtcNow > deadline) throw new ShouldAssertException(because + " | " +
|
|
string.Join(" ", ProjectedStreamDiagnostics.Capture().Where(x => x.Value != 0).Select(x => x.Key + "=" + x.Value)) +
|
|
" | opens=" + Opens + " commands=" + string.Join(",", Commands.GroupBy(c => c.GetType().Name)
|
|
.Select(g => g.Key + "x" + g.Count() + "(" + g.Sum(CommandItems) + " items)")));
|
|
await Task.Delay(10);
|
|
}
|
|
}
|
|
|
|
private static int CommandItems(DataSubscriptionCommand command) => command switch
|
|
{
|
|
OpenSubscription o => o.Items.Count, AddSubscriptionItems a => a.Items.Count, RemoveSubscriptionItems r => r.Items.Count,
|
|
ChallengeSubscriptionFreshness c => c.Items.Count, _ => 0
|
|
};
|
|
|
|
/// <summary>
|
|
/// Runs the fixture clock at about half real speed until disposed: the cohort's command pacer (32/s) and the origin's
|
|
/// per-second command window both read this clock, so a long open stalls on a frozen manual clock.
|
|
/// </summary>
|
|
internal IAsyncDisposable PumpClock()
|
|
{
|
|
var stop = new CancellationTokenSource();
|
|
var pump = Task.Run(async () =>
|
|
{
|
|
while (!stop.IsCancellationRequested)
|
|
{
|
|
try { await Task.Delay(20, stop.Token); } catch (OperationCanceledException) { break; }
|
|
Origin.Clock.Advance(TimeSpan.FromMilliseconds(10));
|
|
}
|
|
});
|
|
return new ClockPump(stop, pump);
|
|
}
|
|
private sealed class ClockPump(CancellationTokenSource stop, Task pump) : IAsyncDisposable
|
|
{
|
|
public async ValueTask DisposeAsync() { await stop.CancelAsync(); await pump; stop.Dispose(); }
|
|
}
|
|
|
|
internal void PublishVersion(long version, int value)
|
|
{
|
|
HubTest.Publish(Origin.Hub, Origin.Ticket, version, value);
|
|
Origin.Hub.ProcessPending();
|
|
}
|
|
|
|
/// <summary>Drops the current physical stream (origin restart / failover) so the cohort must re-open everything.</summary>
|
|
internal async Task DropStreamAsync()
|
|
{
|
|
foreach (var stream in _streams.ToArray()) await stream.DisposeAsync();
|
|
}
|
|
|
|
public TimeProvider Clock => Origin.Clock;
|
|
public event Action<string, long>? Invalidated { add { } remove { } }
|
|
public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => throw new NotSupportedException();
|
|
public Task<IProjectedPreparedPage> PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
|
|
public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) =>
|
|
_proofs.TryGetValue(localId, out proof) && realm == DataRealm.Raw;
|
|
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin)
|
|
{
|
|
pin = _proofs.ContainsKey(localId) ? new NoopPin() : null;
|
|
return pin is not null;
|
|
}
|
|
public bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition) => _definitions.TryGetValue(nodeId, out definition);
|
|
public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId) { nodeId = null; return false; }
|
|
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) =>
|
|
ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(new Lease(Origin.Connection()));
|
|
public bool TryBind(ProjectedValueRoute route) => true;
|
|
/// <summary>#994 (R-10): this many publications are answered CapacityExhausted (a momentarily full sink).</summary>
|
|
internal int CapacityRefusals;
|
|
public ProjectedPublishOutcome TryPublishOrBackpressure(IReadOnlyList<ProjectedValueUpdate> updates)
|
|
{
|
|
if (Volatile.Read(ref CapacityRefusals) > 0 && Interlocked.Decrement(ref CapacityRefusals) >= 0) return ProjectedPublishOutcome.CapacityExhausted;
|
|
return TryPublish(updates) ? ProjectedPublishOutcome.Accepted : ProjectedPublishOutcome.Refused;
|
|
}
|
|
public bool TryPublish(IReadOnlyList<ProjectedValueUpdate> updates)
|
|
{
|
|
if (RefusePublish) return false;
|
|
var allocatedBefore = MeasureAllocations ? GC.GetAllocatedBytesForCurrentThread() : 0;
|
|
try { return PublishAll(updates); }
|
|
finally { if (MeasureAllocations) Allocations.AddSink(GC.GetAllocatedBytesForCurrentThread() - allocatedBefore, updates.Count); }
|
|
}
|
|
private bool PublishAll(IReadOnlyList<ProjectedValueUpdate> updates)
|
|
{
|
|
foreach (var update in updates)
|
|
{
|
|
if (PublishGate is { } gate && !gate(update)) return false;
|
|
Interlocked.Increment(ref Publishes);
|
|
if (update.IsCompleteSnapshot) Baselines.AddOrUpdate(update.Route.LocalIdentifier, 1, (_, count) => count + 1);
|
|
var version = update.SourceVersion ?? 0;
|
|
var target = Volatile.Read(ref TargetVersion);
|
|
if (target != 0 && version == target && (!Latest.TryGetValue(update.Route.LocalIdentifier, out var previous) || previous != target))
|
|
Interlocked.Increment(ref AtTargetVersion);
|
|
Latest[update.Route.LocalIdentifier] = version;
|
|
}
|
|
return true;
|
|
}
|
|
public void Retire(ProjectedValueRoute route) => Interlocked.Increment(ref Retired);
|
|
public void Dispose() => Origin.Dispose();
|
|
|
|
private sealed class NoopPin : IDisposable { public void Dispose() { } }
|
|
private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease
|
|
{
|
|
public IDataConnection Connection => connection;
|
|
public CancellationToken CancellationToken => CancellationToken.None;
|
|
public ValueTask DisposeAsync() => connection.DisposeAsync();
|
|
}
|
|
private sealed class CapturingService(CohortScaleFixture owner, IDataSubscriptionService inner) : IDataSubscriptionService
|
|
{
|
|
public async Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
|
|
{
|
|
var stream = await inner.SubscribeAsync(cancellationToken);
|
|
Interlocked.Increment(ref owner.Opens);
|
|
if (stream is DataSubscriptionSession session)
|
|
{
|
|
Volatile.Write(ref owner._session, session);
|
|
if (owner.MeasureAllocations) owner.Allocations.Attach(session);
|
|
}
|
|
var wrapped = new Recording(owner, stream);
|
|
owner._streams.Enqueue(wrapped);
|
|
return wrapped;
|
|
}
|
|
}
|
|
private sealed class Recording(CohortScaleFixture owner, IDataSubscription inner) : IDataSubscription, IDataSubscriptionFreshnessSupport, IDataSubscriptionCommandLimits,
|
|
IDataSubscriptionProvenance
|
|
{
|
|
public ServingIdentity Serving => owner.Origin.Serving;
|
|
// The origin was built with subscriptionFreshnessChallenges: true (as LocalDataRuntimeComposition is).
|
|
public bool SupportsFreshnessChallenges => true;
|
|
public int FreshnessMaxItems => owner.MaxBatchItems;
|
|
public int MaxCommandItems => (inner as IDataSubscriptionCommandLimits)?.MaxCommandItems ?? owner.MaxBatchItems;
|
|
private readonly ConcurrentDictionary<string, long> _challenges = new(StringComparer.Ordinal);
|
|
public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
|
|
{
|
|
owner.Commands.Enqueue(command);
|
|
if (command is ChallengeSubscriptionFreshness challenge) _challenges[challenge.CommandId] = owner.Clock.GetTimestamp();
|
|
return inner.SendAsync(command, cancellationToken);
|
|
}
|
|
// Mirrors GrpcDataConnection.RemoteSubscription: a challenged value's upper age bound is its origin lower bound plus the
|
|
// consumer-side elapsed time since the challenge was sent (the local session leaves Upper unknown).
|
|
public async IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(
|
|
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken)
|
|
{
|
|
await using var frames = inner.ReadAllAsync(cancellationToken).GetAsyncEnumerator(cancellationToken);
|
|
while (true)
|
|
{
|
|
// #1094: a frame that is already waiting completes on this thread, so its read cost is attributable per thread.
|
|
var readStart = owner.MeasureAllocations ? GC.GetAllocatedBytesForCurrentThread() : 0;
|
|
var next = frames.MoveNextAsync();
|
|
if (next.IsCompleted)
|
|
{
|
|
var readBytes = owner.MeasureAllocations ? GC.GetAllocatedBytesForCurrentThread() - readStart : 0;
|
|
if (!next.GetAwaiter().GetResult()) yield break;
|
|
if (frames.Current is DataSubscriptionValues counted && owner.MeasureAllocations) owner.Allocations.AddRead(readBytes, counted.Items.Count);
|
|
}
|
|
else if (!await next.ConfigureAwait(false)) yield break;
|
|
var frame = frames.Current;
|
|
if (frame is not DataSubscriptionValues values) { yield return frame; continue; }
|
|
var bodyStart = owner.MeasureAllocations ? GC.GetAllocatedBytesForCurrentThread() : 0;
|
|
var bounded = new List<DataSubscriptionValue>(values.Items.Count);
|
|
foreach (var item in values.Items)
|
|
{
|
|
var bounds = item.AgeBounds; long? observed = null;
|
|
if (item.FreshnessChallengeId is { } nonce && _challenges.TryGetValue(nonce, out var start) && bounds.Lower is { } lower)
|
|
{
|
|
observed = owner.Clock.GetTimestamp();
|
|
bounds = new(bounds.Lower, lower + owner.Clock.GetElapsedTime(start, observed.Value));
|
|
}
|
|
bounded.Add(item with { Sample = item.Sample with { Value = item.Sample.Value.Retain() }, AgeBounds = bounds,
|
|
FreshnessObservedTimestamp = observed });
|
|
}
|
|
var result = new DataSubscriptionValues(values.SubscriptionId, values.StreamEpoch, values.Sequence, values.IsSnapshot, bounded, values);
|
|
if (owner.MeasureAllocations) owner.Allocations.AddConsumer(GC.GetAllocatedBytesForCurrentThread() - bodyStart, bounded.Count);
|
|
yield return result;
|
|
}
|
|
}
|
|
public ValueTask DisposeAsync() => inner.DisposeAsync();
|
|
}
|
|
}
|