Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/TargetedLoadRepositoryTests.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

121 lines
5.5 KiB
C#

using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Repositories;
/// <summary>
/// WP6 task 6.6 (DEP-4, DEP-6, TPL-4): the targeted, untracked repository reads that replace
/// whole-graph or per-row tracked loads, asserted against real SQL on SQLite.
/// </summary>
public class TargetedLoadRepositoryTests : IDisposable
{
private readonly ScadaBridgeDbContext _context;
private readonly TemplateEngineRepository _templates;
private readonly DeploymentManagerRepository _deployments;
/// <summary>Initializes the test class with an in-memory context and the repositories.</summary>
public TargetedLoadRepositoryTests()
{
_context = SqliteTestHelper.CreateInMemoryContext();
_templates = new TemplateEngineRepository(_context, new TemplateGraphWatermark());
_deployments = new DeploymentManagerRepository(_context);
}
/// <summary>Releases the resources held by this test class.</summary>
public void Dispose()
{
_context.Database.CloseConnection();
_context.Dispose();
}
private async Task<(int SiteId, int TemplateId, List<int> InstanceIds)> SeedAsync(int instances)
{
var site = new Site("Site", "S1");
var template = new Template("T");
_context.Sites.Add(site);
_context.Templates.Add(template);
await _context.SaveChangesAsync();
var ids = new List<int>();
for (var i = 0; i < instances; i++)
{
var instance = new Instance($"I{i:0000}") { SiteId = site.Id, TemplateId = template.Id };
instance.AttributeOverrides.Add(new InstanceAttributeOverride("A") { OverrideValue = i.ToString() });
_context.Instances.Add(instance);
}
await _context.SaveChangesAsync();
ids.AddRange(await _context.Instances.Select(i => i.Id).ToListAsync());
_context.ChangeTracker.Clear();
return (site.Id, template.Id, ids);
}
/// <summary>DEP-4: the batched loader returns every requested instance with its children, untracked, across chunks.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task GetInstancesByIdsUntracked_LoadsChildren_AcrossChunks_WithoutTracking()
{
var (_, _, ids) = await SeedAsync(620);
var loaded = await _templates.GetInstancesByIdsUntrackedAsync(ids.Append(ids[0]).Append(-1).ToList());
Assert.Equal(ids.Count, loaded.Count);
Assert.All(loaded, i => Assert.Single(i.AttributeOverrides));
Assert.Empty(_context.ChangeTracker.Entries());
}
/// <summary>TPL-4: the shallow site read carries no child collections and tracks nothing.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task GetInstancesBySiteIdShallow_IsUntracked_AndCarriesNoChildren()
{
var (siteId, _, ids) = await SeedAsync(3);
var shallow = await _templates.GetInstancesBySiteIdShallowAsync(siteId);
Assert.Equal(ids.Count, shallow.Count);
Assert.All(shallow, i => Assert.Empty(i.AttributeOverrides));
Assert.Empty(_context.ChangeTracker.Entries());
}
/// <summary>TPL-4: the folder-move collision check is a case-insensitive sibling-name query that excludes the moved template.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task TemplateNameExistsInFolder_IsCaseInsensitive_AndExcludesSelf()
{
var folder = new TemplateFolder("F");
_context.TemplateFolders.Add(folder);
await _context.SaveChangesAsync();
var inFolder = new Template("Pump") { FolderId = folder.Id };
var atRoot = new Template("Valve");
_context.Templates.AddRange(inFolder, atRoot);
await _context.SaveChangesAsync();
Assert.True(await _templates.TemplateNameExistsInFolderAsync(folder.Id, "PUMP", atRoot.Id));
Assert.False(await _templates.TemplateNameExistsInFolderAsync(folder.Id, "Pump", inFolder.Id));
Assert.False(await _templates.TemplateNameExistsInFolderAsync(null, "Pump", atRoot.Id));
Assert.True(await _templates.TemplateNameExistsInFolderAsync(null, "valve", inFolder.Id));
}
/// <summary>DEP-6: the state read sees a state committed after this context loaded (and tracks) the instance.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task GetInstanceState_BypassesIdentityResolution()
{
var (_, _, ids) = await SeedAsync(1);
var tracked = await _context.Instances.SingleAsync(i => i.Id == ids[0]);
Assert.Equal(InstanceState.NotDeployed, tracked.State);
await _context.Database.ExecuteSqlRawAsync(
"UPDATE Instances SET State = {0} WHERE Id = {1}", InstanceState.Disabled.ToString(), ids[0]);
Assert.Equal(InstanceState.NotDeployed, (await _context.Instances.SingleAsync(i => i.Id == ids[0])).State);
Assert.Equal(InstanceState.Disabled, await _deployments.GetInstanceStateAsync(ids[0]));
Assert.Null(await _deployments.GetInstanceStateAsync(-1));
}
}