Merge branch 'review/wp6' into review/integration

# Conflicts:
#	docs/requirements/Component-StoreAndForward.md
#	src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs
#	src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs
#	src/ZB.MOM.WW.ScadaBridge.Transport/Import/BundleImporter.cs
#	tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardStorageTests.cs
This commit is contained in:
Joseph Doherty
2026-12-03 11:03:44 -05:00
84 changed files with 4722 additions and 233 deletions
@@ -186,6 +186,7 @@ public class AuditLogEntityTypeConfigurationTests : IDisposable
var expected = new[]
{
"IX_AuditLog_Actor_Occurred",
"IX_AuditLog_Channel_Occurred", // AuditLogChannelOccurredIndex (AUD-5)
"IX_AuditLog_Channel_Status_Occurred",
"IX_AuditLog_CorrelationId",
"IX_AuditLog_Execution",
@@ -70,7 +70,11 @@ public sealed class FlipAuditLogClusteredKeyMigrationTests : IClassFixture<MsSql
Assert.True(indexes["PK_AuditLog"].Clustered);
Assert.Equal("EventId, OccurredAtUtc", indexes["UX_AuditLog_EventId_Occurred"].Keys);
Assert.True(indexes["UX_AuditLog_EventId_Occurred"].Unique);
Assert.Equal(NonClusteredIndexes.Length + 2, indexes.Count);
// + PK + UX + IX_AuditLog_Channel_Occurred (AuditLogChannelOccurredIndex, AUD-5 — added
// after the flip, so the pre-flip round-trip shape below does not carry it).
Assert.Equal(NonClusteredIndexes.Length + 3, indexes.Count);
Assert.Equal("Category, OccurredAtUtc", indexes["IX_AuditLog_Channel_Occurred"].Keys);
Assert.False(indexes["IX_AuditLog_Channel_Occurred"].Clustered);
Assert.All(indexes.Values, i => Assert.Equal("ps_AuditLog_Month", i.DataSpace));
AssertNonClusteredIndexes(indexes, withChainIndexes: false);
Assert.Equal(ExpectedGrants, await ReadGrantsAsync());
@@ -84,6 +84,28 @@ public class PendingDeploymentRepositoryTests : IDisposable
Assert.Equal(instanceId, current.InstanceId);
}
/// <summary>
/// DEP-5 (WP6 6.6): a prior pending row that the TTL purge (or reconciliation) deleted
/// after this context loaded it must not fail the superseding stage with a concurrency
/// error — the supersede is a set-based delete, not tracked key stubs.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task AddPendingDeployment_PriorRowDeletedConcurrently_DoesNotThrow()
{
var instanceId = await SeedInstanceAsync("Inst-race");
await _repository.AddPendingDeploymentAsync(NewPending("depA", instanceId, "{}"));
await _repository.SaveChangesAsync(); // depA is now tracked by this context
await _repository.AddPendingDeploymentAsync(NewPending("depB", instanceId, "{}"));
// Between the supersede and the save, the purge actor removes depA on its own
// connection/context (ExecuteDelete of expired rows).
await _context.Database.ExecuteSqlRawAsync("DELETE FROM PendingDeployments WHERE DeploymentId = 'depA'");
await _repository.SaveChangesAsync();
Assert.NotNull(await _repository.GetPendingDeploymentByIdAsync("depB"));
}
/// <summary>Verifies that pending deployments for different instances coexist.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
@@ -24,10 +24,31 @@ public class AuditPurgeBudgetTests
Assert.Equal(ConnectionState.Closed, connection.State);
}
/// <summary>
/// AUD-5 (WP6 6.5): the channel is bound as varchar(32) to match the Category column — an
/// nvarchar parameter makes SQL Server convert the column under a SQL collation and rules
/// out a seek on IX_AuditLog_Channel_Occurred.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ChannelParameter_IsBoundAsVarchar32()
{
using var connection = new BackloggedConnection();
await using var context = new ScadaBridgeDbContext(new DbContextOptionsBuilder<ScadaBridgeDbContext>()
.UseSqlServer(connection).Options);
await new AuditLogRepository(context).PurgeChannelOlderThanAsync(
"ScriptTrace", DateTime.UtcNow, batchSize: 3, maxRows: 3);
var channel = Assert.Single(connection.ChannelParameters);
Assert.Equal(SqlDbType.VarChar, channel.Type);
Assert.Equal(32, channel.Size);
}
private sealed class BackloggedConnection : DbConnection
{
/// <summary>Gets the batch sizes requested by the purge, in order.</summary>
public List<int> RequestedBatches { get; } = new();
/// <summary>Gets the SQL type and size of each bound <c>@channel</c> parameter, in order.</summary>
public List<(SqlDbType Type, int Size)> ChannelParameters { get; } = new();
private ConnectionState _state;
/// <inheritdoc />
[AllowNull] public override string ConnectionString { get; set; } = "Server=localhost;Database=test";
@@ -81,6 +102,8 @@ public class AuditPurgeBudgetTests
throw new InvalidOperationException("Purge did not yield despite exhausting its row budget.");
var requested = (int)_parameters.Parameters["@batch"].Value;
owner.RequestedBatches.Add(requested);
var channel = _parameters.Parameters["@channel"];
owner.ChannelParameters.Add((channel.SqlDbType, channel.Size));
return requested;
}
/// <inheritdoc />
@@ -0,0 +1,120 @@
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));
}
}