diff --git a/docs/OpcUaServer.md b/docs/OpcUaServer.md index 23375c564..4c4fcc016 100644 --- a/docs/OpcUaServer.md +++ b/docs/OpcUaServer.md @@ -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. diff --git a/docs/security.md b/docs/security.md index bd2c4e1db..f7e3a33a4 100644 --- a/docs/security.md +++ b/docs/security.md @@ -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. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs index 98c5046aa..d1dc07942 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs @@ -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 callback) => _ = ObserveAsync(Task.Run(() => +#pragma warning disable OTOPCUA0001 source.SubscribeAcquisitionAsync(request, callback, _stop.Token))); +#pragma warning restore OTOPCUA0001 private async Task ObserveAsync(Task operation) { diff --git a/src/Tooling/ZB.MOM.WW.OtOpcUa.Analyzers/UnwrappedCapabilityCallAnalyzer.cs b/src/Tooling/ZB.MOM.WW.OtOpcUa.Analyzers/UnwrappedCapabilityCallAnalyzer.cs index 10506ad49..92a71f056 100644 --- a/src/Tooling/ZB.MOM.WW.OtOpcUa.Analyzers/UnwrappedCapabilityCallAnalyzer.cs +++ b/src/Tooling/ZB.MOM.WW.OtOpcUa.Analyzers/UnwrappedCapabilityCallAnalyzer.cs @@ -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", ]; /// @@ -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."); /// public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create(Rule); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataAdapterLifecycleTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataAdapterLifecycleTests.cs index f4c151bc0..a1757d864 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataAdapterLifecycleTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataAdapterLifecycleTests.cs @@ -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); diff --git a/tests/Tooling/ZB.MOM.WW.OtOpcUa.Analyzers.Tests/UnwrappedCapabilityCallAnalyzerTests.cs b/tests/Tooling/ZB.MOM.WW.OtOpcUa.Analyzers.Tests/UnwrappedCapabilityCallAnalyzerTests.cs index 252f27ee9..afa46d2f5 100644 --- a/tests/Tooling/ZB.MOM.WW.OtOpcUa.Analyzers.Tests/UnwrappedCapabilityCallAnalyzerTests.cs +++ b/tests/Tooling/ZB.MOM.WW.OtOpcUa.Analyzers.Tests/UnwrappedCapabilityCallAnalyzerTests.cs @@ -50,6 +50,12 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions { public interface IHostConnectivityProbe { IReadOnlyList GetHostStatuses(); } + public sealed class AcquisitionSubscriptionRequest { } + public sealed class AcquisitionSubscriptionResult { } + public sealed class AcquisitionBatch { } + public interface IAcknowledgedAcquisitionSource { + Task SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request, Action onAcquired, CancellationToken ct); + } public enum DriverCapability { Read, Write, Discover, AlarmSubscribe, AlarmAcknowledge } public interface IDriverCapabilityInvoker { ValueTask ExecuteAsync(DriverCapability c, string host, Func> call, CancellationToken ct); @@ -57,6 +63,16 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions { ValueTask ExecuteWriteAsync(string host, bool isIdempotent, Func> 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> WriteWithOutcomesAsync(IReadOnlyList 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"); } + /// S-11 (#1001): a direct SubscribeAcquisitionAsync call (here inside Task.Run, the + /// DriverInstanceActor shape) bypasses the invoker and must trip. + [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 cb) => + Task.Run(() => source.SubscribeAcquisitionAsync(r, cb, CancellationToken.None)); + } +} +"""; + var diags = await Compile(userSrc); + diags.Length.ShouldBe(1); + diags[0].GetMessage().ShouldContain("SubscribeAcquisitionAsync"); + } + + /// The same call routed through the invoker lambda passes (positive control). + [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 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(); + } + + /// S-11 (#1001): an unwrapped WriteWithOutcomesAsync trips. + [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(), CancellationToken.None); + } + } +} +"""; + var diags = await Compile(userSrc); + diags.Length.ShouldBe(1); + diags[0].GetMessage().ShouldContain("WriteWithOutcomesAsync"); + } + + /// The outcome write inside ExecuteWriteAsync passes (positive control). + [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(), ct), CancellationToken.None); + } + } +} +"""; + var diags = await Compile(userSrc); + diags.ShouldBeEmpty(); + } + private static async Task> CompileWithoutStubs(string userSource) { var syntaxTrees = new[] { CSharpSyntaxTree.ParseText(userSource) };