perf(deploy): flatten-session caching, bulk DeploySiteAsync, paged management queries
This commit is contained in:
@@ -0,0 +1,279 @@
|
||||
using Akka.Actor;
|
||||
using Akka.TestKit.Xunit2;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Deployment;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Flattening;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
|
||||
using ZB.MOM.WW.ScadaBridge.Communication;
|
||||
using ZB.MOM.WW.ScadaBridge.TemplateEngine.Flattening;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// WP2.5: bulk site deployment. Pins the properties that make the fan-out safe —
|
||||
/// concurrency is BOUNDED by the configured degree, one slow instance does not stop
|
||||
/// the others completing, a per-instance timeout contains a wedged instance, and
|
||||
/// every instance still gets its own deployment id and its own operation lock.
|
||||
/// </summary>
|
||||
public class DeploySiteAsyncTests : TestKit
|
||||
{
|
||||
private const int SiteId = 1;
|
||||
|
||||
private readonly IDeploymentManagerRepository _repo = Substitute.For<IDeploymentManagerRepository>();
|
||||
private readonly IFlatteningPipeline _pipeline = Substitute.For<IFlatteningPipeline>();
|
||||
private readonly ISiteRepository _siteRepo = Substitute.For<ISiteRepository>();
|
||||
private readonly IAuditService _audit = Substitute.For<IAuditService>();
|
||||
private readonly OperationLockManager _lockManager = new();
|
||||
|
||||
public DeploySiteAsyncTests()
|
||||
{
|
||||
_siteRepo.GetSiteByIdAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ci => new Site($"Site {ci.ArgAt<int>(0)}", $"site-{ci.ArgAt<int>(0)}") { Id = ci.ArgAt<int>(0) });
|
||||
|
||||
_pipeline.CreateSession().Returns(_ => new FlattenSession(new TemplateGraphWatermark()));
|
||||
}
|
||||
|
||||
/// <summary>Seeds <paramref name="count"/> deployable instances at the test site.</summary>
|
||||
private List<Instance> ArrangeInstances(int count)
|
||||
{
|
||||
var instances = new List<Instance>();
|
||||
for (var i = 1; i <= count; i++)
|
||||
{
|
||||
var instance = new Instance($"Inst-{i:00}")
|
||||
{
|
||||
Id = i,
|
||||
SiteId = SiteId,
|
||||
TemplateId = 10,
|
||||
State = InstanceState.NotDeployed
|
||||
};
|
||||
instances.Add(instance);
|
||||
|
||||
_repo.GetInstanceByIdAsync(i, Arg.Any<CancellationToken>()).Returns(instance);
|
||||
_repo.GetCurrentDeploymentStatusAsync(i, Arg.Any<CancellationToken>()).Returns((DeploymentRecord?)null);
|
||||
|
||||
var config = new FlattenedConfiguration { InstanceUniqueName = instance.UniqueName };
|
||||
_pipeline.FlattenAndValidateAsync(
|
||||
i, Arg.Any<CancellationToken>(), Arg.Any<bool>(), Arg.Any<FlattenSession?>())
|
||||
.Returns(Result<FlatteningPipelineResult>.Success(
|
||||
new FlatteningPipelineResult(config, $"sha256:{i}", ValidationResult.Success())));
|
||||
}
|
||||
|
||||
_siteRepo.GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>()).Returns(instances);
|
||||
return instances;
|
||||
}
|
||||
|
||||
private DeploymentService CreateService(IActorRef commActor, int maxParallelism, TimeSpan? perInstanceTimeout = null)
|
||||
{
|
||||
var comms = new CommunicationService(
|
||||
Options.Create(new CommunicationOptions { DeploymentTimeout = TimeSpan.FromSeconds(30) }),
|
||||
NullLogger<CommunicationService>.Instance);
|
||||
comms.SetCommunicationActor(commActor);
|
||||
|
||||
var options = Options.Create(new DeploymentManagerOptions
|
||||
{
|
||||
OperationLockTimeout = TimeSpan.FromSeconds(5),
|
||||
SiteDeploymentMaxParallelism = maxParallelism,
|
||||
SiteDeploymentTimeoutPerInstance = perInstanceTimeout ?? TimeSpan.FromSeconds(30)
|
||||
});
|
||||
|
||||
return new DeploymentService(
|
||||
_repo, _siteRepo, _pipeline, comms, _lockManager, _audit,
|
||||
new DiffService(),
|
||||
new RevisionHashService(),
|
||||
new DeploymentStatusNotifier(NullLogger<DeploymentStatusNotifier>.Instance),
|
||||
options,
|
||||
Options.Create(new CommunicationOptions
|
||||
{
|
||||
CentralFetchBaseUrl = "https://central.test:9000",
|
||||
PendingDeploymentTtl = TimeSpan.FromMinutes(5)
|
||||
}),
|
||||
NullLogger<DeploymentService>.Instance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeploySiteAsync_SlowInstance_OthersStillComplete_AndConcurrencyIsBounded()
|
||||
{
|
||||
const int instanceCount = 8;
|
||||
const int maxParallelism = 3;
|
||||
ArrangeInstances(instanceCount);
|
||||
|
||||
var tracker = new ConcurrencyTracker();
|
||||
var commActor = Sys.ActorOf(Props.Create(() =>
|
||||
new ThrottledSiteActor(tracker, slowInstanceName: "Inst-01", slowDelay: TimeSpan.FromMilliseconds(400))));
|
||||
|
||||
var service = CreateService(commActor, maxParallelism);
|
||||
|
||||
var result = await service.DeploySiteAsync(SiteId, "admin");
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
var summary = result.Value;
|
||||
|
||||
// Every instance produced a row and all eight completed, including the
|
||||
// seven that were NOT waiting on the slow site round-trip.
|
||||
Assert.Equal(instanceCount, summary.InstanceResults.Count);
|
||||
Assert.Equal(instanceCount, summary.SuccessCount);
|
||||
Assert.Equal(0, summary.FailureCount);
|
||||
|
||||
// The fan-out never exceeded the configured bound.
|
||||
Assert.True(tracker.MaxObserved <= maxParallelism,
|
||||
$"observed {tracker.MaxObserved} concurrent site round-trips, bound was {maxParallelism}");
|
||||
|
||||
// ...and it genuinely WAS concurrent, so the assertion above is not
|
||||
// vacuously satisfied by a serial implementation.
|
||||
Assert.True(tracker.MaxObserved > 1, "site round-trips did not run concurrently at all");
|
||||
|
||||
// Deployment identity: one distinct deployment id per instance.
|
||||
var deploymentIds = summary.InstanceResults.Select(r => r.DeploymentId).ToList();
|
||||
Assert.Equal(instanceCount, deploymentIds.Distinct().Count());
|
||||
Assert.DoesNotContain(deploymentIds, id => string.IsNullOrEmpty(id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeploySiteAsync_WedgedInstance_TimesOutAlone_RestSucceed()
|
||||
{
|
||||
ArrangeInstances(4);
|
||||
|
||||
var tracker = new ConcurrencyTracker();
|
||||
// Instance 2's round-trip is never answered — its per-instance deadline
|
||||
// must contain it rather than stalling the batch.
|
||||
var commActor = Sys.ActorOf(Props.Create(() =>
|
||||
new ThrottledSiteActor(tracker, slowInstanceName: "Inst-02", slowDelay: Timeout.InfiniteTimeSpan)));
|
||||
|
||||
var service = CreateService(commActor, maxParallelism: 4, perInstanceTimeout: TimeSpan.FromMilliseconds(300));
|
||||
|
||||
var result = await service.DeploySiteAsync(SiteId, "admin");
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
var summary = result.Value;
|
||||
|
||||
Assert.Equal(4, summary.InstanceResults.Count);
|
||||
Assert.Equal(3, summary.SuccessCount);
|
||||
Assert.Equal(1, summary.FailureCount);
|
||||
|
||||
var wedged = Assert.Single(summary.InstanceResults, r => !r.Success);
|
||||
Assert.Equal("Inst-02", wedged.UniqueName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeploySiteAsync_ReleasesEveryOperationLock()
|
||||
{
|
||||
ArrangeInstances(5);
|
||||
|
||||
var commActor = Sys.ActorOf(Props.Create(() =>
|
||||
new ThrottledSiteActor(new ConcurrencyTracker(), slowInstanceName: null, slowDelay: TimeSpan.Zero)));
|
||||
|
||||
var service = CreateService(commActor, maxParallelism: 2);
|
||||
|
||||
await service.DeploySiteAsync(SiteId, "admin");
|
||||
|
||||
// The per-instance operation lock is held from prepare through finalize;
|
||||
// once the batch is done every entry must be reclaimed, or a second bulk
|
||||
// deploy of the same site would deadlock on its own leftovers.
|
||||
Assert.Equal(0, _lockManager.TrackedLockCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeploySiteAsync_SiteWithNoInstances_SucceedsWithEmptySummary()
|
||||
{
|
||||
_siteRepo.GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>()).Returns([]);
|
||||
|
||||
var commActor = Sys.ActorOf(Props.Create(() =>
|
||||
new ThrottledSiteActor(new ConcurrencyTracker(), slowInstanceName: null, slowDelay: TimeSpan.Zero)));
|
||||
|
||||
var result = await CreateService(commActor, maxParallelism: 2).DeploySiteAsync(SiteId, "admin");
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Empty(result.Value.InstanceResults);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeploySiteAsync_UnknownSite_ReturnsFailure()
|
||||
{
|
||||
_siteRepo.GetSiteByIdAsync(99, Arg.Any<CancellationToken>()).Returns((Site?)null);
|
||||
|
||||
var commActor = Sys.ActorOf(Props.Create(() =>
|
||||
new ThrottledSiteActor(new ConcurrencyTracker(), slowInstanceName: null, slowDelay: TimeSpan.Zero)));
|
||||
|
||||
var result = await CreateService(commActor, maxParallelism: 2).DeploySiteAsync(99, "admin");
|
||||
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Contains("not found", result.Error);
|
||||
}
|
||||
|
||||
/// <summary>Records the peak number of simultaneously in-flight site round-trips.</summary>
|
||||
private sealed class ConcurrencyTracker
|
||||
{
|
||||
private int _current;
|
||||
private int _max;
|
||||
|
||||
/// <summary>Highest simultaneous in-flight count observed.</summary>
|
||||
public int MaxObserved => Volatile.Read(ref _max);
|
||||
|
||||
/// <summary>Marks one round-trip as started and updates the peak.</summary>
|
||||
public void Enter()
|
||||
{
|
||||
var now = Interlocked.Increment(ref _current);
|
||||
int observed;
|
||||
while (now > (observed = Volatile.Read(ref _max)))
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref _max, now, observed) == observed)
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Marks one round-trip as finished.</summary>
|
||||
public void Exit() => Interlocked.Decrement(ref _current);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stand-in site that answers <c>RefreshDeploymentCommand</c> with Success,
|
||||
/// optionally delaying (or never answering) one named instance so the test can
|
||||
/// observe the fan-out's bound and its per-instance deadline.
|
||||
///
|
||||
/// <para>
|
||||
/// The reply is scheduled rather than sent inline, so the actor's mailbox is
|
||||
/// not the thing serialising the batch — otherwise the concurrency the test is
|
||||
/// measuring would be an artefact of the harness.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
private sealed class ThrottledSiteActor : ReceiveActor
|
||||
{
|
||||
public ThrottledSiteActor(ConcurrencyTracker tracker, string? slowInstanceName, TimeSpan slowDelay)
|
||||
{
|
||||
Receive<SiteEnvelope>(env =>
|
||||
{
|
||||
if (env.Message is not RefreshDeploymentCommand cmd)
|
||||
return;
|
||||
|
||||
var replyTo = Sender;
|
||||
var isSlow = slowInstanceName != null && cmd.InstanceUniqueName == slowInstanceName;
|
||||
|
||||
if (isSlow && slowDelay == Timeout.InfiniteTimeSpan)
|
||||
{
|
||||
// Never answer: the caller's per-instance deadline must fire.
|
||||
tracker.Enter();
|
||||
return;
|
||||
}
|
||||
|
||||
var delay = isSlow ? slowDelay : TimeSpan.FromMilliseconds(60);
|
||||
tracker.Enter();
|
||||
Context.System.Scheduler.Advanced.ScheduleOnce(delay, () =>
|
||||
{
|
||||
tracker.Exit();
|
||||
replyTo.Tell(new DeploymentStatusResponse(
|
||||
cmd.DeploymentId, cmd.InstanceUniqueName,
|
||||
DeploymentStatus.Success, null, DateTimeOffset.UtcNow));
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Flattening;
|
||||
using ZB.MOM.WW.ScadaBridge.TemplateEngine.Flattening;
|
||||
using ZB.MOM.WW.ScadaBridge.TemplateEngine.Validation;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests;
|
||||
|
||||
@@ -75,7 +76,8 @@ public class DeploymentComparisonTests
|
||||
new FlatteningService(),
|
||||
new ValidationService(),
|
||||
new RevisionHashService(),
|
||||
sharedSchemaRepo);
|
||||
sharedSchemaRepo,
|
||||
new TemplateGraphWatermark());
|
||||
}
|
||||
|
||||
private static (ITemplateEngineRepository, ISiteRepository, ISharedSchemaRepository) ArrangeNonCompilingScript()
|
||||
|
||||
@@ -17,6 +17,7 @@ using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Flattening;
|
||||
using ZB.MOM.WW.ScadaBridge.Communication;
|
||||
using ZB.MOM.WW.ScadaBridge.TemplateEngine.Flattening;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests;
|
||||
|
||||
@@ -641,15 +642,21 @@ public class DeploymentServiceTests : TestKit
|
||||
public async Task StaleInstanceProbe_RequestsValidateScriptsFalse()
|
||||
{
|
||||
// The Transport stale-instance probe also only needs the hash — same skip.
|
||||
_pipeline.FlattenAndValidateAsync(5, Arg.Any<CancellationToken>(), Arg.Any<bool>())
|
||||
// The probe memoises per-instance against the graph watermark, so start
|
||||
// from a clean memo or a sibling test's entry would satisfy the probe
|
||||
// without a flatten at all.
|
||||
StaleInstanceProbe.ClearMemos();
|
||||
|
||||
_pipeline.CreateSession().Returns(_ => new FlattenSession(new TemplateGraphWatermark()));
|
||||
_pipeline.FlattenAndValidateAsync(5, Arg.Any<CancellationToken>(), Arg.Any<bool>(), Arg.Any<FlattenSession?>())
|
||||
.Returns(Result<FlatteningPipelineResult>.Success(
|
||||
new FlatteningPipelineResult(new FlattenedConfiguration(), "sha256:probe", ValidationResult.Success())));
|
||||
var probe = new StaleInstanceProbe(_pipeline);
|
||||
var probe = new StaleInstanceProbe(_pipeline, new TemplateGraphWatermark());
|
||||
|
||||
var hash = await probe.GetCurrentRevisionHashAsync(5);
|
||||
|
||||
Assert.Equal("sha256:probe", hash);
|
||||
await _pipeline.Received(1).FlattenAndValidateAsync(5, Arg.Any<CancellationToken>(), false);
|
||||
await _pipeline.Received(1).FlattenAndValidateAsync(5, Arg.Any<CancellationToken>(), false, Arg.Any<FlattenSession?>());
|
||||
}
|
||||
|
||||
// ── DeploymentManager-007: comparison must produce a structured diff ──
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
using NSubstitute;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
|
||||
using ZB.MOM.WW.ScadaBridge.TemplateEngine.Flattening;
|
||||
using ZB.MOM.WW.ScadaBridge.TemplateEngine.Validation;
|
||||
using Template = ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template;
|
||||
using TemplateAttribute = ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateAttribute;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// WP2.5: the flatten-session cache. Pins the two properties the bulk deploy path
|
||||
/// depends on — that N instances sharing a template chain load that chain ONCE per
|
||||
/// session, and that a template mutation (observed through the watermark)
|
||||
/// invalidates the memo so a session can never serve stale template state.
|
||||
/// </summary>
|
||||
public class FlattenSessionCacheTests
|
||||
{
|
||||
private const int TemplateId = 10;
|
||||
private const int ParentTemplateId = 9;
|
||||
private const int SiteId = 100;
|
||||
|
||||
private readonly ITemplateEngineRepository _templateRepo = Substitute.For<ITemplateEngineRepository>();
|
||||
private readonly ISiteRepository _siteRepo = Substitute.For<ISiteRepository>();
|
||||
private readonly ISharedSchemaRepository _sharedSchemaRepo = Substitute.For<ISharedSchemaRepository>();
|
||||
private readonly TemplateGraphWatermark _watermark = new();
|
||||
private readonly FlatteningPipeline _sut;
|
||||
|
||||
public FlattenSessionCacheTests()
|
||||
{
|
||||
_sharedSchemaRepo.ListAsync(Arg.Any<CancellationToken>()).Returns([]);
|
||||
_templateRepo.GetAllSharedScriptsAsync(Arg.Any<CancellationToken>()).Returns([]);
|
||||
_siteRepo.GetDataConnectionsBySiteIdAsync(SiteId, Arg.Any<CancellationToken>()).Returns([]);
|
||||
|
||||
_sut = new FlatteningPipeline(
|
||||
_templateRepo,
|
||||
_siteRepo,
|
||||
new FlatteningService(),
|
||||
new ValidationService(),
|
||||
new RevisionHashService(),
|
||||
_sharedSchemaRepo,
|
||||
_watermark);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a two-link inheritance chain (Tank -> TankBase) and
|
||||
/// <paramref name="instanceCount"/> instances that all derive from it.
|
||||
/// </summary>
|
||||
private void ArrangeSharedChain(int instanceCount)
|
||||
{
|
||||
var parent = new Template("TankBase") { Id = ParentTemplateId };
|
||||
parent.Attributes.Add(new TemplateAttribute("Serial") { DataType = DataType.String, Value = "x" });
|
||||
|
||||
var template = new Template("Tank") { Id = TemplateId, ParentTemplateId = ParentTemplateId };
|
||||
template.Attributes.Add(new TemplateAttribute("Temp") { DataType = DataType.Double, Value = "0" });
|
||||
|
||||
_templateRepo.GetTemplateWithChildrenAsync(TemplateId, Arg.Any<CancellationToken>()).Returns(template);
|
||||
_templateRepo.GetTemplateWithChildrenAsync(ParentTemplateId, Arg.Any<CancellationToken>()).Returns(parent);
|
||||
_templateRepo.GetCompositionsByTemplateIdAsync(Arg.Any<int>(), Arg.Any<CancellationToken>()).Returns([]);
|
||||
|
||||
for (var i = 1; i <= instanceCount; i++)
|
||||
{
|
||||
var instance = new Instance($"Tank-{i:00}") { Id = i, TemplateId = TemplateId, SiteId = SiteId };
|
||||
_templateRepo.GetInstanceByIdAsync(i, Arg.Any<CancellationToken>()).Returns(instance);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SharedSession_TenInstancesOneTemplate_LoadsEachTemplateOnce()
|
||||
{
|
||||
const int instanceCount = 10;
|
||||
ArrangeSharedChain(instanceCount);
|
||||
|
||||
var session = _sut.CreateSession();
|
||||
for (var i = 1; i <= instanceCount; i++)
|
||||
{
|
||||
var result = await _sut.FlattenAndValidateAsync(i, CancellationToken.None, validateScripts: false, session);
|
||||
Assert.True(result.IsSuccess);
|
||||
}
|
||||
|
||||
// Two templates in the chain, each read exactly once across ten flattens.
|
||||
await _templateRepo.Received(1).GetTemplateWithChildrenAsync(TemplateId, Arg.Any<CancellationToken>());
|
||||
await _templateRepo.Received(1).GetTemplateWithChildrenAsync(ParentTemplateId, Arg.Any<CancellationToken>());
|
||||
|
||||
// The chain walk itself ran once, not once per instance.
|
||||
Assert.Equal(1, session.ChainLoads);
|
||||
Assert.Equal(2, session.TemplateLoads);
|
||||
|
||||
// The session-global queries were hoisted out of the per-instance loop:
|
||||
// shared scripts + schema library once each, site connections once.
|
||||
await _templateRepo.Received(1).GetAllSharedScriptsAsync(Arg.Any<CancellationToken>());
|
||||
await _sharedSchemaRepo.Received(1).ListAsync(Arg.Any<CancellationToken>());
|
||||
await _siteRepo.Received(1).GetDataConnectionsBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NoSharedSession_EveryInstanceReloadsTheChain()
|
||||
{
|
||||
const int instanceCount = 4;
|
||||
ArrangeSharedChain(instanceCount);
|
||||
|
||||
// Baseline: without a shared session each flatten gets its own private
|
||||
// one, which is the pre-WP2.5 behaviour the batch path improves on.
|
||||
for (var i = 1; i <= instanceCount; i++)
|
||||
{
|
||||
var result = await _sut.FlattenAndValidateAsync(i, CancellationToken.None, validateScripts: false);
|
||||
Assert.True(result.IsSuccess);
|
||||
}
|
||||
|
||||
await _templateRepo.Received(instanceCount)
|
||||
.GetTemplateWithChildrenAsync(TemplateId, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TemplateMutation_InvalidatesMemo_SoSessionNeverServesStaleState()
|
||||
{
|
||||
ArrangeSharedChain(instanceCount: 2);
|
||||
|
||||
var session = _sut.CreateSession();
|
||||
Assert.True((await _sut.FlattenAndValidateAsync(1, CancellationToken.None, validateScripts: false, session)).IsSuccess);
|
||||
|
||||
// A template edit lands (the repository bumps the watermark on commit).
|
||||
_watermark.BumpTemplate(TemplateId);
|
||||
|
||||
Assert.True((await _sut.FlattenAndValidateAsync(2, CancellationToken.None, validateScripts: false, session)).IsSuccess);
|
||||
|
||||
// The edited template was re-read rather than served from the memo. The
|
||||
// untouched parent stayed cached — invalidation is per-template, not a
|
||||
// whole-session reset.
|
||||
await _templateRepo.Received(2).GetTemplateWithChildrenAsync(TemplateId, Arg.Any<CancellationToken>());
|
||||
await _templateRepo.Received(1).GetTemplateWithChildrenAsync(ParentTemplateId, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StructuralMutation_InvalidatesCachedChainMembership()
|
||||
{
|
||||
ArrangeSharedChain(instanceCount: 2);
|
||||
|
||||
var session = _sut.CreateSession();
|
||||
Assert.True((await _sut.FlattenAndValidateAsync(1, CancellationToken.None, validateScripts: false, session)).IsSuccess);
|
||||
Assert.Equal(1, session.ChainLoads);
|
||||
|
||||
// A re-parent / composition change: chain MEMBERSHIP may now differ, so the
|
||||
// cached chain must be discarded even though each member's own version is
|
||||
// unchanged.
|
||||
_watermark.BumpTemplate(TemplateId, structural: true);
|
||||
|
||||
Assert.True((await _sut.FlattenAndValidateAsync(2, CancellationToken.None, validateScripts: false, session)).IsSuccess);
|
||||
Assert.Equal(2, session.ChainLoads);
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -8,6 +8,7 @@ using ZB.MOM.WW.ScadaBridge.Commons.Types.Flattening;
|
||||
using ZB.MOM.WW.ScadaBridge.DeploymentManager;
|
||||
using ZB.MOM.WW.ScadaBridge.TemplateEngine.Flattening;
|
||||
using ZB.MOM.WW.ScadaBridge.TemplateEngine.Validation;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests;
|
||||
|
||||
@@ -40,7 +41,8 @@ public class FlatteningPipelineConnectionBindingTests
|
||||
new FlatteningService(),
|
||||
new ValidationService(),
|
||||
new RevisionHashService(),
|
||||
_sharedSchemaRepo);
|
||||
_sharedSchemaRepo,
|
||||
new TemplateGraphWatermark());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+3
-1
@@ -7,6 +7,7 @@ using ZB.MOM.WW.ScadaBridge.Commons.Types.Flattening;
|
||||
using ZB.MOM.WW.ScadaBridge.DeploymentManager;
|
||||
using ZB.MOM.WW.ScadaBridge.TemplateEngine.Flattening;
|
||||
using ZB.MOM.WW.ScadaBridge.TemplateEngine.Validation;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests;
|
||||
|
||||
@@ -40,7 +41,8 @@ public class FlatteningPipelineNativeAlarmCapabilityTests
|
||||
new FlatteningService(),
|
||||
new ValidationService(),
|
||||
new RevisionHashService(),
|
||||
_sharedSchemaRepo);
|
||||
_sharedSchemaRepo,
|
||||
new TemplateGraphWatermark());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
Reference in New Issue
Block a user