Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ApiMethodCacheInvalidationTests.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

145 lines
6.4 KiB
C#

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>
/// Gitea #85: an API-method create / update / delete through the management API must drop this
/// node's <see cref="ApiMethodCache"/> entry once the change commits. Before, only the compiled
/// handler was invalidated, so the node kept resolving the pre-change row for up to the cache
/// TTL — a deleted method stayed callable and a cached not-found hid a newly created one.
/// </summary>
public class ApiMethodCacheInvalidationTests : TestKit
{
private readonly ServiceCollection _services = new ServiceCollection().AddTestConfigurationTransaction();
private readonly IInboundApiRepository _apiRepo = Substitute.For<IInboundApiRepository>();
// A TTL far longer than the test, so only an explicit invalidation can clear an entry.
private readonly ApiMethodCache _cache = new(TimeSpan.FromHours(1));
private readonly PeerCacheInvalidationPublisher _publisher = new();
/// <summary>Initializes the harness with a long-TTL method cache.</summary>
public ApiMethodCacheInvalidationTests()
{
_services.AddScoped(_ => _apiRepo);
_services.AddScoped(_ => Substitute.For<IAuditService>());
_services.AddSingleton(_cache);
_services.AddSingleton<ICentralCacheInvalidationPublisher>(_publisher);
_apiRepo.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(1);
}
private IActorRef CreateActor() =>
Sys.ActorOf(Props.Create(() => new ManagementActor(
_services.BuildServiceProvider(), NullLogger<ManagementActor>.Instance)));
private static ManagementEnvelope Envelope(object command) =>
new(new AuthenticatedUser("designer", "Designer", new[] { "Designer" }, Array.Empty<string>()),
command, Guid.NewGuid().ToString("N"));
private Task Seed(string name, ApiMethod? row) =>
_cache.GetOrFetchAsync(name, _ => Task.FromResult(row), CancellationToken.None);
/// <summary>Returns true when the cache re-fetches <paramref name="name"/> (the entry was dropped).</summary>
private async Task<bool> Refetches(string name)
{
var fetched = false;
await _cache.GetOrFetchAsync(name, _ => { fetched = true; return Task.FromResult<ApiMethod?>(null); }, CancellationToken.None);
return fetched;
}
/// <summary>A cached not-found must not hide a method created through the management API.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Create_DropsCachedNotFound()
{
await Seed("Fresh", null);
Assert.False(await Refetches("Fresh")); // positive control: the negative entry is served
CreateActor().Tell(Envelope(new CreateApiMethodCommand("Fresh", "return 1;", 30, null, null)));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(30));
Assert.True(await Refetches("Fresh"));
}
/// <summary>An update drops the cached pre-change row.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Update_DropsCachedRow()
{
var existing = new ApiMethod("Edited", "return 1;") { Id = 7, TimeoutSeconds = 10 };
_apiRepo.GetApiMethodByIdAsync(7, Arg.Any<CancellationToken>()).Returns(existing);
await Seed("Edited", existing);
CreateActor().Tell(Envelope(new UpdateApiMethodCommand(7, "return 2;", 10, null, null)));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(30));
Assert.True(await Refetches("Edited"));
}
/// <summary>A delete drops the cached row so the deleted method is no longer resolved.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Delete_DropsCachedRow()
{
var existing = new ApiMethod("Gone", "return 1;") { Id = 9, TimeoutSeconds = 10 };
_apiRepo.GetApiMethodByIdAsync(9, Arg.Any<CancellationToken>()).Returns(existing);
await Seed("Gone", existing);
CreateActor().Tell(Envelope(new DeleteApiMethodCommand(9)));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(30));
Assert.True(await Refetches("Gone"));
}
/// <summary>A change to one method leaves other methods' entries cached.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Delete_LeavesOtherMethodsCached()
{
var existing = new ApiMethod("Gone2", "return 1;") { Id = 10, TimeoutSeconds = 10 };
_apiRepo.GetApiMethodByIdAsync(10, Arg.Any<CancellationToken>()).Returns(existing);
await Seed("Other", new ApiMethod("Other", "return 3;"));
CreateActor().Tell(Envelope(new DeleteApiMethodCommand(10)));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(30));
Assert.False(await Refetches("Other"));
}
/// <summary>
/// ScadaBridge#103: create, update and delete tell the peer central node to drop the method's
/// handler, known-bad record and cached row, once each and after commit.
/// </summary>
[Fact]
public void CreateUpdateDelete_TellThePeer()
{
var existing = new ApiMethod("Peer", "return 1;") { Id = 11, TimeoutSeconds = 10 };
_apiRepo.GetApiMethodByIdAsync(11, Arg.Any<CancellationToken>()).Returns(existing);
var actor = CreateActor();
foreach (var command in new object[]
{
new CreateApiMethodCommand("Peer", "return 1;", 30, null, null),
new UpdateApiMethodCommand(11, "return 2;", 10, null, null),
new DeleteApiMethodCommand(11),
})
{
actor.Tell(Envelope(command));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(30));
}
Assert.Equal(
Enumerable.Repeat<ICentralCacheInvalidation>(new InboundApiMethodInvalidated("Peer"), 3),
_publisher.Published);
}
}