fix(analyzers): #1001 OTOPCUA0001 now guards IAcknowledgedAcquisitionSource and IWriteOutcomeCapability

An unwrapped SubscribeAcquisitionAsync / WriteWithOutcomesAsync call now fails the build.
Full-solution build flags exactly one production site (DriverInstanceActor acquisition start),
suppressed inline with the reason the stock retrying/timeout pipeline cannot own that call,
and one wire-level Runtime test call.
This commit is contained in:
Joseph Doherty
2026-12-03 10:40:04 -05:00
parent b9955f6946
commit 2f6f41441a
6 changed files with 130 additions and 3 deletions
+1 -1
View File
@@ -27,7 +27,7 @@ The lifecycle facade `OpcUaApplicationHost` (`src/Server/ZB.MOM.WW.OtOpcUa.OpcUa
## Resilience and capability dispatch
Driver-capability calls (`IReadable.ReadAsync`, `IWritable.WriteAsync`, `ITagDiscovery.DiscoverAsync`, `ISubscribable.SubscribeAsync/UnsubscribeAsync`, the `IHostConnectivityProbe` probe loop, `IAlarmSource` surfaces) are routed through a `CapabilityInvoker` (`src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/CapabilityInvoker.cs`) so the Polly resilience pipeline (retry / timeout / breaker) applies. There is one invoker per `(DriverInstance, IDriver)` pair; all invokers share the process-singleton `DriverResiliencePipelineBuilder`, which keys pipelines on `(DriverInstanceId, hostName, DriverCapability)`. Per-instance resilience options come from the driver's tier — the `DriverTier` passed at factory registration, resolved via `DriverFactoryRegistry.GetTier` (every driver is Tier A today, since no factory passes one) — plus per-instance JSON overrides parsed from `DriverInstance.ResilienceConfig` by `DriverResilienceOptionsParser`. (It was never `DriverTypeRegistry`; that class was vestigial and was deleted in Gitea #522.)
Driver-capability calls (`IReadable.ReadAsync`, `IWritable.WriteAsync`, `ITagDiscovery.DiscoverAsync`, `ISubscribable.SubscribeAsync/UnsubscribeAsync`, the `IHostConnectivityProbe` probe loop, `IAlarmSource` surfaces, `IWriteOutcomeCapability.WriteWithOutcomesAsync`) are routed through a `CapabilityInvoker` (`src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/CapabilityInvoker.cs`) so the Polly resilience pipeline (retry / timeout / breaker) applies. There is one invoker per `(DriverInstance, IDriver)` pair; all invokers share the process-singleton `DriverResiliencePipelineBuilder`, which keys pipelines on `(DriverInstanceId, hostName, DriverCapability)`. Per-instance resilience options come from the driver's tier — the `DriverTier` passed at factory registration, resolved via `DriverFactoryRegistry.GetTier` (every driver is Tier A today, since no factory passes one) — plus per-instance JSON overrides parsed from `DriverInstance.ResilienceConfig` by `DriverResilienceOptionsParser`. (It was never `DriverTypeRegistry`; that class was vestigial and was deleted in Gitea #522.)
The `OTOPCUA0001` Roslyn analyzer (`src/Tooling/ZB.MOM.WW.OtOpcUa.Analyzers/UnwrappedCapabilityCallAnalyzer.cs`, category `OtOpcUa.Resilience`, severity Warning) flags direct driver-capability calls that bypass the invoker.
+1 -1
View File
@@ -1951,7 +1951,7 @@ host).
Per-capability resilience (retry, timeout, circuit-breaker) is applied by `CapabilityInvoker` in `src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/`. A driver-capability call made **outside** the invoker bypasses resilience entirely — which in production looks like inconsistent timeouts, un-wrapped retries, and unbounded blocking.
`OTOPCUA0001` (Roslyn analyzer at `src/Tooling/ZB.MOM.WW.OtOpcUa.Analyzers/UnwrappedCapabilityCallAnalyzer.cs`) fires with category `OtOpcUa.Resilience` and default severity **Warning** (per `AnalyzerReleases.Shipped.md`) when a method on one of the six guarded capability interfaces (`IReadable`, `IWritable`, `ITagDiscovery`, `ISubscribable`, `IHostConnectivityProbe`, `IAlarmSource` — all in `ZB.MOM.WW.OtOpcUa.Core.Abstractions`) is invoked **outside** a lambda passed to `CapabilityInvoker.ExecuteAsync` / `ExecuteWriteAsync`. `AlarmSurfaceInvoker` is **not** a wrapper home — its own implementation is covered transitively because it routes through the inner `CapabilityInvoker.ExecuteAsync`. The analyzer walks up the syntax tree from the call site, finds any enclosing invoker invocation, and verifies the call lives transitively inside that invocation's anonymous-function argument — a sibling pattern (do the call, then invoke `ExecuteAsync` on something unrelated nearby) does not satisfy the rule.
`OTOPCUA0001` (Roslyn analyzer at `src/Tooling/ZB.MOM.WW.OtOpcUa.Analyzers/UnwrappedCapabilityCallAnalyzer.cs`) fires with category `OtOpcUa.Resilience` and default severity **Warning** (per `AnalyzerReleases.Shipped.md`) when a method on one of the eight guarded capability interfaces (`IReadable`, `IWritable`, `ITagDiscovery`, `ISubscribable`, `IHostConnectivityProbe`, `IAlarmSource`, `IAcknowledgedAcquisitionSource`, plus `IWriteOutcomeCapability` in `…Core.Abstractions.DataConnections` — all others in `ZB.MOM.WW.OtOpcUa.Core.Abstractions`; the last two were added by #1001). The one intentional production suppression of the acquisition call is `DriverInstanceActor.PendingAcquisition.Start`, justified inline (the stock Subscribe pipeline's retry/per-attempt timeout would orphan late-arriving handles that the actor must release itself) is invoked **outside** a lambda passed to `CapabilityInvoker.ExecuteAsync` / `ExecuteWriteAsync`. `AlarmSurfaceInvoker` is **not** a wrapper home — its own implementation is covered transitively because it routes through the inner `CapabilityInvoker.ExecuteAsync`. The analyzer walks up the syntax tree from the call site, finds any enclosing invoker invocation, and verifies the call lives transitively inside that invocation's anonymous-function argument — a sibling pattern (do the call, then invoke `ExecuteAsync` on something unrelated nearby) does not satisfy the rule.
The xunit.v3 + Shouldly suite at `tests/Tooling/ZB.MOM.WW.OtOpcUa.Analyzers.Tests/UnwrappedCapabilityCallAnalyzerTests.cs` covers the common fail/pass shapes + the sibling-pattern regression guard.
@@ -2246,9 +2246,19 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
_finished.TrySetResult(true);
}
// OTOPCUA0001 (#1001/S-11) is suppressed here ON PURPOSE, not overlooked. The stock Subscribe
// pipeline cannot wrap this call safely: it retries (3x on tiers A/B) and times out per attempt
// (5-8 s, shorter than the actor's 10 s acquisition timeout), but a SubscribeAcquisitionAsync
// attempt that is cancelled or superseded may still complete later with a physical handle, and
// the contract makes THIS class (PendingAcquisition) the sole owner of releasing it. A Polly
// retry/timeout would orphan those handles and desync the capacity reservation. Establishment
// is already bounded by the actor's own acquisition timeout + the _stop token. Follow-up: give
// the invoker a non-retrying acquisition capability so breaker/telemetry cover it too.
internal void Start(IAcknowledgedAcquisitionSource source, AcquisitionSubscriptionRequest request,
Action<AcquisitionBatch> callback) => _ = ObserveAsync(Task.Run(() =>
#pragma warning disable OTOPCUA0001
source.SubscribeAcquisitionAsync(request, callback, _stop.Token)));
#pragma warning restore OTOPCUA0001
private async Task ObserveAsync(Task<AcquisitionSubscriptionResult> operation)
{
@@ -75,6 +75,10 @@ public sealed class UnwrappedCapabilityCallAnalyzer : DiagnosticAnalyzer
"ZB.MOM.WW.OtOpcUa.Core.Abstractions.ISubscribable",
"ZB.MOM.WW.OtOpcUa.Core.Abstractions.IHostConnectivityProbe",
"ZB.MOM.WW.OtOpcUa.Core.Abstractions.IAlarmSource",
// #1001 (S-11): newer capability interfaces whose Task-returning members do real driver
// work and so must run under the invoker's timeout/breaker/telemetry.
"ZB.MOM.WW.OtOpcUa.Core.Abstractions.IAcknowledgedAcquisitionSource",
"ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.IWriteOutcomeCapability",
];
/// <summary>
@@ -105,7 +109,7 @@ public sealed class UnwrappedCapabilityCallAnalyzer : DiagnosticAnalyzer
category: "OtOpcUa.Resilience",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: "Phase 6.1 Stream A requires every IReadable/IWritable/ITagDiscovery/ISubscribable/IHostConnectivityProbe/IAlarmSource call to route through the shared Polly pipeline. Direct calls skip the pipeline + lose per-host isolation, retry semantics, and telemetry. If the caller is Core/Server/Driver dispatch code, wrap the call in CapabilityInvoker.ExecuteAsync. If the caller is a unit test invoking the driver directly to test its wire-level behavior, either suppress with a pragma or move the suppression into a NoWarn for the test project.");
description: "Phase 6.1 Stream A requires every IReadable/IWritable/ITagDiscovery/ISubscribable/IHostConnectivityProbe/IAlarmSource/IAcknowledgedAcquisitionSource/IWriteOutcomeCapability call to route through the shared Polly pipeline. Direct calls skip the pipeline + lose per-host isolation, retry semantics, and telemetry. If the caller is Core/Server/Driver dispatch code, wrap the call in CapabilityInvoker.ExecuteAsync. If the caller is a unit test invoking the driver directly to test its wire-level behavior, either suppress with a pragma or move the suppression into a NoWarn for the test project.");
/// <inheritdoc />
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule);
@@ -29,7 +29,9 @@ public sealed class GrpcDataAdapterLifecycleTests
var publications = 0;
adapter.OnDataChange += (_, _) => Interlocked.Increment(ref publications);
await adapter.InitializeAsync("{}", Ct);
#pragma warning disable OTOPCUA0001 // Adapter wire-level test: exercises the driver adapter directly, not the dispatch path.
var outcomes = await adapter.WriteWithOutcomesAsync([new WriteRequest(Ref, 42)], Ct);
#pragma warning restore OTOPCUA0001
outcomes.ShouldHaveSingleItem().State.ShouldBe(DataWriteState.OutcomeUnknown);
source.Connection.WriteCount.ShouldBe(1);
publications.ShouldBe(0);
@@ -50,6 +50,12 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions {
public interface IHostConnectivityProbe {
IReadOnlyList<HostConnectivityStatus> GetHostStatuses();
}
public sealed class AcquisitionSubscriptionRequest { }
public sealed class AcquisitionSubscriptionResult { }
public sealed class AcquisitionBatch { }
public interface IAcknowledgedAcquisitionSource {
Task<AcquisitionSubscriptionResult> SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request, Action<AcquisitionBatch> onAcquired, CancellationToken ct);
}
public enum DriverCapability { Read, Write, Discover, AlarmSubscribe, AlarmAcknowledge }
public interface IDriverCapabilityInvoker {
ValueTask<T> ExecuteAsync<T>(DriverCapability c, string host, Func<CancellationToken, ValueTask<T>> call, CancellationToken ct);
@@ -57,6 +63,16 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions {
ValueTask<T> ExecuteWriteAsync<T>(string host, bool isIdempotent, Func<CancellationToken, ValueTask<T>> call, CancellationToken ct);
}
}
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections {
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
public sealed class WriteRequest { }
public sealed class DataWriteOutcome { }
public interface IWriteOutcomeCapability {
Task<IReadOnlyList<DataWriteOutcome>> WriteWithOutcomesAsync(IReadOnlyList<WriteRequest> writes, CancellationToken ct);
}
}
namespace ZB.MOM.WW.OtOpcUa.Core.Resilience {
using System;
using System.Collections.Generic;
@@ -690,6 +706,101 @@ namespace ZB.MOM.WW.OtOpcUa.Server {
diags[0].GetMessage().ShouldContain("AcknowledgeAsync");
}
/// <summary>S-11 (#1001): a direct SubscribeAcquisitionAsync call (here inside Task.Run, the
/// DriverInstanceActor shape) bypasses the invoker and must trip.</summary>
[Fact]
public async Task Direct_SubscribeAcquisitionAsync_InsideTaskRun_TripsDiagnostic()
{
const string userSrc = """
using System;
using System.Threading;
using System.Threading.Tasks;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Server {
public sealed class BadAcq {
public Task DoIt(IAcknowledgedAcquisitionSource source, AcquisitionSubscriptionRequest r, Action<AcquisitionBatch> cb) =>
Task.Run(() => source.SubscribeAcquisitionAsync(r, cb, CancellationToken.None));
}
}
""";
var diags = await Compile(userSrc);
diags.Length.ShouldBe(1);
diags[0].GetMessage().ShouldContain("SubscribeAcquisitionAsync");
}
/// <summary>The same call routed through the invoker lambda passes (positive control).</summary>
[Fact]
public async Task Wrapped_SubscribeAcquisitionAsync_InsideInvokerLambda_PassesCleanly()
{
const string userSrc = """
using System;
using System.Threading;
using System.Threading.Tasks;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Resilience;
namespace ZB.MOM.WW.OtOpcUa.Server {
public sealed class GoodAcq {
public async Task DoIt(IAcknowledgedAcquisitionSource source, AcquisitionSubscriptionRequest r, Action<AcquisitionBatch> cb, CapabilityInvoker invoker) {
var _ = await invoker.ExecuteAsync(DriverCapability.Read, "h1",
async ct => await source.SubscribeAcquisitionAsync(r, cb, ct), CancellationToken.None);
}
}
}
""";
var diags = await Compile(userSrc);
diags.ShouldBeEmpty();
}
/// <summary>S-11 (#1001): an unwrapped WriteWithOutcomesAsync trips.</summary>
[Fact]
public async Task Direct_WriteWithOutcomesAsync_Call_TripsDiagnostic()
{
const string userSrc = """
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Server {
public sealed class BadOutcomeWrite {
public async Task DoIt(IWriteOutcomeCapability driver) {
var _ = await driver.WriteWithOutcomesAsync(new List<WriteRequest>(), CancellationToken.None);
}
}
}
""";
var diags = await Compile(userSrc);
diags.Length.ShouldBe(1);
diags[0].GetMessage().ShouldContain("WriteWithOutcomesAsync");
}
/// <summary>The outcome write inside ExecuteWriteAsync passes (positive control).</summary>
[Fact]
public async Task Wrapped_WriteWithOutcomesAsync_InsideExecuteWriteAsync_PassesCleanly()
{
const string userSrc = """
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Resilience;
namespace ZB.MOM.WW.OtOpcUa.Server {
public sealed class GoodOutcomeWrite {
public async Task DoIt(IWriteOutcomeCapability driver, CapabilityInvoker invoker) {
var _ = await invoker.ExecuteWriteAsync("h1", false,
async ct => await driver.WriteWithOutcomesAsync(new List<WriteRequest>(), ct), CancellationToken.None);
}
}
}
""";
var diags = await Compile(userSrc);
diags.ShouldBeEmpty();
}
private static async Task<ImmutableArray<Diagnostic>> CompileWithoutStubs(string userSource)
{
var syntaxTrees = new[] { CSharpSyntaxTree.ParseText(userSource) };