Files
lmxopcua/scripts/validation/grpc-data/probe/ProbeEngine.cs
T

375 lines
25 KiB
C#

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,
DateTimeOffset? HistoryStartUtc = null, DateTimeOffset? HistoryEndUtc = null, uint HistoryNumValues = 5);
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 if (command.Operation == "history")
{
// H2 smoke: a Raw HistoryRead through whatever IDataConnection the caller holds (the deployed lease on a
// consumer node, or a probe-built GrpcDataConnection). ExpectedState: Good (default) | Unsupported.
phase = ProbeFailurePhase.Read;
Check(connection is IDataHistoryService, "connection serves history");
var history = (IDataHistoryService)connection;
observations["historyCapabilities"] = caps.History;
observations["historyReadAdvertised"] = caps.Operations.HasFlag(DataOperations.HistoryRead);
var details = new DataHistoryRawDetails(command.HistoryStartUtc, command.HistoryEndUtc ?? DateTimeOffset.UtcNow,
command.HistoryNumValues, false);
var historyBudget = budget with { MaxBytes = 4 * 1024 * 1024 };
static object Page(DataHistoryReadResult result) => new
{
statusCode = "0x" + result.StatusCode.ToString("X8"), result.Diagnostic, hasContinuation = result.Continuation is not null,
samples = result.Samples.Select(sample => new
{
value = ZB.MOM.WW.OtOpcUa.Commons.DataConnections.TypedValueCodec.Encode(sample.Value).ToString(),
statusCode = "0x" + sample.StatusCode.ToString("X8"), sourceTimestampUtc = sample.SourceTimestampUtc?.ToString("O"),
serverTimestampUtc = sample.ServerTimestampUtc?.ToString("O"),
}).ToArray(),
};
var pages = new List<object>();
observations["pages"] = pages;
var first = await history.ReadAsync(new(details, [new("one", view)], historyBudget), ct);
try
{
Check(first.Count == 1 && first[0].CorrelationId == "one", "history cardinality");
pages.Add(Page(first[0]));
if (command.ExpectedState == "Unsupported")
{
Check(first[0].StatusCode == 0x80720000u && first[0].Samples.Count == 0 && first[0].Continuation is null, "history unsupported");
}
else
{
Check(first[0].StatusCode >> 30 == 0, "history status Good");
Check(first[0].Samples.Count > 0 && (command.HistoryNumValues == 0 || first[0].Samples.Count <= command.HistoryNumValues), "history page bound");
if (command.HistoryStartUtc is null)
Check(first[0].Samples.Zip(first[0].Samples.Skip(1)).All(pair => pair.First.SourceTimestampUtc > pair.Second.SourceTimestampUtc), "end-only read newest first");
if (first[0].Continuation is { } token)
{
var second = await history.ReadAsync(new(details, [new("one", view, null, token)], historyBudget), ct);
try
{
Check(second.Count == 1, "resumed cardinality");
pages.Add(Page(second[0]));
Check(second[0].StatusCode >> 30 == 0 && second[0].Samples.Count > 0, "resumed page Good");
if (command.HistoryStartUtc is null)
Check(second[0].Samples[0].SourceTimestampUtc < first[0].Samples[^1].SourceTimestampUtc, "resumed page continues older");
if (second[0].Continuation is { } rest) await history.ReleaseAsync([rest], ct);
}
finally { foreach (var item in second) item.Dispose(); }
}
}
}
finally { foreach (var item in first) item.Dispose(); }
}
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")
});
}