Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ApiMethodCompileDiagnosticsTests.cs
T
Joseph Doherty 0c2e852a62 fix(inbound-api): API-method recompile/invalidate reaches the peer central node; stale doc; locked-override name rule (ScadaBridge#103)
(a) Inbound API compile state (#75) is per central node: a recompile cleared the
known-bad record only on the node that answered, and the peer kept refusing the
unchanged script with SCRIPT_COMPILE_FAILED (the per-request revision check only
notices a changed script). Create / update / delete (ManagementActor post-commit),
RecompileApiMethod, and API methods written by a Transport bundle import now publish
InboundApiMethodInvalidated on the central cache-invalidation topic (#100 item 3).
The new InboundApiCacheInvalidationHandler drops that method's compiled handler,
known-bad record and cached ApiMethod row on the peer, which compiles the current
text on its next request.

(b) docs/components/InboundAPI.md no longer claims a direct DB edit stays stale
until restart: the per-request revision check picks it up once the node's cached
row expires (ApiMethodCacheTtl, 5 s). Component-InboundAPI, Component-Host and the
#85 cache audit describe the peer invalidation.

(c) Decision: the import's locked-override warnings keep EXACT (ordinal) name
matching, because FlatteningService matches override names ordinally. An override
differing from a locked member only by case never reaches that member's lock check
(the flattener drops it as unresolved), so a "targets a LOCKED member" warning for it
would be false. The comparer is now named (LockedOverrideNameComparer) and documented,
and pinned by tests on both sides (flattener + import).

Tests: the peer's known-bad record is cleared by a recompile (and validate leaves it
alone); create/update/delete and the import publish the invalidation; the handler
drops only the named method; composition root registers the handler; case-only
override gets no lock warning; the flattener matches override names exactly.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 16:04:28 -05:00

180 lines
8.6 KiB
C#

using System.Text.Json;
using Akka.Actor;
using Akka.TestKit.Xunit2;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.InboundApi;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Communication;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
using ZB.MOM.WW.ScadaBridge.InboundAPI;
namespace ZB.MOM.WW.ScadaBridge.ManagementService.Tests;
/// <summary>
/// ScadaBridge#75: an inbound method whose script fails to compile answers callers with a
/// generic message and its real diagnostic used to reach only the central log. The
/// management surface now returns the diagnostics (<c>ValidateApiMethod</c>), shows the
/// node's compile state on <c>GetApiMethod</c>, and can clear a stale failure without a
/// full-replace update (<c>RecompileApiMethod</c>).
/// </summary>
public class ApiMethodCompileDiagnosticsTests : TestKit
{
private const string BrokenScript = "return doesNotExist;";
private readonly ServiceCollection _services = new ServiceCollection().AddTestConfigurationTransaction();
private readonly IInboundApiRepository _apiRepo = Substitute.For<IInboundApiRepository>();
private readonly IAuditService _audit = Substitute.For<IAuditService>();
private readonly InboundScriptExecutor _executor =
new(NullLogger<InboundScriptExecutor>.Instance, Substitute.For<IServiceProvider>());
private readonly ApiMethod _method = new("Broken", BrokenScript) { Id = 5, TimeoutSeconds = 10 };
// The other central node, reached only through the peer invalidation (ScadaBridge#103).
private readonly InboundScriptExecutor _peerExecutor =
new(NullLogger<InboundScriptExecutor>.Instance, Substitute.For<IServiceProvider>());
private readonly ApiMethodCache _peerMethodCache = new(TimeSpan.FromHours(1));
private readonly PeerCacheInvalidationPublisher _publisher;
/// <summary>Initializes the harness with a real executor and a stubbed repository.</summary>
public ApiMethodCompileDiagnosticsTests()
{
_services.AddScoped(_ => _apiRepo);
_services.AddScoped(_ => _audit);
_services.AddSingleton(_executor);
_publisher = new PeerCacheInvalidationPublisher(
new InboundApiCacheInvalidationHandler(_peerExecutor, _peerMethodCache));
_services.AddSingleton<ICentralCacheInvalidationPublisher>(_publisher);
_apiRepo.GetApiMethodByIdAsync(5, Arg.Any<CancellationToken>()).Returns(_method);
_apiRepo.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(1);
}
private JsonElement Send(object command, string role = "Designer")
{
var actor = Sys.ActorOf(Props.Create(() => new ManagementActor(
_services.BuildServiceProvider(), NullLogger<ManagementActor>.Instance)));
actor.Tell(new ManagementEnvelope(
new AuthenticatedUser("designer", "Designer", new[] { role }, Array.Empty<string>()),
command, Guid.NewGuid().ToString("N")));
var response = ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(30));
return JsonDocument.Parse(response.JsonData).RootElement.Clone();
}
/// <summary>
/// After the data plane recorded a compile failure, GetApiMethod reports it with the real
/// compiler diagnostic, alongside the unchanged entity fields.
/// </summary>
[Fact]
public void Get_AfterACompileFailure_ReportsKnownBadWithTheDiagnostic()
{
Assert.False(_executor.CompileAndRegister(_method));
var result = Send(new GetApiMethodCommand(5), role: "Viewer");
Assert.Equal("Broken", result.GetProperty("name").GetString());
Assert.Equal(BrokenScript, result.GetProperty("script").GetString());
Assert.True(result.GetProperty("isKnownBad").GetBoolean());
Assert.False(result.GetProperty("isCompiled").GetBoolean());
Assert.Contains("doesNotExist", result.GetProperty("lastCompileError").GetString());
}
/// <summary>Validate returns the diagnostics and leaves the handler cache untouched.</summary>
[Fact]
public void Validate_ReturnsDiagnostics_WithoutRecordingAFailure()
{
var result = Send(new ValidateApiMethodCommand(5));
Assert.False(result.GetProperty("success").GetBoolean());
Assert.Contains(result.GetProperty("errors").EnumerateArray(),
e => e.GetString()!.Contains("doesNotExist", StringComparison.Ordinal));
var state = _executor.GetCompileState("Broken", BrokenScript);
Assert.False(state.IsKnownBad);
Assert.False(state.IsCompiled);
}
/// <summary>
/// A failure recorded for unchanged script text is cleared by a recompile once the cause
/// outside the script is gone — here modelled by the stored row now compiling — without
/// re-sending the entity. The recompile is audited.
/// </summary>
[Fact]
public void Recompile_ClearsAStaleFailure_AndIsAudited()
{
Assert.False(_executor.CompileAndRegister(_method));
_method.Script = "return 1;";
var result = Send(new RecompileApiMethodCommand(5));
Assert.True(result.GetProperty("success").GetBoolean());
Assert.Empty(result.GetProperty("errors").EnumerateArray());
var state = _executor.GetCompileState("Broken", "return 1;");
Assert.True(state.IsCompiled);
Assert.False(state.IsKnownBad);
_audit.Received(1).LogAsync("designer", "Recompile", "ApiMethod", "5", "Broken",
Arg.Any<object?>(), Arg.Any<CancellationToken>());
}
/// <summary>A recompile of a still-broken script records the new diagnostics.</summary>
[Fact]
public void Recompile_StillBroken_RecordsTheDiagnostics()
{
var result = Send(new RecompileApiMethodCommand(5));
Assert.False(result.GetProperty("success").GetBoolean());
var state = _executor.GetCompileState("Broken", BrokenScript);
Assert.True(state.IsKnownBad);
Assert.Contains("doesNotExist", state.LastCompileError);
}
/// <summary>
/// ScadaBridge#103: compile state is per node, so a recompile used to clear the known-bad
/// record only on the node that answered — the peer kept refusing the unchanged script with
/// SCRIPT_COMPILE_FAILED until it restarted. The recompile now drops the peer's record (and
/// its cached row), so the peer compiles the current text on its next request.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Recompile_ClearsTheKnownBadRecordOnThePeerNode()
{
Assert.False(_peerExecutor.CompileAndRegister(_method));
Assert.True(_peerExecutor.GetCompileState("Broken", BrokenScript).IsKnownBad); // positive control
await _peerMethodCache.GetOrFetchAsync("Broken", _ => Task.FromResult<ApiMethod?>(_method), CancellationToken.None);
Send(new RecompileApiMethodCommand(5));
Assert.False(_peerExecutor.GetCompileState("Broken", BrokenScript).IsKnownBad);
var refetched = false;
await _peerMethodCache.GetOrFetchAsync("Broken", _ => { refetched = true; return Task.FromResult<ApiMethod?>(_method); }, CancellationToken.None);
Assert.True(refetched);
Assert.Equal(new[] { new InboundApiMethodInvalidated("Broken") }, _publisher.Published);
}
/// <summary>Negative control: validate changes nothing anywhere, so it tells the peer nothing.</summary>
[Fact]
public void Validate_DoesNotTouchThePeer()
{
Assert.False(_peerExecutor.CompileAndRegister(_method));
Send(new ValidateApiMethodCommand(5));
Assert.True(_peerExecutor.GetCompileState("Broken", BrokenScript).IsKnownBad);
Assert.Empty(_publisher.Published);
}
/// <summary>Validate and recompile are Designer operations, like UpdateApiMethod.</summary>
/// <param name="command">The command name to send.</param>
[Theory]
[InlineData("Validate")]
[InlineData("Recompile")]
public void ValidateAndRecompile_RequireDesigner(string command)
{
var actor = Sys.ActorOf(Props.Create(() => new ManagementActor(
_services.BuildServiceProvider(), NullLogger<ManagementActor>.Instance)));
object message = command == "Validate" ? new ValidateApiMethodCommand(5) : new RecompileApiMethodCommand(5);
actor.Tell(new ManagementEnvelope(
new AuthenticatedUser("viewer", "Viewer", new[] { "Viewer" }, Array.Empty<string>()),
message, Guid.NewGuid().ToString("N")));
ExpectMsg<ManagementUnauthorized>(TimeSpan.FromSeconds(10));
}
}