Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/AnalysisClosureMock.cs
T
Joseph Doherty 59817f5017 perf(deployment,template-engine): batched untracked staleness loads, staging-failure detach, lock-held Disabled re-check, targeted single-entity loads (DEP-4, DEP-5, DEP-6, TPL-4, WP6 task 6.6)
DEP-4: new ITemplateEngineRepository.GetInstancesByIdsUntrackedAsync (one
AsNoTracking split query per 500-id chunk). GetInstanceStalenessAsync preloads
each chunk into its FlattenSession; FlattenCoreAsync takes a preloaded
instance (consumed once) before falling back to the tracked per-instance load.
Deploy sessions never preload, so prepare keeps its tracked load.
  Throwaway harness, SQLite, 1,000 instances x 50 overrides:
  before: 5,000 reader commands, 51,000 tracked entities
  after:  10 reader commands, 0 tracked entities
  (wall time on in-process SQLite 2.7 s -> 2.3 s; the win on SQL Server is
  the 4,990 saved round-trips and the change tracker staying empty)

DEP-5: AddPendingDeploymentAsync supersedes prior rows with a set-based
delete (DeletePendingWhereAsync) instead of tracked key stubs, and a failed
staging save calls DetachPendingChanges under dbGate so it cannot poison the
next instance's staging save on the shared bulk context.
  Regression: prior row purged between supersede and save -> before:
  DbUpdateConcurrencyException; after: stages cleanly.

DEP-6: bulk prepare (reconcileGate != null) re-reads the instance state
untracked (new IDeploymentManagerRepository.GetInstanceStateAsync) once the
operation lock is held; Disabled -> reported in SkippedInstances with the
Disabled reason, never flattened/sent/re-enabled. Placed at the top of
PrepareUnderLockAsync so it is independent of WP7's lock-ordering change.

TPL-4: area delete uses the new shallow untracked GetInstancesBySiteIdShallowAsync;
SetAlarmOverride and Delete{Attribute,Alarm,Script} read the analysis closure
instead of the whole template table; MoveTemplate's collision check is the new
TemplateNameExistsInFolderAsync (one folder's names). SiteService already used
the include-free ISiteRepository read (unchanged).
2026-12-03 10:09:41 -05:00

90 lines
4.7 KiB
C#

using Moq;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
namespace ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests;
/// <summary>
/// Gitea #66: member add/update now asks the repository for a template's analysis closure
/// rather than the whole analysis graph. Test classes keep seeding the whole graph through
/// <c>GetAllTemplatesForAnalysisAsync</c>; this wires <c>GetTemplateAnalysisClosureAsync</c>
/// to serve the real closure walk over that seeded graph, so every existing scenario runs the
/// service against the reduced set — the same set the production repository returns.
/// </summary>
internal static class AnalysisClosureMock
{
/// <summary>Wires the closure method to filter whatever the full-graph setup returns.</summary>
/// <param name="repoMock">The repository mock.</param>
/// <param name="closureRequests">Optional sink recording each requested closure root.</param>
public static void ServeClosureFromFullGraph(
this Mock<ITemplateEngineRepository> repoMock,
List<int>? closureRequests = null)
{
repoMock
.Setup(r => r.GetTemplateAnalysisClosureAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns((int templateId, CancellationToken ct) =>
{
closureRequests?.Add(templateId);
return TemplateAnalysisClosure.CollectAsync(
templateId,
async (ids, token) =>
{
var all = await repoMock.Object.GetAllTemplatesForAnalysisAsync(token)
?? Array.Empty<Template>();
return all.Where(t => ids.Contains(t.Id)).ToList();
},
ct);
});
// TPL-4: the folder-move collision check is a (FolderId, Name) existence query now;
// answer it from the same seeded graph.
repoMock
.Setup(r => r.TemplateNameExistsInFolderAsync(
It.IsAny<int?>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(async (int? folderId, string name, int excludeId, CancellationToken ct) =>
((await repoMock.Object.GetAllTemplatesForAnalysisAsync(ct)) ?? Array.Empty<Template>())
.Any(t => t.Id != excludeId && t.FolderId == folderId
&& string.Equals(t.Name, name, StringComparison.OrdinalIgnoreCase)));
}
/// <summary>
/// Gitea #86: the descendant reconcile now asks for the reconcile closure (derived subtree +
/// the template's chain) instead of <c>GetAllTemplatesAsync</c>. Wires it to run the real
/// closure walk over whatever the full tracked-graph setup returns, so every existing
/// propagation scenario exercises the service against the reduced set. Also serves the
/// chain-only read the inherited-member resync falls back to for a leaf (Gitea #89).
/// </summary>
/// <param name="repoMock">The repository mock.</param>
/// <param name="closureRequests">Optional sink recording each requested closure root.</param>
public static void ServeReconcileClosureFromFullGraph(
this Mock<ITemplateEngineRepository> repoMock,
List<int>? closureRequests = null)
{
async Task<IReadOnlyList<Template>> All(CancellationToken token) =>
await repoMock.Object.GetAllTemplatesAsync(token) ?? Array.Empty<Template>();
repoMock
.Setup(r => r.GetTemplateReconcileClosureAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns((int templateId, CancellationToken ct) =>
{
closureRequests?.Add(templateId);
return TemplateReconcileClosure.CollectAsync(
templateId,
async (parentIds, token) => (await All(token))
.Where(t => t.ParentTemplateId is int p && parentIds.Contains(p)).ToList(),
async (ids, token) => (await All(token)).Where(t => ids.Contains(t.Id)).ToList(),
ct);
});
// Gitea #89: the resync of a template nobody derives from falls back to its chain.
repoMock
.Setup(r => r.GetTemplateChainAsync(It.IsAny<int>(), It.IsAny<bool>(), It.IsAny<CancellationToken>()))
.Returns((int templateId, bool _, CancellationToken ct) =>
TemplateReconcileClosure.CollectChainAsync(
templateId,
async (ids, token) => (await All(token)).Where(t => ids.Contains(t.Id)).ToList(),
ct));
}
}