test: validate grpc data connections with local docker and opcua cli
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup><OutputType>Exe</OutputType><IsPackable>false</IsPackable></PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../../../src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ZB.MOM.WW.OtOpcUa.Runtime.csproj" />
|
||||
<PackageReference Include="Grpc.Net.Client" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,316 @@
|
||||
using System.Text.Json;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace GrpcDataProbe;
|
||||
|
||||
// Shared by the external wire client and the fixture-only in-process caller.
|
||||
public sealed record ProbeCommand(string Id, string ConnectionId, string Operation, string Realm = "Raw",
|
||||
string OriginCluster = "SOURCE", string NamespaceUri = "", string Path = "", string? Subject = null,
|
||||
int TimeoutSeconds = 30, int Value = 42, string? OperationId = null, string? ExpectedNodeId = null,
|
||||
string? ExpectedRole = null, string? ExpectedState = null, string? Continuation = null,
|
||||
long? ExpectedCatalogRevision = null, string? ExpectedIncarnation = null, long? ExpectedGeneration = null,
|
||||
WorkloadOptions? Workload = null, string? WorkloadUnsNamespaceUri = null,
|
||||
IReadOnlyDictionary<string, string>? WorkloadBrowseRoots = null, int? MaximumAgeMilliseconds = 5000);
|
||||
|
||||
public sealed record ProbeResult(string Id, string Operation, bool Passed, int Assertions,
|
||||
Dictionary<string, object?> Observations, string? Failure = null);
|
||||
|
||||
public static class ProbeEngine
|
||||
{
|
||||
private sealed class ProbeAssertionException(string name) : Exception(name) { }
|
||||
public static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web) { WriteIndented = true };
|
||||
public static async Task<ProbeResult> RunAsync(IDataConnection connection, ProbeCommand command, CancellationToken stop)
|
||||
{
|
||||
if (command.Operation == "workload") return await WorkloadEngine.RunAsync(connection, command, stop);
|
||||
var observations = new Dictionary<string, object?>();
|
||||
var assertions = 0;
|
||||
var phase = ProbeFailurePhase.ValidateCommand;
|
||||
DataCapabilities? validatedCapabilities = null;
|
||||
void Check(bool condition, string name)
|
||||
{
|
||||
if (!condition) throw new ProbeAssertionException(name);
|
||||
assertions++;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (command.TimeoutSeconds is < 1 or > 120) throw new InvalidOperationException("invalid deadline");
|
||||
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(stop);
|
||||
deadline.CancelAfter(TimeSpan.FromSeconds(command.TimeoutSeconds));
|
||||
var ct = deadline.Token;
|
||||
var budgetSeconds = command.Operation is "write" or "dedup" or "mixed-write" ? 30 : 10;
|
||||
var budget = new DataBudget(TimeSpan.FromSeconds(Math.Min(command.TimeoutSeconds, budgetSeconds)), 32, 1024 * 1024);
|
||||
phase = ProbeFailurePhase.GetCapabilities;
|
||||
var caps = await connection.GetCapabilitiesAsync(budget, ct);
|
||||
caps.Validate();
|
||||
Check(caps.ProtocolMajor == 1, "protocol major");
|
||||
Check(caps.ProtocolMinor >= 3 && caps.ResponseServingIdentity && caps.SubscriptionAgeReadiness, "negotiated serving and age protocol");
|
||||
Check(!caps.CompactBatches || caps.CompactCodecVersion == 1, "compact negotiation");
|
||||
observations["serving"] = caps.Serving;
|
||||
observations["readiness"] = caps.Readiness.ToString();
|
||||
observations["operations"] = caps.Operations.ToString();
|
||||
observations["compact"] = caps.CompactBatches;
|
||||
observations["limits"] = caps.Limits;
|
||||
if (command.ExpectedNodeId is { } expectedNode) Check(caps.Serving.NodeId == expectedNode, "serving node");
|
||||
if (command.ExpectedRole is { } expectedRole) Check(caps.Serving.Role == expectedRole, "serving role");
|
||||
if (command.Operation == "capabilities")
|
||||
{
|
||||
if (command.ExpectedState is { } state) Check(caps.Readiness.ToString() == state, "expected readiness");
|
||||
return new(command.Id, command.Operation, true, assertions, observations);
|
||||
}
|
||||
Check(caps.Readiness == DataReadiness.Ready
|
||||
|| command.Operation == "read" && command.ExpectedState == "UnavailableData", "connection ready");
|
||||
validatedCapabilities = caps;
|
||||
var realm = Enum.Parse<DataRealm>(command.Realm, ignoreCase: true);
|
||||
var view = new DataView(new(command.OriginCluster, command.NamespaceUri, "string", command.Path),
|
||||
realm, null, 0, command.Subject ?? command.Path);
|
||||
view.Validate();
|
||||
if (command.Operation is "browse" or "continuation")
|
||||
{
|
||||
phase = ProbeFailurePhase.Metadata;
|
||||
view = await CanonicalBrowseViewAsync(connection, view, budget, ct);
|
||||
observations["browseView"] = view;
|
||||
Check(view.Address.Identifier == command.Path, "canonical browse container identity");
|
||||
phase = ProbeFailurePhase.Browse;
|
||||
var branch = await connection.BrowseAsync(new(view, null, command.Continuation, budget with { MaxItems = 1 }), ct);
|
||||
observations["status"] = branch.Status.ToString();
|
||||
observations["complete"] = branch.Complete;
|
||||
observations["continuation"] = branch.Continuation;
|
||||
observations["items"] = branch.Items;
|
||||
observations["lease"] = branch.Lease;
|
||||
Check(branch.Status.ToString() == (command.ExpectedState ?? "Good"), "browse status");
|
||||
Check(branch.Items.Count <= 1, "page bound");
|
||||
var bytes = ZB.MOM.WW.OtOpcUa.Commons.DataConnections.DataProtoMapper.EncodeBrowseResponse(branch).CalculateSize();
|
||||
Check(bytes <= budget.MaxBytes, "browse byte budget");
|
||||
observations["serializedBytes"] = bytes;
|
||||
if (branch.Lease is { } lease) Check(lease.Duration > TimeSpan.Zero && lease.Duration <= caps.Limits.MaxMetadataLease, "bounded metadata lease");
|
||||
if (!branch.Complete && branch.Status == DataItemStatus.Good) Check(!string.IsNullOrEmpty(branch.Continuation), "cursor present");
|
||||
}
|
||||
else if (command.Operation == "metadata")
|
||||
{
|
||||
phase = ProbeFailurePhase.Metadata;
|
||||
var metadata = await connection.GetMetadataAsync(new([view], budget), ct);
|
||||
Check(metadata.Count == 1, "metadata cardinality");
|
||||
Check(metadata[0].Status.ToString() == (command.ExpectedState ?? "Good"), "metadata status");
|
||||
observations["metadata"] = metadata[0].Value;
|
||||
}
|
||||
else if (command.Operation == "read")
|
||||
{
|
||||
phase = ProbeFailurePhase.Read;
|
||||
Check(command.MaximumAgeMilliseconds is null or >= 0 and <= 30000, "bounded requested read freshness");
|
||||
var maximumAge = command.MaximumAgeMilliseconds is { } milliseconds ? TimeSpan.FromMilliseconds(milliseconds) : (TimeSpan?)null;
|
||||
var items = await connection.ReadAsync(new([new("one", view, maximumAge)], budget), ct);
|
||||
try
|
||||
{
|
||||
Check(items.Count == 1 && items[0].CorrelationId == "one", "ordered read cardinality");
|
||||
observations["status"] = items[0].Status.ToString();
|
||||
observations["resultReadiness"] = items[0].Readiness.ToString();
|
||||
observations["maximumAgeMilliseconds"] = command.MaximumAgeMilliseconds;
|
||||
observations["ageBounds"] = new { lowerMilliseconds = items[0].AgeBounds.Lower?.TotalMilliseconds,
|
||||
upperMilliseconds = items[0].AgeBounds.Upper?.TotalMilliseconds };
|
||||
observations["sample"] = items[0].Sample is { } observedSample
|
||||
? new { observedSample.StatusCode, observedSample.SourceTimestampUtc, observedSample.ServerTimestampUtc,
|
||||
observedSample.Serving, observedSample.Version,
|
||||
value = ZB.MOM.WW.OtOpcUa.Commons.DataConnections.TypedValueCodec.Encode(observedSample.Value).ToString() }
|
||||
: null;
|
||||
if (command.ExpectedState == "UnavailableData")
|
||||
{
|
||||
Check(items[0].Status is DataItemStatus.WaitingForInitialData or DataItemStatus.Unavailable,
|
||||
"unavailable data status");
|
||||
Check(items[0].Readiness != DataReadiness.Ready, "unavailable data must not be ready");
|
||||
Check(items[0].Sample is null, "unavailable data must not carry a sample");
|
||||
}
|
||||
else
|
||||
Check(items[0].Status.ToString() == (command.ExpectedState ?? "Good"), "read status");
|
||||
if (command.ExpectedState is null or "Good")
|
||||
{
|
||||
Check(items[0].Readiness == DataReadiness.Ready, "read result readiness");
|
||||
if (maximumAge is { } boundedAge)
|
||||
Check(items[0].AgeBounds.Lower is { } lower && items[0].AgeBounds.Upper is { } upper
|
||||
&& lower >= TimeSpan.Zero && upper >= lower && upper <= boundedAge, "finite read age within requested bound");
|
||||
Check(items[0].Sample is not null, "read sample");
|
||||
var sample = items[0].Sample!;
|
||||
Check(sample.StatusCode == 0, "sample quality");
|
||||
Check(sample.SourceTimestampUtc != default && sample.ServerTimestampUtc != default, "sample timestamps");
|
||||
}
|
||||
}
|
||||
finally { foreach (var item in items) item.Dispose(); }
|
||||
}
|
||||
else if (command.Operation is "write" or "dedup" or "mixed-write")
|
||||
{
|
||||
phase = ProbeFailurePhase.Metadata;
|
||||
var metadata = await connection.GetMetadataAsync(new([view], budget), ct);
|
||||
Check(metadata.Count == 1 && metadata[0].Value is not null, "write metadata");
|
||||
var meta = metadata[0].Value!;
|
||||
using var value = Scalar(meta.ValueKind, command.Value);
|
||||
var item = new WriteItem("one", command.OperationId ?? Guid.NewGuid().ToString("N"), view, value,
|
||||
command.ExpectedCatalogRevision ?? meta.CatalogRevision, command.ExpectedIncarnation ?? caps.Serving.Incarnation,
|
||||
budget.Timeout, command.ExpectedGeneration ?? caps.Serving.ServingGeneration);
|
||||
var batch = command.Operation == "mixed-write"
|
||||
? new WriteBatch([item, item with { CorrelationId = "two", OperationId = Guid.NewGuid().ToString("N"),
|
||||
View = view with { Address = view.Address with { Identifier = command.Path + "/absent" }, Subject = command.Path + "/absent" } }], budget)
|
||||
: new WriteBatch([item], budget);
|
||||
phase = ProbeFailurePhase.Write;
|
||||
var outcomes = await connection.WriteAsync(batch, ct);
|
||||
// Preserve bounded, non-secret outcome evidence even if an assertion below fails.
|
||||
observations["outcomes"] = outcomes.Select(result => new
|
||||
{
|
||||
result.CorrelationId,
|
||||
Outcome = new { result.Outcome.State, result.Outcome.StatusCode },
|
||||
}).ToArray();
|
||||
Check(outcomes.Count == batch.Items.Count, "write cardinality");
|
||||
Check(outcomes[0].CorrelationId == "one", "write order");
|
||||
Check(outcomes[0].Outcome.State.ToString() == (command.ExpectedState ?? "DriverConfirmedSuccess"), "write outcome");
|
||||
if (command.Operation == "mixed-write") Check(outcomes[1].Outcome.State == DataWriteState.RejectedBeforeDispatch, "undispatched item");
|
||||
if (command.Operation == "dedup")
|
||||
{
|
||||
var duplicate = await connection.WriteAsync(batch, ct);
|
||||
Check(duplicate.Count == 1 && duplicate[0].Outcome.State == outcomes[0].Outcome.State, "duplicate stable outcome");
|
||||
}
|
||||
observations["outcomes"] = outcomes;
|
||||
observations["operationId"] = item.OperationId;
|
||||
}
|
||||
else if (command.Operation == "subscribe")
|
||||
{
|
||||
phase = ProbeFailurePhase.Subscribe;
|
||||
await using var subscription = await connection.SubscribeAsync(ct);
|
||||
var id = Guid.NewGuid().ToString("N");
|
||||
await subscription.SendAsync(new OpenSubscription(id, 1, "open", TimeSpan.FromSeconds(5),
|
||||
[new("one", view, new(TimeSpan.FromMilliseconds(200), TimeSpan.FromMilliseconds(200), DataChangeTrigger.StatusValue, null))],
|
||||
false, TimeSpan.FromSeconds(command.TimeoutSeconds), budget), ct);
|
||||
var acknowledged = false;
|
||||
var snapshot = false;
|
||||
long lastSequence = 0;
|
||||
var values = new HashSet<string>(StringComparer.Ordinal);
|
||||
DataItemHandle? handle = null;
|
||||
var controls = new List<object>();
|
||||
var controlCounts = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
var streamEvidence = new Dictionary<string, object?>
|
||||
{
|
||||
["frames"] = 0, ["acknowledged"] = false, ["snapshotValue"] = false,
|
||||
["distinctValues"] = 0, ["lastSequence"] = 0L,
|
||||
["controlCounts"] = controlCounts, ["controls"] = controls,
|
||||
};
|
||||
observations["stream"] = streamEvidence;
|
||||
await foreach (var frame in subscription.ReadAllAsync(ct))
|
||||
{
|
||||
streamEvidence["frames"] = (int)streamEvidence["frames"]! + 1;
|
||||
streamEvidence["lastFrame"] = frame.GetType().Name;
|
||||
streamEvidence["lastSequence"] = frame.Sequence;
|
||||
if (frame is DataSubscriptionControl control)
|
||||
{
|
||||
var kind = control.Kind.ToString();
|
||||
controlCounts[kind] = controlCounts.GetValueOrDefault(kind) + 1;
|
||||
if (controls.Count < 32)
|
||||
controls.Add(new { Kind = kind, Reason = SafeControlReason(control.Diagnostic) });
|
||||
}
|
||||
Check(frame.SubscriptionId == id && frame.StreamEpoch == 1 && frame.Sequence > lastSequence, "stream ordering");
|
||||
lastSequence = frame.Sequence;
|
||||
if (frame is DataSubscriptionAck ack)
|
||||
{
|
||||
streamEvidence["ackStatuses"] = ack.Items.Take(32).Select(item => item.Status.ToString()).ToArray();
|
||||
Check(ack.CommandId == "open" && ack.Items.Count == 1 && ack.Items[0].Status == DataItemStatus.Good && ack.Items[0].Handle is not null, "open acknowledgement");
|
||||
handle = ack.Items[0].Handle;
|
||||
acknowledged = true;
|
||||
streamEvidence["acknowledged"] = true;
|
||||
}
|
||||
if (frame is DataSubscriptionValues update)
|
||||
{
|
||||
using (update)
|
||||
{
|
||||
snapshot |= update.IsSnapshot;
|
||||
streamEvidence["snapshotValue"] = snapshot;
|
||||
foreach (var entry in update.Items)
|
||||
{
|
||||
Check(acknowledged && entry.Handle == handle, "acknowledged handle revision");
|
||||
Check(entry.Sample.StatusCode == 0 && entry.Readiness == DataReadiness.Ready, "stream quality and readiness");
|
||||
values.Add(ZB.MOM.WW.OtOpcUa.Commons.DataConnections.TypedValueCodec.Encode(entry.Sample.Value).ToString());
|
||||
streamEvidence["distinctValues"] = values.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (acknowledged && snapshot && values.Count >= 2) break;
|
||||
}
|
||||
Check(acknowledged && snapshot && values.Count >= 2, "changing snapshot and updates");
|
||||
observations["distinctValues"] = values.Count;
|
||||
observations["lastSequence"] = lastSequence;
|
||||
}
|
||||
else throw new InvalidOperationException("unsupported operation");
|
||||
return new(command.Id, command.Operation, true, assertions, observations);
|
||||
}
|
||||
catch (Exception error) when (error is not OutOfMemoryException)
|
||||
{
|
||||
var failure = ProbeFailureClassifier.Capture(error, phase);
|
||||
observations["failurePhase"] = failure.Phase;
|
||||
observations["failureEvidence"] = failure;
|
||||
if (command.Operation == "read" && command.ExpectedState == "Denied" && phase == ProbeFailurePhase.Read
|
||||
&& ProbeFailureClassifier.IsPinnedReadPermissionDenied(connection.Target, validatedCapabilities, failure))
|
||||
{
|
||||
observations["status"] = "Denied";
|
||||
observations["reason"] = "pinned origin Read RPC explicitly denied the unadvertised operation";
|
||||
observations["denialBoundary"] = "origin Read RPC";
|
||||
return new(command.Id, command.Operation, true, assertions + 1, observations);
|
||||
}
|
||||
if (command.ExpectedState == "TargetIneligible" && phase == ProbeFailurePhase.GetCapabilities
|
||||
&& failure.Category == "TargetIneligible" && !failure.Truncated)
|
||||
{
|
||||
observations["readiness"] = "Unavailable";
|
||||
observations["selectionRejection"] = "TargetIneligible";
|
||||
return new(command.Id, command.Operation, true, assertions + 1, observations);
|
||||
}
|
||||
if (command.Operation == "capabilities" && command.ExpectedState == "Unavailable"
|
||||
&& error is InvalidOperationException { Message: "No ready authenticated data endpoint." or "Data endpoint discovery is backing off." })
|
||||
{
|
||||
observations["readiness"] = "Unavailable";
|
||||
observations["reason"] = "authenticated endpoint selection failed";
|
||||
return new(command.Id, command.Operation, true, assertions + 1, observations);
|
||||
}
|
||||
if (command.ExpectedState == "Denied" && (error is UnauthorizedAccessException
|
||||
|| error is Grpc.Core.RpcException { StatusCode: Grpc.Core.StatusCode.PermissionDenied }))
|
||||
{
|
||||
observations["status"] = "Denied";
|
||||
observations["reason"] = "explicit permission rejection";
|
||||
return new(command.Id, command.Operation, true, assertions + 1, observations);
|
||||
}
|
||||
// Only fixed local assertion names and classifier codes cross the evidence boundary.
|
||||
return new(command.Id, command.Operation, false, assertions, observations,
|
||||
error is ProbeAssertionException ? error.Message : failure.Category);
|
||||
}
|
||||
}
|
||||
|
||||
private static string? SafeControlReason(string? diagnostic) => diagnostic switch
|
||||
{
|
||||
null => null,
|
||||
"Source change history expired." or "Source became unavailable." or
|
||||
"Snapshot catch-up expired; retry later." or "Snapshot lifetime expired; retry later." or
|
||||
"Snapshot admission exhausted; retry later." or "Freshness snapshot admission exhausted; retry later." or
|
||||
"Pending snapshot memory exhausted." or "Pending value memory exhausted." or
|
||||
"Pending value capacity exhausted." or "Pending control capacity exhausted." or
|
||||
"Transport capacity exhausted." => diagnostic,
|
||||
_ when diagnostic.StartsWith("Snapshot pacing; retry after ", StringComparison.Ordinal) => "Snapshot pacing",
|
||||
_ => "Other server control reason",
|
||||
};
|
||||
|
||||
internal static async Task<DataView> CanonicalBrowseViewAsync(IDataConnection connection, DataView requested,
|
||||
DataBudget budget, CancellationToken stop)
|
||||
{
|
||||
// Container IDs and physical authorization subjects are separate in UNS.
|
||||
// Metadata resolves the authoritative subject without altering Read's
|
||||
// deliberate forged-subject negative scenario.
|
||||
var metadata = await connection.GetMetadataAsync(new([requested], budget), stop);
|
||||
if (metadata.Count != 1 || metadata[0].Status != DataItemStatus.Good || metadata[0].Value is not { } parent
|
||||
|| parent.View.Address != requested.Address || parent.View.Realm != requested.Realm || parent.View.MappingId is not null)
|
||||
throw new InvalidOperationException("Canonical browse parent metadata unavailable.");
|
||||
parent.View.Validate();
|
||||
return parent.View;
|
||||
}
|
||||
|
||||
private static DataValue Scalar(DataValueKind kind, int value) => DataValue.FromScalar(kind, kind switch
|
||||
{
|
||||
DataValueKind.Int8 => (object)checked((sbyte)value), DataValueKind.UInt8 => checked((byte)value),
|
||||
DataValueKind.Int16 => checked((short)value), DataValueKind.UInt16 => checked((ushort)value),
|
||||
DataValueKind.Int32 => value, DataValueKind.UInt32 => checked((uint)value),
|
||||
DataValueKind.Int64 => (long)value, DataValueKind.UInt64 => checked((ulong)value),
|
||||
DataValueKind.Float => (float)value, DataValueKind.Double => (double)value,
|
||||
_ => throw new InvalidOperationException("fixture writable scalar type")
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using System.Security.Authentication;
|
||||
using Grpc.Core;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace GrpcDataProbe;
|
||||
|
||||
/// <summary>Fixed fixture stages; no caller-controlled text is emitted as a stage.</summary>
|
||||
public enum ProbeFailurePhase
|
||||
{
|
||||
ValidateCommand, GetCapabilities, Metadata, Browse, Read, Write, Subscribe, NodeProbe,
|
||||
WireSetup, WirePositiveCapabilities, WireProtocolMajor, WirePreviousKey, WireBadKey, WireWrongCa,
|
||||
WireWrongSan, WireWrongListener, WireH2c, WireRetiredCa, WireOperation, Other
|
||||
}
|
||||
|
||||
/// <summary>Fixed local rejection code and an optional gRPC status enum name.</summary>
|
||||
public sealed record ProbeFailureFrame(string Code, string? RpcStatus = null);
|
||||
|
||||
/// <summary>Bounded nonsecret exception-chain evidence for fixture assertions.</summary>
|
||||
public sealed record ProbeFailureEvidence(string Phase, string Category, bool Truncated, IReadOnlyList<ProbeFailureFrame> Chain);
|
||||
|
||||
/// <summary>Classifies only known local messages and typed transport failure categories.</summary>
|
||||
public static class ProbeFailureClassifier
|
||||
{
|
||||
/// <summary>Recognizes only an explicit missing-Read denial from the exact pinned SOURCE primary.</summary>
|
||||
public static bool IsPinnedReadPermissionDenied(DataTarget target, DataCapabilities? capabilities, ProbeFailureEvidence evidence) =>
|
||||
target.Mode == DataTargetMode.Node && target.Consistency == DataConsistency.Primary
|
||||
&& target.ExpectedClusterId == "SOURCE" && target.ExpectedNodeId is "source-1:4053" or "source-2:4053"
|
||||
&& capabilities is { ProtocolMajor: 1, ProtocolMinor: >= 3, Readiness: DataReadiness.Ready,
|
||||
ResponseServingIdentity: true, SubscriptionAgeReadiness: true, ClusterId: "SOURCE" }
|
||||
&& capabilities.Serving.NodeId == target.ExpectedNodeId && capabilities.Serving.Role == "Primary"
|
||||
&& !string.IsNullOrWhiteSpace(capabilities.Serving.Incarnation) && capabilities.Serving.CatalogEpoch > 0
|
||||
&& capabilities.Serving.AuthorityEpoch > 0 && capabilities.Serving.ServingGeneration > 0
|
||||
&& (capabilities.Operations & DataOperations.Read) == 0
|
||||
&& (capabilities.Operations & ~(DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe)) == 0
|
||||
&& evidence is { Phase: "Read", Category: "RpcFailure", Truncated: false }
|
||||
&& evidence.Chain.Count == 2
|
||||
&& evidence.Chain[0] is { Code: "NoReadyEndpoint", RpcStatus: null }
|
||||
&& evidence.Chain[1] is { Code: "RpcFailure", RpcStatus: "PermissionDenied" };
|
||||
|
||||
/// <summary>Recognizes a typed TLS authentication rejection at the retired-CA fixture phase.</summary>
|
||||
public static bool IsRetiredCaTlsRejection(ProbeFailureEvidence evidence) =>
|
||||
evidence is { Phase: "WireRetiredCa", Category: "TlsFailure", Truncated: false }
|
||||
&& evidence.Chain.Count == 3
|
||||
&& evidence.Chain[0] is { Code: "RpcFailure", RpcStatus: "Internal" or "Unavailable" }
|
||||
&& evidence.Chain[1] is { Code: "TransportFailure", RpcStatus: null }
|
||||
&& evidence.Chain[2] is { Code: "TlsFailure", RpcStatus: null };
|
||||
|
||||
/// <summary>Captures bounded fixed-code evidence without exception text, URIs or stacks.</summary>
|
||||
public static ProbeFailureEvidence Capture(Exception error, ProbeFailurePhase phase)
|
||||
{
|
||||
var frames = new List<ProbeFailureFrame>(8);
|
||||
Exception? current = error;
|
||||
while (current is not null && frames.Count < 8)
|
||||
{
|
||||
frames.Add(current switch
|
||||
{
|
||||
InvalidOperationException { Message: "No ready authenticated data endpoint." } => new("NoReadyEndpoint"),
|
||||
InvalidOperationException { Message: "Endpoint is not an authenticated ready target." } => new("TargetIneligible"),
|
||||
InvalidOperationException { Message: "Data endpoint discovery is backing off." } => new("DiscoveryBackoff"),
|
||||
InvalidOperationException { Message: "No ready subscription endpoint." } => new("NoReadySubscriptionEndpoint"),
|
||||
InvalidOperationException { Message: "Subscriptions unavailable or peer stream capacity exhausted." } => new("SubscriptionUnavailable"),
|
||||
InvalidOperationException { Message: "Unary capacity exhausted." } => new("UnaryCapacity"),
|
||||
UnauthorizedAccessException { Message: "Connection credential or trust unavailable." } => new("SecurityMaterialUnavailable"),
|
||||
TimeoutException { Message: "Original data request budget expired." } => new("RequestBudgetExpired"),
|
||||
RpcException rpc => new("RpcFailure", Enum.IsDefined(rpc.StatusCode) ? rpc.StatusCode.ToString() : "Unknown"),
|
||||
AuthenticationException => new("TlsFailure"),
|
||||
HttpRequestException => new("TransportFailure"),
|
||||
OperationCanceledException => new("Cancelled"),
|
||||
_ => new("Other")
|
||||
});
|
||||
current = current.InnerException;
|
||||
}
|
||||
var truncated = current is not null;
|
||||
var ineligible = !truncated && frames.Any(frame => frame.Code == "TargetIneligible")
|
||||
&& frames.All(frame => frame.Code is "NoReadyEndpoint" or "TargetIneligible");
|
||||
var category = ineligible ? "TargetIneligible" : frames.Any(frame => frame.Code == "SecurityMaterialUnavailable")
|
||||
? "SecurityMaterialUnavailable" : frames.Any(frame => frame.Code == "TlsFailure") ? "TlsFailure"
|
||||
: frames.Any(frame => frame.Code == "TransportFailure") ? "TransportFailure"
|
||||
: frames.Any(frame => frame.Code == "RpcFailure") ? "RpcFailure" : "Other";
|
||||
return new(Enum.IsDefined(phase) ? phase.ToString() : "Other", category, truncated, frames);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
using System.Net;
|
||||
using System.Net.Security;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Authentication;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Text.Json;
|
||||
using Grpc.Core;
|
||||
using Grpc.Net.Client;
|
||||
using GrpcDataProbe;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
|
||||
|
||||
var failurePhase = ProbeFailurePhase.WireSetup;
|
||||
string? failureTarget = null;
|
||||
string? failureOutput = null;
|
||||
var results = new List<ProbeResult>();
|
||||
try
|
||||
{
|
||||
var arguments = args.Chunk(2).ToDictionary(pair => pair[0], pair => pair.Length == 2 ? pair[1] : throw new ArgumentException());
|
||||
failureOutput = arguments.GetValueOrDefault("--output");
|
||||
var manifestPath = Path.GetFullPath(arguments["--manifest"]);
|
||||
Restricted(manifestPath);
|
||||
using var manifest = JsonDocument.Parse(await File.ReadAllTextAsync(manifestPath));
|
||||
var root = manifest.RootElement;
|
||||
var scenario = arguments.GetValueOrDefault("--scenario", "all");
|
||||
if (scenario is not ("all" or "D13" or "wire")) throw new ArgumentException("Unsupported wire scenario.");
|
||||
var nodes = root.GetProperty("nodes");
|
||||
var endpoints = root.GetProperty("endpoints");
|
||||
var keyPath = root.GetProperty("credentials").GetProperty("data_key_files").GetProperty("source").GetString()!;
|
||||
Restricted(keyPath);
|
||||
var key = (await File.ReadAllTextAsync(keyPath)).Trim();
|
||||
var caPath = root.GetProperty("tls").GetProperty("ca_file").GetString()!;
|
||||
using var ca = X509Certificate2.CreateFromPem(File.ReadAllText(caPath));
|
||||
var sourceNodes = nodes.EnumerateObject().Where(item => item.Value.GetProperty("cluster_id").GetString() == "SOURCE").ToArray();
|
||||
if (sourceNodes.Length != 2) throw new InvalidOperationException();
|
||||
var routes = sourceNodes.ToDictionary(item => item.Name, item => endpoints.GetProperty(item.Name + ".data").GetProperty("host_port").GetInt32());
|
||||
foreach (var port in routes.Values) if (port is < 1 or > 65535) throw new InvalidOperationException();
|
||||
using var security = new ProbeSecurity(routes, ca, key);
|
||||
if (scenario is "all" or "D13")
|
||||
{
|
||||
foreach (var node in sourceNodes)
|
||||
{
|
||||
var name = node.Name;
|
||||
failureTarget = name is "source-1" or "source-2" ? name : null;
|
||||
var nodeId = node.Value.GetProperty("node_id").GetString()!;
|
||||
async Task Reject(string id, string credential, bool correctCa, bool correctName, bool useUi = false, bool plainData = false)
|
||||
{
|
||||
failurePhase = id switch
|
||||
{
|
||||
"bad-key" => ProbeFailurePhase.WireBadKey, "wrong-ca" => ProbeFailurePhase.WireWrongCa,
|
||||
"wrong-san" => ProbeFailurePhase.WireWrongSan, "wrong-listener" => ProbeFailurePhase.WireWrongListener,
|
||||
"h2c-data-listener" => ProbeFailurePhase.WireH2c, _ => ProbeFailurePhase.Other
|
||||
};
|
||||
using var handler = security.Handler(name, correctCa, correctName, useUi
|
||||
? endpoints.GetProperty(name + ".admin").GetProperty("host_port").GetInt32() : null);
|
||||
using var channel = GrpcChannel.ForAddress($"{(useUi || plainData ? "http" : "https")}://{name}:{(useUi ? 9000 : 4057)}", new() { HttpHandler = handler });
|
||||
var client = new W.DataConnectionService.DataConnectionServiceClient(channel);
|
||||
var headers = Headers(credential, "Node", nodeId);
|
||||
var denied = false;
|
||||
try { await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, headers, DateTime.UtcNow.AddSeconds(5)); }
|
||||
catch (RpcException error) when (error.StatusCode is StatusCode.Unauthenticated or StatusCode.PermissionDenied or StatusCode.Unavailable or StatusCode.Unimplemented or StatusCode.Internal) { denied = true; }
|
||||
results.Add(new(id + "-" + name, "wire-rejection", denied, 1, new() { ["target"] = nodeId, ["rejected"] = denied }));
|
||||
}
|
||||
// Each negative changes only one admission input after a positive TLS call.
|
||||
using (var handler = security.Handler(name))
|
||||
using (var channel = GrpcChannel.ForAddress($"https://{name}:4057", new() { HttpHandler = handler }))
|
||||
{
|
||||
failurePhase = ProbeFailurePhase.WirePositiveCapabilities;
|
||||
var client = new W.DataConnectionService.DataConnectionServiceClient(channel);
|
||||
var caps = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, Headers(key, "Node", nodeId), DateTime.UtcNow.AddSeconds(5));
|
||||
var valid = caps.ProtocolMajor == 1 && caps.ClusterId == "SOURCE" && caps.Serving.NodeId == nodeId;
|
||||
results.Add(new("positive-" + name, "wire-capabilities", valid, 3, new() { ["serving"] = caps.Serving.ToString() }));
|
||||
var incompatible = false;
|
||||
failurePhase = ProbeFailurePhase.WireProtocolMajor;
|
||||
try { await client.GetCapabilitiesAsync(new() { ProtocolMajor = 99 }, Headers(key, "Node", nodeId), DateTime.UtcNow.AddSeconds(5)); }
|
||||
catch (RpcException error) when (error.StatusCode == StatusCode.Unimplemented) { incompatible = true; }
|
||||
results.Add(new("protocol-major-" + name, "wire-negotiation", incompatible, 1, new() { ["rejectedIncompatibleMajor"] = incompatible }));
|
||||
if (arguments.TryGetValue("--previous-key-state", out var previousState))
|
||||
{
|
||||
failurePhase = ProbeFailurePhase.WirePreviousKey;
|
||||
if (previousState is not ("enabled" or "revoked")) throw new ArgumentException();
|
||||
var previousPath = Path.Combine(Path.GetDirectoryName(keyPath)!, "source-previous.key");
|
||||
Restricted(previousPath);
|
||||
var previousKey = (await File.ReadAllTextAsync(previousPath)).Trim();
|
||||
var accepted = false;
|
||||
var explicitlyDenied = false;
|
||||
try
|
||||
{
|
||||
var oldCaps = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, Headers(previousKey, "Node", nodeId), DateTime.UtcNow.AddSeconds(5));
|
||||
accepted = oldCaps.Serving.NodeId == nodeId;
|
||||
}
|
||||
catch (RpcException error) when (error.StatusCode is StatusCode.Unauthenticated or StatusCode.PermissionDenied) { explicitlyDenied = true; }
|
||||
results.Add(new("previous-key-" + name, "wire-credential-rotation", previousState == "enabled" ? accepted : explicitlyDenied, 1,
|
||||
new() { ["expectedState"] = previousState, ["accepted"] = accepted, ["explicitlyDenied"] = explicitlyDenied }));
|
||||
}
|
||||
}
|
||||
await Reject("bad-key", "invalid-presented-key", true, true);
|
||||
await Reject("wrong-ca", key, false, true);
|
||||
await Reject("wrong-san", key, true, false);
|
||||
await Reject("wrong-listener", key, true, true, useUi: true);
|
||||
await Reject("h2c-data-listener", key, true, true, plainData: true);
|
||||
if (root.GetProperty("tls").TryGetProperty("rotation", out var rotation) && rotation.GetString() == "retired")
|
||||
{
|
||||
failurePhase = ProbeFailurePhase.WireRetiredCa;
|
||||
using var oldCa = X509Certificate2.CreateFromPem(File.ReadAllText(Path.Combine(Path.GetDirectoryName(caPath)!, "ca-original.pem")));
|
||||
using var oldSecurity = new ProbeSecurity(routes, oldCa, key);
|
||||
using var handler = oldSecurity.Handler(name);
|
||||
using var channel = GrpcChannel.ForAddress($"https://{name}:4057", new() { HttpHandler = handler });
|
||||
var rejected = false;
|
||||
ProbeFailureEvidence? tlsRejection = null;
|
||||
try { await new W.DataConnectionService.DataConnectionServiceClient(channel).GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, Headers(key, "Node", nodeId), DateTime.UtcNow.AddSeconds(5)); }
|
||||
catch (RpcException error) when (ProbeFailureClassifier.IsRetiredCaTlsRejection(
|
||||
ProbeFailureClassifier.Capture(error, ProbeFailurePhase.WireRetiredCa)))
|
||||
{
|
||||
rejected = true;
|
||||
tlsRejection = ProbeFailureClassifier.Capture(error, ProbeFailurePhase.WireRetiredCa);
|
||||
}
|
||||
results.Add(new("retired-ca-" + name, "wire-trust-retirement", rejected, 1,
|
||||
new() { ["oldCaRejected"] = rejected, ["failureEvidence"] = tlsRejection }));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (scenario != "D13")
|
||||
{
|
||||
var fixture = root.GetProperty("fixture");
|
||||
var rawUri = fixture.GetProperty("namespace_uris").GetProperty("raw").GetString()!;
|
||||
var unsUri = fixture.GetProperty("namespace_uris").GetProperty("uns").GetString()!;
|
||||
foreach (var mode in new[] { DataTargetMode.Node, DataTargetMode.Cluster })
|
||||
{
|
||||
foreach (var source in mode == DataTargetMode.Node ? sourceNodes : sourceNodes.Take(1))
|
||||
{
|
||||
failurePhase = ProbeFailurePhase.WireOperation;
|
||||
failureTarget = source.Name is "source-1" or "source-2" ? source.Name : null;
|
||||
var target = new DataTarget(mode, "SOURCE", mode == DataTargetMode.Node ? source.Value.GetProperty("node_id").GetString() : null,
|
||||
mode == DataTargetMode.Node ? DataConsistency.ReadyReplica : DataConsistency.Primary);
|
||||
using var scope = new DataConnectionScopeLease(1, CancellationToken.None, () => { });
|
||||
await using var connection = new GrpcDataConnection("wire-probe", target,
|
||||
(mode == DataTargetMode.Node ? [source] : sourceNodes).Select(item => new Uri($"https://{item.Name}:4057")),
|
||||
security, scope, 1024 * 1024, 2, eligibleNodeIds: sourceNodes.Select(item => item.Value.GetProperty("node_id").GetString()!).ToHashSet());
|
||||
foreach (var realm in new[] { "raw", "uns" })
|
||||
{
|
||||
var path = fixture.GetProperty("origin_paths").GetProperty(realm).GetString()!;
|
||||
foreach (var operation in new[] { "capabilities", "metadata", "read", "browse" })
|
||||
{
|
||||
var command = new ProbeCommand($"{mode}-{source.Name}-{realm}-{operation}", "wire-probe", operation,
|
||||
realm, "SOURCE", realm == "raw" ? rawUri : unsUri,
|
||||
operation == "browse" ? fixture.GetProperty("browse_roots").GetProperty(realm).GetString()! : path,
|
||||
ExpectedNodeId: mode == DataTargetMode.Node ? source.Value.GetProperty("node_id").GetString() : null);
|
||||
results.Add(await ProbeEngine.RunAsync(connection, command, CancellationToken.None));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var output = JsonSerializer.Serialize(new { schemaVersion = 1, scenario, passed = results.Count > 0 && results.All(result => result.Passed && result.Assertions > 0), results }, ProbeEngine.Json);
|
||||
if (arguments.TryGetValue("--output", out var outputPath))
|
||||
{
|
||||
await File.WriteAllTextAsync(outputPath, output);
|
||||
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(outputPath, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
}
|
||||
Console.WriteLine(output);
|
||||
return results.Count > 0 && results.All(result => result.Passed && result.Assertions > 0) ? 0 : 1;
|
||||
}
|
||||
catch (Exception error) when (error is not OutOfMemoryException)
|
||||
{
|
||||
var failure = ProbeFailureClassifier.Capture(error, failurePhase);
|
||||
var output = JsonSerializer.Serialize(new { passed = false, failure = failure.Category,
|
||||
failurePhase = failure.Phase, targetNode = failureTarget, failureEvidence = failure,
|
||||
results = results.Take(128).ToArray(), partialResultsTruncated = results.Count > 128 }, ProbeEngine.Json);
|
||||
if (failureOutput is not null && Path.IsPathFullyQualified(failureOutput))
|
||||
{
|
||||
try
|
||||
{
|
||||
if (new FileInfo(failureOutput).LinkTarget is null)
|
||||
{
|
||||
await File.WriteAllTextAsync(failureOutput, output);
|
||||
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(failureOutput, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
}
|
||||
}
|
||||
catch (Exception) { /* Preserve the original wire failure and exit status. */ }
|
||||
}
|
||||
Console.Error.WriteLine(output);
|
||||
return 2;
|
||||
}
|
||||
|
||||
static void Restricted(string path)
|
||||
{
|
||||
var file = new FileInfo(path);
|
||||
if (!file.Exists || file.LinkTarget is not null || !Path.IsPathFullyQualified(path) || file.Length > 1024 * 1024) throw new InvalidOperationException();
|
||||
if (!OperatingSystem.IsWindows() && (File.GetUnixFileMode(path) & (UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherWrite | UnixFileMode.OtherExecute)) != 0)
|
||||
throw new InvalidOperationException();
|
||||
}
|
||||
|
||||
static Metadata Headers(string key, string mode, string nodeId) => new()
|
||||
{
|
||||
{ "authorization", "Bearer " + key }, { "x-data-target-mode", mode }, { "x-data-cluster-id", "SOURCE" },
|
||||
{ "x-data-node-id", nodeId }, { "x-data-consistency", "ReadyReplica" }
|
||||
};
|
||||
|
||||
sealed class ProbeSecurity(Dictionary<string, int> routes, X509Certificate2 root, string key) : IDataConnectionSecurityProvider, IDisposable
|
||||
{
|
||||
private readonly X509Certificate2 _untrustedRoot = UntrustedRoot();
|
||||
private static X509Certificate2 UntrustedRoot()
|
||||
{
|
||||
using var signingKey = ECDsa.Create(ECCurve.NamedCurves.nistP256);
|
||||
var request = new CertificateRequest("CN=unrelated-grpc-data-probe-ca", signingKey, HashAlgorithmName.SHA256);
|
||||
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
|
||||
return request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-1), DateTimeOffset.UtcNow.AddHours(1));
|
||||
}
|
||||
public void Dispose() => _untrustedRoot.Dispose();
|
||||
public event Action<string>? Changed { add { } remove { } }
|
||||
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
|
||||
ValueTask.FromResult<DataConnectionSecurity?>(new("fixture-key-v1", Convert.ToHexString(SHA256.HashData(root.RawData)), key,
|
||||
() => Handler(endpoint.Host)));
|
||||
|
||||
public HttpMessageHandler Handler(string host, bool correctCa = true, bool correctName = true, int? overridePort = null)
|
||||
{
|
||||
if (!routes.TryGetValue(host, out var port)) throw new InvalidOperationException();
|
||||
return new SocketsHttpHandler
|
||||
{
|
||||
UseProxy = false,
|
||||
ConnectTimeout = TimeSpan.FromSeconds(5),
|
||||
ConnectCallback = async (_, token) =>
|
||||
{
|
||||
var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
||||
try { await socket.ConnectAsync(IPAddress.Loopback, overridePort ?? port, token); return new NetworkStream(socket, ownsSocket: true); }
|
||||
catch { socket.Dispose(); throw; }
|
||||
},
|
||||
SslOptions = new SslClientAuthenticationOptions
|
||||
{
|
||||
EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13,
|
||||
RemoteCertificateValidationCallback = (_, certificate, _, _) =>
|
||||
{
|
||||
if (certificate is null) return false;
|
||||
using var leaf = X509CertificateLoader.LoadCertificate(certificate.GetRawCertData());
|
||||
if (!leaf.MatchesHostname(correctName ? host : "wrong-san.grpc-data.invalid", allowWildcards: false, allowCommonName: false)) return false;
|
||||
using var chain = new X509Chain();
|
||||
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
|
||||
chain.ChainPolicy.CustomTrustStore.Add(correctCa ? root : _untrustedRoot);
|
||||
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
|
||||
chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.1"));
|
||||
return chain.Build(leaf);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
using System.Diagnostics;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace GrpcDataProbe;
|
||||
|
||||
// Limits apply to the experiment itself, independently of production admission.
|
||||
public sealed record WorkloadSource(string Id, string RawPath, string UnsPath, string ExpectedKind = "UInt16", int ExpectedRank = -1, bool RequireChanges = false);
|
||||
public sealed record WorkloadOptions(string ProfileId, IReadOnlyList<WorkloadSource> Sources,
|
||||
int Clients = 1, int RegistrationsPerClient = 1, int ViewsPerSource = 1, int DurationSeconds = 8,
|
||||
int SamplingMilliseconds = 100, int PublishingMilliseconds = 100, double? Deadband = null,
|
||||
int SlowClientCount = 0, int SlowClientMilliseconds = 0, int BrowseBurst = 0, int BrowseWorkers = 1,
|
||||
bool Overlap = true, bool RequireAllAdmitted = true, int HubPartitions = 4, bool CompactBatches = true);
|
||||
|
||||
/// <summary>Measures real facade streams; it never synthesizes sources or values.</summary>
|
||||
public static class WorkloadEngine
|
||||
{
|
||||
public static async Task<ProbeResult> RunAsync(IDataConnection connection, ProbeCommand command, CancellationToken stop, Func<object>? captureDiagnostics = null)
|
||||
{
|
||||
var observations = new Dictionary<string, object?>();
|
||||
var assertions = 0;
|
||||
var phase = "configuration";
|
||||
void Check(bool condition, string name)
|
||||
{
|
||||
if (!condition)
|
||||
{
|
||||
observations["failedCheck"] = name;
|
||||
throw new InvalidOperationException(name);
|
||||
}
|
||||
assertions++;
|
||||
}
|
||||
try
|
||||
{
|
||||
var options = command.Workload ?? throw new InvalidOperationException("missing workload");
|
||||
Check(options.ProfileId.Length is > 0 and <= 64 && options.Sources.Count is > 0 and <= 64
|
||||
&& options.Sources.Select(source => source.Id).Distinct().Count() == options.Sources.Count, "bounded sources");
|
||||
Check(options.Clients is > 0 and <= 64 && options.RegistrationsPerClient is > 0 and <= 256
|
||||
&& options.Clients * options.RegistrationsPerClient <= 4096 && options.ViewsPerSource is 1 or 2
|
||||
&& options.DurationSeconds is >= 2 and <= 90 && command.TimeoutSeconds >= options.DurationSeconds + 10
|
||||
&& options.SamplingMilliseconds is >= 0 and <= 10000 && options.PublishingMilliseconds is >= 0 and <= 10000
|
||||
&& options.SlowClientCount >= 0 && options.SlowClientCount <= options.Clients
|
||||
&& options.SlowClientMilliseconds is >= 0 and <= 5000 && options.BrowseBurst is >= 0 and <= 1024
|
||||
&& options.BrowseWorkers is > 0 and <= 32 && options.HubPartitions is > 0 and <= 16
|
||||
&& options.RegistrationsPerClient * (options.Overlap ? 1 : options.Clients) >= options.Sources.Count * options.ViewsPerSource
|
||||
&& (options.Overlap || options.Clients * options.RegistrationsPerClient <= options.Sources.Count * options.ViewsPerSource), "bounded experiment");
|
||||
var budget = new DataBudget(TimeSpan.FromSeconds(5), 256, 1024 * 1024);
|
||||
phase = "capabilities";
|
||||
var capabilities = await connection.GetCapabilitiesAsync(budget, stop);
|
||||
Check(capabilities.Readiness == DataReadiness.Ready, "ready workload target");
|
||||
Check(!options.CompactBatches || capabilities.CompactBatches, "requested compact codec is supported");
|
||||
var views = new List<(WorkloadSource Source, DataView View)>();
|
||||
foreach (var source in options.Sources)
|
||||
{
|
||||
views.Add((source, new(new(command.OriginCluster, command.NamespaceUri, "string", source.RawPath), DataRealm.Raw, null, 0, source.RawPath)));
|
||||
if (options.ViewsPerSource == 2)
|
||||
{
|
||||
// UNS URI is a public fixture value passed explicitly, never inferred from an index.
|
||||
var unsUri = command.WorkloadUnsNamespaceUri ?? throw new InvalidOperationException("UNS namespace required");
|
||||
views.Add((source, new(new(command.OriginCluster, unsUri, "string", source.UnsPath), DataRealm.Uns, null, 0, source.UnsPath)));
|
||||
}
|
||||
}
|
||||
phase = "metadata";
|
||||
foreach (var chunk in views.Chunk(256))
|
||||
{
|
||||
var metadata = await connection.GetMetadataAsync(new(chunk.Select(item => item.View).ToArray(), budget), stop);
|
||||
Check(metadata.Count == chunk.Length, "metadata cardinality");
|
||||
for (var i = 0; i < chunk.Length; i++)
|
||||
Check(metadata[i].Status == DataItemStatus.Good && metadata[i].Value is { } value
|
||||
&& value.ValueKind.ToString() == chunk[i].Source.ExpectedKind && value.ValueRank == chunk[i].Source.ExpectedRank,
|
||||
"observed payload kind and rank");
|
||||
}
|
||||
phase = "browse-parent";
|
||||
var browseViews = new List<DataView>();
|
||||
if (options.BrowseBurst > 0)
|
||||
foreach (var leaf in views.Select(item => item.View).DistinctBy(view => view.Realm))
|
||||
{
|
||||
var realm = leaf.Realm.ToString().ToLowerInvariant();
|
||||
if (command.WorkloadBrowseRoots is null || !command.WorkloadBrowseRoots.TryGetValue(realm, out var root)
|
||||
|| string.IsNullOrWhiteSpace(root)) throw new InvalidOperationException("Explicit workload browse container required.");
|
||||
var requested = leaf with { Address = leaf.Address with { Identifier = root }, Subject = root };
|
||||
browseViews.Add(await ProbeEngine.CanonicalBrowseViewAsync(connection, requested, budget, stop));
|
||||
}
|
||||
phase = "measurement";
|
||||
observations["profile"] = options;
|
||||
observations["serving"] = capabilities.Serving;
|
||||
observations["capabilities"] = new { capabilities.CompactBatches, capabilities.Limits };
|
||||
observations["processBefore"] = CaptureProcess();
|
||||
observations["diagnosticsBefore"] = captureDiagnostics?.Invoke();
|
||||
var watch = Stopwatch.StartNew();
|
||||
using var measurement = new CancellationTokenSource(TimeSpan.FromSeconds(options.DurationSeconds));
|
||||
using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(stop, measurement.Token);
|
||||
bool MeasurementEnded() => measurement.IsCancellationRequested && !stop.IsCancellationRequested;
|
||||
var clients = Enumerable.Range(0, options.Clients).Select(index => RunClient(index)).ToArray();
|
||||
var browse = RunBrowse();
|
||||
var samples = new List<object>();
|
||||
while (!lifetime.IsCancellationRequested)
|
||||
{
|
||||
samples.Add(new { process = CaptureProcess(), diagnostics = captureDiagnostics?.Invoke() });
|
||||
try { await Task.Delay(500, lifetime.Token); } catch (OperationCanceledException) when (lifetime.IsCancellationRequested) { }
|
||||
}
|
||||
var results = await Task.WhenAll(clients);
|
||||
observations["clients"] = results;
|
||||
phase = "browse-completion";
|
||||
var browseResult = await browse;
|
||||
phase = "reconciliation";
|
||||
watch.Stop();
|
||||
observations["elapsedSeconds"] = watch.Elapsed.TotalSeconds;
|
||||
observations["browse"] = browseResult;
|
||||
observations["processSamples"] = samples;
|
||||
observations["processAfter"] = CaptureProcess();
|
||||
observations["diagnosticsAfter"] = captureDiagnostics?.Invoke();
|
||||
observations["bytesDefinition"] = "serialized typed-value protobuf bytes only; excludes frame, HTTP/2 and TLS overhead";
|
||||
observations["schedulingDefinition"] = "monotonic client inter-delivery gaps and first-snapshot latency; source age is reported separately";
|
||||
Check(results.All(result => result.Failure is null), "all workload tasks completed");
|
||||
Check(results.All(result => result.UnreadySamples == 0), "steady workload retains source readiness");
|
||||
if (options.RequireAllAdmitted)
|
||||
{
|
||||
Check(results.Sum(result => result.Acknowledged) == options.Clients * options.RegistrationsPerClient, "actual acknowledged registrations");
|
||||
Check(results.All(result => result.Snapshots == result.Acknowledged && result.Acknowledged > 0
|
||||
&& result.Controls.GetValueOrDefault("SnapshotEnd") > 0), "every registration initialized in a completed snapshot");
|
||||
Check(results.All(result => result.RequiredChangingItems.All(item => item.Changes > 0)), "hot registrations progress");
|
||||
Check(results.Where(result => result.Client >= options.SlowClientCount).All(result => result.RequiredChangingItems.All(item =>
|
||||
item.ChangesAfterMidpoint > 0 && item.HotTailMilliseconds <= budget.Timeout.TotalMilliseconds)), "healthy registrations progress through final half within snapshot budget");
|
||||
}
|
||||
else
|
||||
{
|
||||
Check(results.Any(result => result.RejectedBeforeStream), "independent bounded stream admission rejection observed");
|
||||
Check(results.Any(result => result.Acknowledged > 0 && result.Snapshots == result.Acknowledged), "admitted peers retain initialized service");
|
||||
}
|
||||
Check(browseResult.Completed == options.BrowseBurst, "concurrent browse completion");
|
||||
return new(command.Id, command.Operation, true, assertions, observations);
|
||||
|
||||
async Task<ClientResult> RunClient(int client)
|
||||
{
|
||||
var result = new ClientResult(client);
|
||||
var items = new Dictionary<string, ItemResult>(StringComparer.Ordinal);
|
||||
var handles = new Dictionary<ulong, ItemResult>();
|
||||
var id = command.Id + "-c" + client;
|
||||
var timer = Stopwatch.StartNew();
|
||||
long sequence = 0;
|
||||
var snapshotOpen = false;
|
||||
var clientPhase = "subscribe";
|
||||
try
|
||||
{
|
||||
await using var stream = await connection.SubscribeAsync(lifetime.Token);
|
||||
var definitions = Enumerable.Range(0, options.RegistrationsPerClient).Select(index =>
|
||||
{
|
||||
var selected = views[(options.Overlap ? index : client * options.RegistrationsPerClient + index) % views.Count];
|
||||
var key = "r" + index;
|
||||
items.Add(key, new(key, selected.Source.Id, selected.View.Realm.ToString(), selected.Source.RequireChanges));
|
||||
return new DataSubscriptionItem(key, selected.View, new(TimeSpan.FromMilliseconds(options.SamplingMilliseconds),
|
||||
TimeSpan.FromMilliseconds(options.PublishingMilliseconds), DataChangeTrigger.StatusValue, options.Deadband));
|
||||
}).ToArray();
|
||||
clientPhase = "open";
|
||||
await stream.SendAsync(new OpenSubscription(id, 1, "open", TimeSpan.FromSeconds(5), definitions, false,
|
||||
TimeSpan.FromSeconds(options.DurationSeconds + 5), budget), lifetime.Token);
|
||||
clientPhase = "receive";
|
||||
await foreach (var frame in stream.ReadAllAsync(lifetime.Token))
|
||||
{
|
||||
clientPhase = "frame";
|
||||
result.LastFrame = new(frame.Sequence, frame.StreamEpoch, frame.GetType().Name,
|
||||
frame is DataSubscriptionControl marker ? marker.Kind.ToString() : null,
|
||||
frame is DataSubscriptionValues batch ? batch.Items.Count : null);
|
||||
if (frame.SubscriptionId != id || frame.StreamEpoch != 1 || frame.Sequence <= sequence)
|
||||
throw new InvalidOperationException("stream order");
|
||||
sequence = frame.Sequence;
|
||||
if (frame is DataSubscriptionAck ack)
|
||||
{
|
||||
if (ack.CommandId != "open" || ack.Items.Count != definitions.Length) throw new InvalidOperationException("ack cardinality");
|
||||
foreach (var entry in ack.Items)
|
||||
{
|
||||
if (!items.TryGetValue(entry.ClientItemId, out var item)) throw new InvalidOperationException("unknown ack item");
|
||||
if (entry.Status == DataItemStatus.Good && entry.Handle is { } handle)
|
||||
{ handles.Add(handle.Handle, item); item.HandleRevision = handle.ItemRevision; result.Acknowledged++; }
|
||||
else { result.Rejected++; result.RejectionStatuses.Add(entry.Status.ToString()); }
|
||||
}
|
||||
}
|
||||
else if (frame is DataSubscriptionControl control)
|
||||
{
|
||||
result.Controls[control.Kind.ToString()] = result.Controls.GetValueOrDefault(control.Kind.ToString()) + 1;
|
||||
if (control.Kind == DataStreamControlKind.Reset) foreach (var item in items.Values) item.Initialized = false;
|
||||
if (control.Kind == DataStreamControlKind.SnapshotBegin)
|
||||
{ if (snapshotOpen) throw new InvalidOperationException("nested snapshot"); snapshotOpen = true; }
|
||||
if (control.Kind == DataStreamControlKind.SnapshotEnd)
|
||||
{ if (!snapshotOpen || handles.Values.Any(item => !item.Initialized)) throw new InvalidOperationException("incomplete snapshot"); snapshotOpen = false; }
|
||||
}
|
||||
else if (frame is DataSubscriptionValues update)
|
||||
{
|
||||
using (update)
|
||||
{
|
||||
foreach (var entry in update.Items)
|
||||
{
|
||||
if (!handles.TryGetValue(entry.Handle.Handle, out var item) || entry.Handle.ItemRevision != item.HandleRevision)
|
||||
throw new InvalidOperationException("unacknowledged revision");
|
||||
if (entry.Readiness != DataReadiness.Ready || entry.Sample.StatusCode != 0)
|
||||
{ result.UnreadySamples++; continue; }
|
||||
if (!item.Initialized && !update.IsSnapshot) throw new InvalidOperationException("delta before snapshot");
|
||||
if (update.IsSnapshot && !snapshotOpen) throw new InvalidOperationException("unbracketed snapshot");
|
||||
var elapsed = timer.Elapsed.TotalMilliseconds;
|
||||
if (update.IsSnapshot && !item.Initialized)
|
||||
{ item.Initialized = true; if (item.FirstSnapshotMilliseconds is null) { item.FirstSnapshotMilliseconds = elapsed; result.Snapshots++; } }
|
||||
var encoded = TypedValueCodec.Encode(entry.Sample.Value);
|
||||
var fingerprint = encoded.ToString();
|
||||
if (item.LastFingerprint is { } previous && previous != fingerprint)
|
||||
{ item.Changes++; if (elapsed >= options.DurationSeconds * 500) item.ChangesAfterMidpoint++; }
|
||||
item.LastFingerprint = fingerprint;
|
||||
if (item.LastDeliveryMilliseconds is { } last) item.DeliveryGaps.Observe(elapsed - last);
|
||||
item.LastDeliveryMilliseconds = elapsed;
|
||||
if (entry.AgeBounds.Upper is { } age) item.SourceAge.Observe(age.TotalMilliseconds);
|
||||
item.Samples++; item.TypedValueBytes += encoded.CalculateSize();
|
||||
}
|
||||
}
|
||||
if (client < options.SlowClientCount && options.SlowClientMilliseconds > 0)
|
||||
await Task.Delay(options.SlowClientMilliseconds, lifetime.Token);
|
||||
}
|
||||
clientPhase = "receive";
|
||||
}
|
||||
clientPhase = "end";
|
||||
if (!MeasurementEnded()) throw new InvalidOperationException("Stream ended before the scheduled measurement deadline.");
|
||||
}
|
||||
catch (OperationCanceledException) when (MeasurementEnded()) { }
|
||||
catch (Grpc.Core.RpcException error) when (error.StatusCode == Grpc.Core.StatusCode.Cancelled && MeasurementEnded()) { }
|
||||
catch (InvalidOperationException error) when (!options.RequireAllAdmitted && error.Message == "Stream capacity exhausted.")
|
||||
{ result.RejectedBeforeStream = true; }
|
||||
catch (Exception error) when (error is not OutOfMemoryException)
|
||||
{
|
||||
result.Failure = FailureCode(error);
|
||||
result.FailurePhase = clientPhase;
|
||||
result.FailureMilliseconds = timer.Elapsed.TotalMilliseconds;
|
||||
}
|
||||
foreach (var item in items.Values)
|
||||
item.HotTailMilliseconds = item.LastDeliveryMilliseconds is { } last ? timer.Elapsed.TotalMilliseconds - last : timer.Elapsed.TotalMilliseconds;
|
||||
result.Items = items.Values.ToArray();
|
||||
return result;
|
||||
}
|
||||
async Task<BrowseResult> RunBrowse()
|
||||
{
|
||||
var completed = 0;
|
||||
var latency = new BoundedHistogram();
|
||||
using var slots = new SemaphoreSlim(options.BrowseWorkers);
|
||||
await Task.WhenAll(Enumerable.Range(0, options.BrowseBurst).Select(async index =>
|
||||
{
|
||||
await slots.WaitAsync(stop);
|
||||
try
|
||||
{
|
||||
var timer = Stopwatch.StartNew();
|
||||
var view = browseViews[index % browseViews.Count];
|
||||
var branch = await connection.BrowseAsync(new(view, null, null, budget), stop);
|
||||
if (branch.Status != DataItemStatus.Good) throw new BrowseResponseFailure(branch.Status, view.Realm);
|
||||
lock (latency) { latency.Observe(timer.Elapsed.TotalMilliseconds); completed++; }
|
||||
}
|
||||
finally { slots.Release(); }
|
||||
}));
|
||||
return new(completed, latency);
|
||||
}
|
||||
}
|
||||
catch (Exception error) when (error is not OutOfMemoryException)
|
||||
{
|
||||
observations["failurePhase"] = phase;
|
||||
if (error is BrowseResponseFailure browse)
|
||||
observations["browseFailure"] = new { status = browse.Status.ToString(), realm = browse.Realm.ToString() };
|
||||
return new(command.Id, command.Operation, false, assertions, observations, FailureCode(error));
|
||||
}
|
||||
}
|
||||
|
||||
// Emit only fixed local reasons and the enum transport status.
|
||||
private static string FailureCode(Exception error) => error switch
|
||||
{
|
||||
Grpc.Core.RpcException rpc => "rpc:" + rpc.StatusCode,
|
||||
BrowseResponseFailure => "workload-browse-status",
|
||||
InvalidOperationException invalid => invalid.Message switch
|
||||
{
|
||||
"Stream ended before the scheduled measurement deadline." => "early-stream-end",
|
||||
"Unexpected stream epoch or sequence." => "remote-order",
|
||||
"Response serving identity changed." => "serving-identity",
|
||||
"Duplicate handle or sample version regression." => "remote-version-or-handle",
|
||||
"Canonical browse parent metadata unavailable." => "browse-parent-metadata",
|
||||
"No ready authenticated data endpoint." => "no-ready-endpoint",
|
||||
"No ready subscription endpoint." => "no-ready-subscription-endpoint",
|
||||
"Data endpoint discovery is backing off." => "endpoint-backoff",
|
||||
"Unknown acknowledgement." => "remote-ack",
|
||||
"Acknowledgement expired." => "remote-ack-expired",
|
||||
"stream order" => "workload-order",
|
||||
"ack cardinality" => "workload-ack-cardinality",
|
||||
"unknown ack item" => "workload-ack-item",
|
||||
"nested snapshot" => "workload-nested-snapshot",
|
||||
"incomplete snapshot" => "workload-incomplete-snapshot",
|
||||
"unacknowledged revision" => "workload-handle",
|
||||
"delta before snapshot" => "workload-delta-before-snapshot",
|
||||
"unbracketed snapshot" => "workload-unbracketed-snapshot",
|
||||
_ => nameof(InvalidOperationException)
|
||||
},
|
||||
_ => error.GetType().Name
|
||||
};
|
||||
|
||||
private sealed class BrowseResponseFailure(DataItemStatus status, DataRealm realm) : Exception
|
||||
{
|
||||
internal DataItemStatus Status { get; } = status;
|
||||
internal DataRealm Realm { get; } = realm;
|
||||
}
|
||||
|
||||
public static object CaptureProcess()
|
||||
{
|
||||
using var process = Process.GetCurrentProcess();
|
||||
var gc = GC.GetGCMemoryInfo();
|
||||
return new { atUtc = DateTimeOffset.UtcNow, processId = Environment.ProcessId, process.WorkingSet64, process.PrivateMemorySize64,
|
||||
totalProcessorMilliseconds = process.TotalProcessorTime.TotalMilliseconds, managedBytes = GC.GetTotalMemory(false),
|
||||
gc.HeapSizeBytes, gc.FragmentedBytes, gc.TotalCommittedBytes, gc.MemoryLoadBytes,
|
||||
collections = new[] { GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2) }, threadCount = process.Threads.Count };
|
||||
}
|
||||
public sealed class ClientResult(int client)
|
||||
{
|
||||
public int Client { get; } = client;
|
||||
public int Acknowledged { get; set; }
|
||||
public int Rejected { get; set; }
|
||||
public bool RejectedBeforeStream { get; set; }
|
||||
public int Snapshots { get; set; }
|
||||
public long UnreadySamples { get; set; }
|
||||
public HashSet<string> RejectionStatuses { get; } = new();
|
||||
public Dictionary<string, int> Controls { get; } = new();
|
||||
public IReadOnlyList<ItemResult> Items { get; set; } = [];
|
||||
public IEnumerable<ItemResult> RequiredChangingItems => Items.Where(item => item.RequireChanges);
|
||||
public string? Failure { get; set; }
|
||||
public string? FailurePhase { get; set; }
|
||||
public double? FailureMilliseconds { get; set; }
|
||||
public FrameReceipt? LastFrame { get; set; }
|
||||
}
|
||||
|
||||
public sealed record FrameReceipt(long Sequence, long Epoch, string Kind, string? Control, int? Items);
|
||||
|
||||
public sealed class ItemResult(string id, string sourceId, string realm, bool requireChanges)
|
||||
{
|
||||
public string Id { get; } = id;
|
||||
public string SourceId { get; } = sourceId;
|
||||
public string Realm { get; } = realm;
|
||||
public bool RequireChanges { get; } = requireChanges;
|
||||
public long HandleRevision { get; set; }
|
||||
public bool Initialized { get; set; }
|
||||
public long Samples { get; set; }
|
||||
public long Changes { get; set; }
|
||||
public long ChangesAfterMidpoint { get; set; }
|
||||
public double HotTailMilliseconds { get; set; }
|
||||
public long TypedValueBytes { get; set; }
|
||||
public double? FirstSnapshotMilliseconds { get; set; }
|
||||
public BoundedHistogram DeliveryGaps { get; } = new();
|
||||
public BoundedHistogram SourceAge { get; } = new();
|
||||
[System.Text.Json.Serialization.JsonIgnore] public string? LastFingerprint { get; set; }
|
||||
[System.Text.Json.Serialization.JsonIgnore] public double? LastDeliveryMilliseconds { get; set; }
|
||||
}
|
||||
public sealed record BrowseResult(int Completed, BoundedHistogram Latency);
|
||||
// Fixed logarithmic buckets bound memory regardless of delivery rate.
|
||||
public sealed class BoundedHistogram
|
||||
{
|
||||
private readonly long[] _buckets = new long[256];
|
||||
public long Count { get; private set; }
|
||||
public double Maximum { get; private set; }
|
||||
public double? P95 => Quantile(.95);
|
||||
public double? P99 => Quantile(.99);
|
||||
public void Observe(double value)
|
||||
{ if (!double.IsFinite(value) || value < 0) throw new ArgumentOutOfRangeException(nameof(value)); _buckets[Math.Min(255, (int)(Math.Log2(value + 1) * 16))]++; Count++; Maximum = Math.Max(Maximum, value); }
|
||||
private double? Quantile(double fraction)
|
||||
{ if (Count == 0) return null; var target = (long)Math.Ceiling(Count * fraction); long seen = 0; for (var i = 0; i < _buckets.Length; i++) { seen += _buckets[i]; if (seen >= target) return Math.Min(Maximum, Math.Pow(2, (i + 1) / 16d) - 1); } return Maximum; }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user