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).
This commit is contained in:
@@ -180,6 +180,14 @@ site-wide push would silently restart every piece of equipment an operator had
|
|||||||
deliberately stopped; they are reported in the summary's `SkippedInstances` with
|
deliberately stopped; they are reported in the summary's `SkippedInstances` with
|
||||||
the reason "Disabled — bulk deploy preserves disabled state; deploy individually
|
the reason "Disabled — bulk deploy preserves disabled state; deploy individually
|
||||||
to re-enable", and the single-instance deploy remains the explicit re-enable path.
|
to re-enable", and the single-instance deploy remains the explicit re-enable path.
|
||||||
|
The skip is re-checked once each instance's operation lock is held (DEP-6, 2026-12-03):
|
||||||
|
the candidate list is read once when the batch starts, so an instance an operator
|
||||||
|
disables while the batch is still preparing earlier instances is caught by a fresh,
|
||||||
|
untracked state read (`IDeploymentManagerRepository.GetInstanceStateAsync`) and reported
|
||||||
|
as skipped with the same reason, instead of being deployed and re-enabled. A failed
|
||||||
|
staging write detaches its pending changes so it cannot poison the staging writes of
|
||||||
|
the instances after it on the shared unit of work (DEP-5), and the supersede of a prior
|
||||||
|
`PendingDeployment` row is a set-based delete rather than tracked key stubs.
|
||||||
|
|
||||||
**Up-to-date instances are skipped too (unless `force`), at batch cost.** The
|
**Up-to-date instances are skipped too (unless `force`), at batch cost.** The
|
||||||
pre-filter reads the deployed-hash projection (`GetDeployedRevisionHashesAsync`) and
|
pre-filter reads the deployed-hash projection (`GetDeployedRevisionHashesAsync`) and
|
||||||
|
|||||||
+10
@@ -413,6 +413,16 @@ public interface IDeploymentManagerRepository
|
|||||||
/// <param name="cancellationToken">A cancellation token that can be used to cancel the operation.</param>
|
/// <param name="cancellationToken">A cancellation token that can be used to cancel the operation.</param>
|
||||||
/// <returns>The instance, or null if not found.</returns>
|
/// <returns>The instance, or null if not found.</returns>
|
||||||
Task<Instance?> GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default);
|
Task<Instance?> GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// DEP-6: reads an instance's CURRENT lifecycle state straight from the database,
|
||||||
|
/// untracked — bypassing EF identity resolution, which would otherwise answer with the
|
||||||
|
/// state of an entity this unit of work loaded earlier.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="instanceId">The instance id.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The state, or <see langword="null"/> when the instance does not exist.</returns>
|
||||||
|
Task<InstanceState?> GetInstanceStateAsync(int instanceId, CancellationToken cancellationToken = default);
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets an instance by unique name.
|
/// Gets an instance by unique name.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
+36
@@ -286,6 +286,18 @@ public interface ITemplateEngineRepository
|
|||||||
/// <param name="cancellationToken">Cancellation token.</param>
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
/// <returns>A task that resolves to the matching instance, or <see langword="null"/> if not found.</returns>
|
/// <returns>A task that resolves to the matching instance, or <see langword="null"/> if not found.</returns>
|
||||||
Task<Instance?> GetInstanceByIdAsync(int id, CancellationToken cancellationToken = default);
|
Task<Instance?> GetInstanceByIdAsync(int id, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// DEP-4: loads several instances with the same child collections as
|
||||||
|
/// <see cref="GetInstanceByIdAsync"/>, <b>untracked</b>, in one split query per chunk of
|
||||||
|
/// ids — for read-only paths (fleet staleness) that must not fill the scoped change
|
||||||
|
/// tracker with every deployed instance's overrides and bindings.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="ids">The instance ids; missing ids are absent from the result.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The instances found.</returns>
|
||||||
|
Task<IReadOnlyList<Instance>> GetInstancesByIdsUntrackedAsync(
|
||||||
|
IReadOnlyCollection<int> ids, CancellationToken cancellationToken = default);
|
||||||
/// <summary>Retrieves all instances.</summary>
|
/// <summary>Retrieves all instances.</summary>
|
||||||
/// <param name="cancellationToken">Cancellation token.</param>
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
/// <returns>A task that resolves to a read-only list of all instances.</returns>
|
/// <returns>A task that resolves to a read-only list of all instances.</returns>
|
||||||
@@ -301,6 +313,30 @@ public interface ITemplateEngineRepository
|
|||||||
/// <returns>A task that resolves to a read-only list of instances for the specified site.</returns>
|
/// <returns>A task that resolves to a read-only list of instances for the specified site.</returns>
|
||||||
Task<IReadOnlyList<Instance>> GetInstancesBySiteIdAsync(int siteId, CancellationToken cancellationToken = default);
|
Task<IReadOnlyList<Instance>> GetInstancesBySiteIdAsync(int siteId, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// TPL-4: a site's instances WITHOUT their child collections, untracked — for checks
|
||||||
|
/// that only need identity, name and area (area/site delete guards), which used to load
|
||||||
|
/// and track every instance's overrides and bindings.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="siteId">The site ID.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The site's instances, shallow and untracked.</returns>
|
||||||
|
Task<IReadOnlyList<Instance>> GetInstancesBySiteIdShallowAsync(int siteId, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// TPL-4: whether a template other than <paramref name="excludeTemplateId"/> named
|
||||||
|
/// <paramref name="name"/> (case-insensitively) already sits in <paramref name="folderId"/>
|
||||||
|
/// (<see langword="null"/> = the root) — the folder-move collision check, which used to load
|
||||||
|
/// the whole template table.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="folderId">The destination folder, or null for the root.</param>
|
||||||
|
/// <param name="name">The template name.</param>
|
||||||
|
/// <param name="excludeTemplateId">The template being moved.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns><see langword="true"/> when a sibling with that name exists.</returns>
|
||||||
|
Task<bool> TemplateNameExistsInFolderAsync(
|
||||||
|
int? folderId, string name, int excludeTemplateId, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
/// <summary>Reads one bounded, untracked page of topology instance rows for a site/area.</summary>
|
/// <summary>Reads one bounded, untracked page of topology instance rows for a site/area.</summary>
|
||||||
/// <param name="siteId">The site ID.</param>
|
/// <param name="siteId">The site ID.</param>
|
||||||
/// <param name="areaId">The area ID to filter by, or null for every area.</param>
|
/// <param name="areaId">The area ID to filter by, or null for every area.</param>
|
||||||
|
|||||||
+24
-37
@@ -407,21 +407,20 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository
|
|||||||
|
|
||||||
// Supersession: a newer deploy for the same instance replaces any prior pending
|
// Supersession: a newer deploy for the same instance replaces any prior pending
|
||||||
// row. Safe because the per-instance operation lock serializes same-instance
|
// row. Safe because the per-instance operation lock serializes same-instance
|
||||||
// deploys. SaveChanges is deferred to the caller, matching the other Add methods.
|
// deploys. The new row's SaveChanges is deferred to the caller, matching the other
|
||||||
|
// Add methods.
|
||||||
//
|
//
|
||||||
// Only the prior rows' KEYS are read: each row carries the whole flattened
|
// DEP-5: the prior rows are removed with a set-based ExecuteDelete keyed on the
|
||||||
// ConfigurationJson (tens of KB), and materialising it just to delete it was the
|
// instance — never materialised (each carries the whole flattened ConfigurationJson)
|
||||||
// dominant cost of the supersede. The delete itself stays a tracked Remove (not
|
// and never tracked. The old tracked key-only stubs made the caller's SaveChanges
|
||||||
// ExecuteDelete) so it still commits atomically with the new row in the caller's
|
// throw DbUpdateConcurrencyException whenever the TTL purge (or reconciliation)
|
||||||
// SaveChanges.
|
// removed one of those rows first, and the failed stub then stayed tracked and
|
||||||
var priorIds = await _dbContext.Set<PendingDeployment>()
|
// poisoned every later staging save on the shared bulk-deploy context. The trade
|
||||||
.Where(p => p.InstanceId == pending.InstanceId)
|
// is that the supersede commits on its own, just before the insert: a failed
|
||||||
.Select(p => p.Id)
|
// insert leaves the instance with no pending row, which is what the superseded
|
||||||
.ToListAsync(cancellationToken);
|
// deploy was about to become anyway.
|
||||||
foreach (var id in priorIds)
|
var instanceId = pending.InstanceId;
|
||||||
{
|
await DeletePendingWhereAsync(p => p.InstanceId == instanceId, cancellationToken);
|
||||||
RemovePendingByKey(id);
|
|
||||||
}
|
|
||||||
await _dbContext.Set<PendingDeployment>().AddAsync(pending, cancellationToken);
|
await _dbContext.Set<PendingDeployment>().AddAsync(pending, cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -505,29 +504,6 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository
|
|||||||
return rows.Count;
|
return rows.Count;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Marks the pending row with primary key <paramref name="id"/> for deletion on the next
|
|
||||||
/// <c>SaveChanges</c> without loading it: an already-tracked instance is removed in place,
|
|
||||||
/// otherwise a key-only stub is attached and removed (EF deletes by key).
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="id">Primary key of the pending row.</param>
|
|
||||||
private void RemovePendingByKey(int id)
|
|
||||||
{
|
|
||||||
var set = _dbContext.Set<PendingDeployment>();
|
|
||||||
var tracked = set.Local.FirstOrDefault(p => p.Id == id);
|
|
||||||
if (tracked != null)
|
|
||||||
{
|
|
||||||
set.Remove(tracked);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var stub = new PendingDeployment(
|
|
||||||
string.Empty, 0, string.Empty, string.Empty, string.Empty,
|
|
||||||
default, default) { Id = id };
|
|
||||||
set.Attach(stub);
|
|
||||||
set.Remove(stub);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public async Task<int> PurgeTerminalDeploymentRecordsAsync(
|
public async Task<int> PurgeTerminalDeploymentRecordsAsync(
|
||||||
DateTimeOffset cutoffUtc,
|
DateTimeOffset cutoffUtc,
|
||||||
@@ -777,6 +753,17 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository
|
|||||||
|
|
||||||
// --- Instance lookups for deployment pipeline ---
|
// --- Instance lookups for deployment pipeline ---
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<InstanceState?> GetInstanceStateAsync(int instanceId, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
// A scalar projection is never tracked and never identity-resolved, so this sees a
|
||||||
|
// state committed by another request after this context loaded the instance.
|
||||||
|
return await _dbContext.Set<Instance>()
|
||||||
|
.Where(i => i.Id == instanceId)
|
||||||
|
.Select(i => (InstanceState?)i.State)
|
||||||
|
.FirstOrDefaultAsync(cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public async Task<Instance?> GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default)
|
public async Task<Instance?> GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
|
|||||||
+47
@@ -501,6 +501,29 @@ public class TemplateEngineRepository : ITemplateEngineRepository
|
|||||||
.FirstOrDefaultAsync(i => i.Id == id, cancellationToken);
|
.FirstOrDefaultAsync(i => i.Id == id, cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<IReadOnlyList<Instance>> GetInstancesByIdsUntrackedAsync(
|
||||||
|
IReadOnlyCollection<int> ids, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(ids);
|
||||||
|
var result = new List<Instance>(ids.Count);
|
||||||
|
// Chunked so the IN list stays well under SQL Server's 2,100-parameter limit.
|
||||||
|
foreach (var chunk in ids.Distinct().Chunk(500))
|
||||||
|
{
|
||||||
|
result.AddRange(await _context.Instances
|
||||||
|
.AsNoTracking()
|
||||||
|
.Where(i => chunk.Contains(i.Id))
|
||||||
|
.Include(i => i.AttributeOverrides)
|
||||||
|
.Include(i => i.AlarmOverrides)
|
||||||
|
.Include(i => i.ConnectionBindings)
|
||||||
|
.Include(i => i.NativeAlarmSourceOverrides)
|
||||||
|
.AsSplitQuery()
|
||||||
|
.ToListAsync(cancellationToken));
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public async Task<IReadOnlyList<Instance>> GetAllInstancesAsync(CancellationToken cancellationToken = default)
|
public async Task<IReadOnlyList<Instance>> GetAllInstancesAsync(CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
@@ -521,6 +544,30 @@ public class TemplateEngineRepository : ITemplateEngineRepository
|
|||||||
.ToListAsync(cancellationToken);
|
.ToListAsync(cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<IReadOnlyList<Instance>> GetInstancesBySiteIdShallowAsync(int siteId, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
return await _context.Instances
|
||||||
|
.AsNoTracking()
|
||||||
|
.Where(i => i.SiteId == siteId)
|
||||||
|
.ToListAsync(cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<bool> TemplateNameExistsInFolderAsync(
|
||||||
|
int? folderId, string name, int excludeTemplateId, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(name);
|
||||||
|
// Only the destination folder's names are read (one narrow projection), then compared
|
||||||
|
// case-insensitively in memory — independent of the database collation.
|
||||||
|
var siblingNames = await _context.Templates
|
||||||
|
.AsNoTracking()
|
||||||
|
.Where(t => t.FolderId == folderId && t.Id != excludeTemplateId)
|
||||||
|
.Select(t => t.Name)
|
||||||
|
.ToListAsync(cancellationToken);
|
||||||
|
return siblingNames.Any(n => string.Equals(n, name, StringComparison.OrdinalIgnoreCase));
|
||||||
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public async Task<IReadOnlyList<Instance>> GetInstancesBySiteIdAsync(int siteId, CancellationToken cancellationToken = default)
|
public async Task<IReadOnlyList<Instance>> GetInstancesBySiteIdAsync(int siteId, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -63,6 +63,9 @@ public class DeploymentService
|
|||||||
/// Reason reported on every <see cref="SkippedInstanceResult"/> a bulk site
|
/// Reason reported on every <see cref="SkippedInstanceResult"/> a bulk site
|
||||||
/// deploy produces for a <see cref="InstanceState.Disabled"/> instance.
|
/// deploy produces for a <see cref="InstanceState.Disabled"/> instance.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <summary>DEP-4: instances bulk-loaded (untracked) per chunk by the fleet staleness read.</summary>
|
||||||
|
private const int StalenessPreloadChunk = 500;
|
||||||
|
|
||||||
internal const string DisabledSkipReason =
|
internal const string DisabledSkipReason =
|
||||||
"Disabled — bulk deploy preserves disabled state; deploy individually to re-enable";
|
"Disabled — bulk deploy preserves disabled state; deploy individually to re-enable";
|
||||||
|
|
||||||
@@ -320,6 +323,20 @@ public class DeploymentService
|
|||||||
{
|
{
|
||||||
var instanceId = instance.Id;
|
var instanceId = instance.Id;
|
||||||
|
|
||||||
|
// DEP-6: a bulk deploy loaded its candidates once, up front, and EF identity
|
||||||
|
// resolution hands Prepare that same tracked entity — so a Disable committed after
|
||||||
|
// the batch started was invisible here, and the batch would deploy (and finalise
|
||||||
|
// as enabled) an instance the operator had just stopped. Disable/enable take this
|
||||||
|
// operation lock too, so a fresh, untracked read of the state taken while holding
|
||||||
|
// it is authoritative. Single-instance deploy (no reconcileGate) keeps
|
||||||
|
// deploy-and-enable as its explicit operator action.
|
||||||
|
if (reconcileGate is not null
|
||||||
|
&& await _repository.GetInstanceStateAsync(instanceId, cancellationToken) == InstanceState.Disabled)
|
||||||
|
{
|
||||||
|
lockHandle.Dispose();
|
||||||
|
return PreparedDeployment.Skipped(DisabledSkipReason);
|
||||||
|
}
|
||||||
|
|
||||||
// Generate unique deployment ID
|
// Generate unique deployment ID
|
||||||
var deploymentId = Guid.NewGuid().ToString("N");
|
var deploymentId = Guid.NewGuid().ToString("N");
|
||||||
|
|
||||||
@@ -493,6 +510,15 @@ public class DeploymentService
|
|||||||
{
|
{
|
||||||
command = await StagePendingDeploymentAsync(prepared, user, cancellationToken);
|
command = await StagePendingDeploymentAsync(prepared, user, cancellationToken);
|
||||||
}
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// DEP-5: a failed staging save leaves its Added row tracked on the scoped
|
||||||
|
// context; in a bulk deploy every later instance's staging save would retry
|
||||||
|
// it and fail the same way. Drop it while still holding dbGate (the only
|
||||||
|
// repository writer in phase 2), like MarkDeploymentFailedAsync does (P7-5).
|
||||||
|
_repository.DetachPendingChanges();
|
||||||
|
throw;
|
||||||
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
dbGate?.Release();
|
dbGate?.Release();
|
||||||
@@ -823,8 +849,19 @@ public class DeploymentService
|
|||||||
string ConfigJson,
|
string ConfigJson,
|
||||||
string SiteIdentifier,
|
string SiteIdentifier,
|
||||||
IDisposable? LockHandle,
|
IDisposable? LockHandle,
|
||||||
Result<DeploymentRecord>? EarlyResult)
|
Result<DeploymentRecord>? EarlyResult,
|
||||||
|
string? SkipReason = null)
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// DEP-6: a bulk-deploy instance found Disabled once its operation lock was held —
|
||||||
|
/// reported as a skipped row (never sent, never re-enabled), not as a failure.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="reason">The skip reason shown in the bulk summary.</param>
|
||||||
|
/// <returns>A prepared deployment holding no lock, with <see cref="SkipReason"/> set.</returns>
|
||||||
|
public static PreparedDeployment Skipped(string reason) =>
|
||||||
|
new(null!, string.Empty, null!, string.Empty, string.Empty, string.Empty, null,
|
||||||
|
Result<DeploymentRecord>.Failure(reason), reason);
|
||||||
|
|
||||||
/// <summary>Builds a prepare-phase-resolved deployment carrying the given result and holding no lock.</summary>
|
/// <summary>Builds a prepare-phase-resolved deployment carrying the given result and holding no lock.</summary>
|
||||||
/// <param name="result">The result to hand back to the caller.</param>
|
/// <param name="result">The result to hand back to the caller.</param>
|
||||||
/// <returns>A prepared deployment whose <see cref="EarlyResult"/> is set.</returns>
|
/// <returns>A prepared deployment whose <see cref="EarlyResult"/> is set.</returns>
|
||||||
@@ -1067,6 +1104,13 @@ public class DeploymentService
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (step.SkipReason is { } skipReason)
|
||||||
|
{
|
||||||
|
skipped.Add(new SkippedInstanceResult(instance.Id, instance.UniqueName, skipReason));
|
||||||
|
disabledCount++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if (step.EarlyResult is { } early)
|
if (step.EarlyResult is { } early)
|
||||||
{
|
{
|
||||||
results.Add(ToInstanceResult(instance.Id, instance.UniqueName, early));
|
results.Add(ToInstanceResult(instance.Id, instance.UniqueName, early));
|
||||||
@@ -2067,13 +2111,25 @@ public class DeploymentService
|
|||||||
// resolved together after the loop with ONE untracked snapshot read.
|
// resolved together after the loop with ONE untracked snapshot read.
|
||||||
var mismatched = new Dictionary<int, string>();
|
var mismatched = new Dictionary<int, string>();
|
||||||
|
|
||||||
foreach (var instanceId in instanceIds.Distinct())
|
// DEP-4: load the deployed instances in untracked chunks (one split query each)
|
||||||
|
// instead of a tracked four-Include load per instance — the evaluator's scoped
|
||||||
|
// context used to end up tracking every deployed instance, override and binding.
|
||||||
|
var toEvaluate = instanceIds.Distinct().Where(deployedHashes.ContainsKey).ToList();
|
||||||
|
foreach (var instanceId in toEvaluate)
|
||||||
{
|
{
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
if (!deployedHashes.TryGetValue(instanceId, out var deployedHash))
|
if (!deployedHashes.TryGetValue(instanceId, out var deployedHash))
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
|
if ((evaluated % StalenessPreloadChunk) == 0)
|
||||||
|
{
|
||||||
|
var chunk = toEvaluate.Skip(evaluated).Take(StalenessPreloadChunk).ToList();
|
||||||
|
session.PreloadInstances(
|
||||||
|
await _templateRepository.GetInstancesByIdsUntrackedAsync(chunk, cancellationToken)
|
||||||
|
?? (IReadOnlyList<Instance>)Array.Empty<Instance>());
|
||||||
|
}
|
||||||
|
|
||||||
evaluated++;
|
evaluated++;
|
||||||
|
|
||||||
// Read-only path: hash only — no validation (its result was always discarded
|
// Read-only path: hash only — no validation (its result was always discarded
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
|
||||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
|
||||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
|
||||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
|
||||||
@@ -48,6 +49,7 @@ public sealed class FlattenSession
|
|||||||
private readonly Dictionary<int, CachedChain> _chains = new();
|
private readonly Dictionary<int, CachedChain> _chains = new();
|
||||||
private readonly Dictionary<int, (long Version, IReadOnlyList<TemplateComposition> Compositions)> _compositions = new();
|
private readonly Dictionary<int, (long Version, IReadOnlyList<TemplateComposition> Compositions)> _compositions = new();
|
||||||
private readonly Dictionary<int, IReadOnlyDictionary<int, DataConnection>> _dataConnections = new();
|
private readonly Dictionary<int, IReadOnlyDictionary<int, DataConnection>> _dataConnections = new();
|
||||||
|
private readonly Dictionary<int, Instance> _preloadedInstances = new();
|
||||||
|
|
||||||
private IReadOnlyList<ResolvedScript>? _sharedScripts;
|
private IReadOnlyList<ResolvedScript>? _sharedScripts;
|
||||||
private IReadOnlyDictionary<string, string>? _schemaLibrary;
|
private IReadOnlyDictionary<string, string>? _schemaLibrary;
|
||||||
@@ -78,6 +80,27 @@ public sealed class FlattenSession
|
|||||||
/// <summary>Number of per-site data-connection queries that missed the memo.</summary>
|
/// <summary>Number of per-site data-connection queries that missed the memo.</summary>
|
||||||
public int DataConnectionLoads { get; private set; }
|
public int DataConnectionLoads { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// DEP-4: hands the session instances already loaded in bulk (untracked) so the flatten
|
||||||
|
/// does not load each one again. Only read-only callers (fleet staleness) preload; a
|
||||||
|
/// deploy's session never does, so prepare keeps its tracked load.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="instances">The preloaded instances.</param>
|
||||||
|
public void PreloadInstances(IEnumerable<Instance> instances)
|
||||||
|
{
|
||||||
|
foreach (var instance in instances)
|
||||||
|
_preloadedInstances[instance.Id] = instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Takes (and forgets) a preloaded instance, so a chunked caller never holds more than
|
||||||
|
/// one chunk of the fleet in memory.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="instanceId">The instance id.</param>
|
||||||
|
/// <returns>The preloaded instance, or <see langword="null"/> when none was preloaded.</returns>
|
||||||
|
public Instance? TakePreloadedInstance(int instanceId) =>
|
||||||
|
_preloadedInstances.Remove(instanceId, out var instance) ? instance : null;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Every template id this session resolved — the union of all inheritance and
|
/// Every template id this session resolved — the union of all inheritance and
|
||||||
/// composed chains it walked. The staleness fast path records the watermark
|
/// composed chains it walked. The staleness fast path records the watermark
|
||||||
|
|||||||
@@ -190,8 +190,9 @@ public class FlatteningPipeline : IFlatteningPipeline
|
|||||||
private async Task<Result<(FlattenedConfiguration Config, IReadOnlyDictionary<int, DataConnection> DataConnections)>>
|
private async Task<Result<(FlattenedConfiguration Config, IReadOnlyDictionary<int, DataConnection> DataConnections)>>
|
||||||
FlattenCoreAsync(int instanceId, FlattenSession session, CancellationToken cancellationToken)
|
FlattenCoreAsync(int instanceId, FlattenSession session, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
// Load instance with full graph
|
// Load instance with full graph (DEP-4: a read-only caller may have bulk-preloaded it)
|
||||||
var instance = await _templateRepo.GetInstanceByIdAsync(instanceId, cancellationToken);
|
var instance = session.TakePreloadedInstance(instanceId)
|
||||||
|
?? await _templateRepo.GetInstanceByIdAsync(instanceId, cancellationToken);
|
||||||
if (instance == null)
|
if (instance == null)
|
||||||
return Result<(FlattenedConfiguration, IReadOnlyDictionary<int, DataConnection>)>.Failure(
|
return Result<(FlattenedConfiguration, IReadOnlyDictionary<int, DataConnection>)>.Failure(
|
||||||
$"Instance with ID {instanceId} not found.");
|
$"Instance with ID {instanceId} not found.");
|
||||||
|
|||||||
@@ -188,7 +188,8 @@ public class AreaService
|
|||||||
return Result<bool>.Failure($"Area with ID {areaId} not found.");
|
return Result<bool>.Failure($"Area with ID {areaId} not found.");
|
||||||
|
|
||||||
// Check for instances assigned to this area
|
// Check for instances assigned to this area
|
||||||
var allInstances = await _repository.GetInstancesBySiteIdAsync(area.SiteId, cancellationToken);
|
// TPL-4: shallow + untracked — only AreaId/UniqueName are read.
|
||||||
|
var allInstances = await _repository.GetInstancesBySiteIdShallowAsync(area.SiteId, cancellationToken);
|
||||||
var allAreas = await _repository.GetAreasBySiteIdAsync(area.SiteId, cancellationToken);
|
var allAreas = await _repository.GetAreasBySiteIdAsync(area.SiteId, cancellationToken);
|
||||||
|
|
||||||
// Collect this area and all descendant area IDs
|
// Collect this area and all descendant area IDs
|
||||||
|
|||||||
@@ -247,7 +247,9 @@ public class InstanceService
|
|||||||
// rule for a composed alarm. Mirrors SetAttributeOverrideAsync.
|
// rule for a composed alarm. Mirrors SetAttributeOverrideAsync.
|
||||||
// The resolver reads member names and lock flags only, so the no-tracking,
|
// The resolver reads member names and lock flags only, so the no-tracking,
|
||||||
// script-body-free analysis projection suffices (review 2026-10-21 04/P6, 08/P1).
|
// script-body-free analysis projection suffices (review 2026-10-21 04/P6, 08/P1).
|
||||||
var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken);
|
// TPL-4: the template's analysis closure (chain + compositions) is all the resolver
|
||||||
|
// walks — not the whole template table.
|
||||||
|
var allTemplates = await _repository.GetTemplateAnalysisClosureAsync(instance.TemplateId, cancellationToken);
|
||||||
var resolvedAlarm = TemplateResolver
|
var resolvedAlarm = TemplateResolver
|
||||||
.ResolveAllMembers(instance.TemplateId, allTemplates)
|
.ResolveAllMembers(instance.TemplateId, allTemplates)
|
||||||
.FirstOrDefault(m => m.MemberType == "Alarm" && m.CanonicalName == alarmCanonicalName);
|
.FirstOrDefault(m => m.MemberType == "Alarm" && m.CanonicalName == alarmCanonicalName);
|
||||||
|
|||||||
@@ -228,12 +228,9 @@ public class TemplateService
|
|||||||
// only invariant the move can break is two templates sharing a
|
// only invariant the move can break is two templates sharing a
|
||||||
// (FolderId, Name) at the destination, which the design's
|
// (FolderId, Name) at the destination, which the design's
|
||||||
// naming-collisions-are-design-time-errors rule forbids.
|
// naming-collisions-are-design-time-errors rule forbids.
|
||||||
var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken);
|
// TPL-4: a (FolderId, Name) existence query, not a load of every template.
|
||||||
var collision = allTemplates.FirstOrDefault(t =>
|
if (await _repository.TemplateNameExistsInFolderAsync(
|
||||||
t.Id != templateId &&
|
newFolderId, template.Name, templateId, cancellationToken))
|
||||||
t.FolderId == newFolderId &&
|
|
||||||
string.Equals(t.Name, template.Name, StringComparison.OrdinalIgnoreCase));
|
|
||||||
if (collision != null)
|
|
||||||
{
|
{
|
||||||
var location = newFolderId.HasValue ? "the target folder" : "the root";
|
var location = newFolderId.HasValue ? "the target folder" : "the root";
|
||||||
return Result<Template>.Failure(
|
return Result<Template>.Failure(
|
||||||
@@ -449,7 +446,9 @@ public class TemplateService
|
|||||||
var template = await _repository.GetTemplateByIdAsync(attribute.TemplateId, cancellationToken);
|
var template = await _repository.GetTemplateByIdAsync(attribute.TemplateId, cancellationToken);
|
||||||
if (template?.ParentTemplateId != null)
|
if (template?.ParentTemplateId != null)
|
||||||
{
|
{
|
||||||
var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken);
|
// TPL-4: the parent's analysis closure is all FindMemberByCanonicalName walks.
|
||||||
|
var allTemplates = await _repository.GetTemplateAnalysisClosureAsync(
|
||||||
|
template.ParentTemplateId.Value, cancellationToken);
|
||||||
var parentMember = TemplateResolver.FindMemberByCanonicalName(
|
var parentMember = TemplateResolver.FindMemberByCanonicalName(
|
||||||
attribute.Name, template.ParentTemplateId.Value, allTemplates);
|
attribute.Name, template.ParentTemplateId.Value, allTemplates);
|
||||||
if (parentMember != null)
|
if (parentMember != null)
|
||||||
@@ -676,7 +675,9 @@ public class TemplateService
|
|||||||
var template = await _repository.GetTemplateByIdAsync(alarm.TemplateId, cancellationToken);
|
var template = await _repository.GetTemplateByIdAsync(alarm.TemplateId, cancellationToken);
|
||||||
if (template?.ParentTemplateId != null)
|
if (template?.ParentTemplateId != null)
|
||||||
{
|
{
|
||||||
var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken);
|
// TPL-4: the parent's analysis closure is all FindMemberByCanonicalName walks.
|
||||||
|
var allTemplates = await _repository.GetTemplateAnalysisClosureAsync(
|
||||||
|
template.ParentTemplateId.Value, cancellationToken);
|
||||||
var parentMember = TemplateResolver.FindMemberByCanonicalName(
|
var parentMember = TemplateResolver.FindMemberByCanonicalName(
|
||||||
alarm.Name, template.ParentTemplateId.Value, allTemplates);
|
alarm.Name, template.ParentTemplateId.Value, allTemplates);
|
||||||
if (parentMember != null)
|
if (parentMember != null)
|
||||||
@@ -853,7 +854,9 @@ public class TemplateService
|
|||||||
var template = await _repository.GetTemplateByIdAsync(script.TemplateId, cancellationToken);
|
var template = await _repository.GetTemplateByIdAsync(script.TemplateId, cancellationToken);
|
||||||
if (template?.ParentTemplateId != null)
|
if (template?.ParentTemplateId != null)
|
||||||
{
|
{
|
||||||
var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken);
|
// TPL-4: the parent's analysis closure is all FindMemberByCanonicalName walks.
|
||||||
|
var allTemplates = await _repository.GetTemplateAnalysisClosureAsync(
|
||||||
|
template.ParentTemplateId.Value, cancellationToken);
|
||||||
var parentMember = TemplateResolver.FindMemberByCanonicalName(
|
var parentMember = TemplateResolver.FindMemberByCanonicalName(
|
||||||
script.Name, template.ParentTemplateId.Value, allTemplates);
|
script.Name, template.ParentTemplateId.Value, allTemplates);
|
||||||
if (parentMember != null)
|
if (parentMember != null)
|
||||||
|
|||||||
+22
@@ -84,6 +84,28 @@ public class PendingDeploymentRepositoryTests : IDisposable
|
|||||||
Assert.Equal(instanceId, current.InstanceId);
|
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>
|
/// <summary>Verifies that pending deployments for different instances coexist.</summary>
|
||||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|||||||
+120
@@ -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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -397,6 +397,62 @@ public class DeploySiteAsyncTests : TestKit
|
|||||||
Arg.Is<DeploymentRecord>(r => r.InstanceId == 2 || r.InstanceId == 4), Arg.Any<CancellationToken>());
|
Arg.Is<DeploymentRecord>(r => r.InstanceId == 2 || r.InstanceId == 4), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// DEP-6 (WP6 6.6): an instance Disabled by another request AFTER the batch loaded its
|
||||||
|
/// candidates is caught by the fresh, lock-held state read — skipped, never flattened,
|
||||||
|
/// sent or finalised as enabled.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task DeploySiteAsync_InstanceDisabledAfterTheBatchStarted_IsSkippedNotReEnabled()
|
||||||
|
{
|
||||||
|
ArrangeInstances(3);
|
||||||
|
// The candidate list (and the tracked entity Prepare re-reads) still says NotDeployed,
|
||||||
|
// but the database already holds the operator's Disable.
|
||||||
|
_repo.GetInstanceStateAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||||
|
.Returns(ci => ci.ArgAt<int>(0) == 2 ? InstanceState.Disabled : InstanceState.NotDeployed);
|
||||||
|
|
||||||
|
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.Equal(2, result.Value.SuccessCount);
|
||||||
|
Assert.DoesNotContain(result.Value.InstanceResults, r => r.UniqueName == "Inst-02");
|
||||||
|
var skipped = Assert.Single(result.Value.SkippedInstances!);
|
||||||
|
Assert.Equal("Inst-02", skipped.UniqueName);
|
||||||
|
await _pipeline.DidNotReceive().FlattenAndValidateAsync(
|
||||||
|
2, Arg.Any<CancellationToken>(), Arg.Any<bool>(), Arg.Any<FlattenSession?>());
|
||||||
|
await _repo.DidNotReceive().AddDeploymentRecordAsync(
|
||||||
|
Arg.Is<DeploymentRecord>(r => r.InstanceId == 2), Arg.Any<CancellationToken>());
|
||||||
|
Assert.False(_lockManager.IsLocked("Inst-02"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// DEP-5 (WP6 6.6): a failed staging save drops its pending changes from the shared
|
||||||
|
/// context, so the instances staged after it are not poisoned by the same failure.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task DeploySiteAsync_FailedStagingWrite_DetachesItsPendingChanges()
|
||||||
|
{
|
||||||
|
ArrangeInstances(3);
|
||||||
|
_repo.AddPendingDeploymentAsync(
|
||||||
|
Arg.Is<PendingDeployment>(p => p.InstanceId == 1), Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Task.FromException(new InvalidOperationException("staging save lost a race")));
|
||||||
|
|
||||||
|
var commActor = Sys.ActorOf(Props.Create(() =>
|
||||||
|
new ThrottledSiteActor(new ConcurrencyTracker(), slowInstanceName: null, slowDelay: TimeSpan.Zero)));
|
||||||
|
|
||||||
|
var result = await CreateService(commActor, maxParallelism: 1).DeploySiteAsync(SiteId, "admin");
|
||||||
|
|
||||||
|
Assert.True(result.IsSuccess);
|
||||||
|
Assert.Equal(2, result.Value.SuccessCount);
|
||||||
|
Assert.Equal("Inst-01", Assert.Single(result.Value.InstanceResults, r => !r.Success).UniqueName);
|
||||||
|
_repo.Received().DetachPendingChanges();
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Phase 1 is serial, so an unreachable site used to cost the batch one
|
/// Phase 1 is serial, so an unreachable site used to cost the batch one
|
||||||
/// full 30-second <c>QueryTimeout</c> PER INSTANCE before a single deploy was
|
/// full 30-second <c>QueryTimeout</c> PER INSTANCE before a single deploy was
|
||||||
|
|||||||
+30
-1
@@ -1,3 +1,4 @@
|
|||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Extensions.Logging.Abstractions;
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
@@ -35,6 +36,9 @@ public class DeploymentServiceStalenessTests
|
|||||||
private readonly RevisionHashService _hasher = new();
|
private readonly RevisionHashService _hasher = new();
|
||||||
private readonly DeploymentService _service;
|
private readonly DeploymentService _service;
|
||||||
|
|
||||||
|
/// <summary>DEP-4: the batched untracked instance loader the staleness read preloads from.</summary>
|
||||||
|
private readonly ITemplateEngineRepository _templateRepo = Substitute.For<ITemplateEngineRepository>();
|
||||||
|
|
||||||
/// <summary>The single session every flatten in a batch must share.</summary>
|
/// <summary>The single session every flatten in a batch must share.</summary>
|
||||||
private readonly FlattenSession _session = new(new TemplateGraphWatermark());
|
private readonly FlattenSession _session = new(new TemplateGraphWatermark());
|
||||||
|
|
||||||
@@ -61,7 +65,7 @@ public class DeploymentServiceStalenessTests
|
|||||||
_service = new DeploymentService(
|
_service = new DeploymentService(
|
||||||
_repo,
|
_repo,
|
||||||
siteRepo,
|
siteRepo,
|
||||||
Substitute.For<ITemplateEngineRepository>(),
|
_templateRepo,
|
||||||
_pipeline,
|
_pipeline,
|
||||||
new CommunicationService(
|
new CommunicationService(
|
||||||
Options.Create(new CommunicationOptions()),
|
Options.Create(new CommunicationOptions()),
|
||||||
@@ -182,6 +186,31 @@ public class DeploymentServiceStalenessTests
|
|||||||
await _pipeline.Received(1).ComputeRevisionHashAsync(3, _session, Arg.Any<CancellationToken>());
|
await _pipeline.Received(1).ComputeRevisionHashAsync(3, _session, Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// DEP-4 (WP6 6.6): the deployed instances are bulk-loaded untracked (one call for the
|
||||||
|
/// batch) and handed to the shared session, instead of one tracked load per flatten.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task GetInstanceStalenessAsync_BulkPreloadsDeployedInstancesUntracked()
|
||||||
|
{
|
||||||
|
var config = ScalarConfig("5");
|
||||||
|
var hash = _hasher.ComputeHash(config);
|
||||||
|
ArrangeDeployedHashes((1, hash), (2, hash));
|
||||||
|
ArrangeFlatten(1, config, hash);
|
||||||
|
ArrangeFlatten(2, config, hash);
|
||||||
|
_templateRepo.GetInstancesByIdsUntrackedAsync(Arg.Any<IReadOnlyCollection<int>>(), Arg.Any<CancellationToken>())
|
||||||
|
.Returns(ci => (IReadOnlyList<Instance>)ci.ArgAt<IReadOnlyCollection<int>>(0)
|
||||||
|
.Select(id => new Instance($"I{id}") { Id = id }).ToList());
|
||||||
|
|
||||||
|
await _service.GetInstanceStalenessAsync([1, 2, 3]); // 3 is not deployed: never loaded
|
||||||
|
|
||||||
|
await _templateRepo.Received(1).GetInstancesByIdsUntrackedAsync(
|
||||||
|
Arg.Is<IReadOnlyCollection<int>>(ids => ids.Order().SequenceEqual(new[] { 1, 2 })),
|
||||||
|
Arg.Any<CancellationToken>());
|
||||||
|
Assert.NotNull(_session.TakePreloadedInstance(1));
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that a matching hash is reported as not stale and no snapshot is read.</summary>
|
/// <summary>Verifies that a matching hash is reported as not stale and no snapshot is read.</summary>
|
||||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|||||||
@@ -97,6 +97,30 @@ public class FlattenSessionCacheTests
|
|||||||
await _siteRepo.Received(1).GetDataConnectionsBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
|
await _siteRepo.Received(1).GetDataConnectionsBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// DEP-4 (WP6 6.6): an instance bulk-preloaded into the session is flattened from the
|
||||||
|
/// session — no per-instance tracked repository load — and is consumed once taken.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task PreloadedInstances_AreFlattenedWithoutPerInstanceLoads()
|
||||||
|
{
|
||||||
|
const int instanceCount = 5;
|
||||||
|
ArrangeSharedChain(instanceCount);
|
||||||
|
|
||||||
|
var session = _sut.CreateSession();
|
||||||
|
session.PreloadInstances(Enumerable.Range(1, instanceCount)
|
||||||
|
.Select(i => new Instance($"Tank-{i:00}") { Id = i, TemplateId = TemplateId, SiteId = SiteId }));
|
||||||
|
for (var i = 1; i <= instanceCount; i++)
|
||||||
|
{
|
||||||
|
var result = await _sut.ComputeRevisionHashAsync(i, session, CancellationToken.None);
|
||||||
|
Assert.True(result.IsSuccess);
|
||||||
|
}
|
||||||
|
|
||||||
|
await _templateRepo.DidNotReceive().GetInstanceByIdAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
|
||||||
|
Assert.Null(session.TakePreloadedInstance(1));
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that no shared session, every instance reloads the chain.</summary>
|
/// <summary>Verifies that no shared session, every instance reloads the chain.</summary>
|
||||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|||||||
@@ -36,6 +36,16 @@ internal static class AnalysisClosureMock
|
|||||||
},
|
},
|
||||||
ct);
|
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>
|
/// <summary>
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ public class AreaServiceTests
|
|||||||
{
|
{
|
||||||
_repoMock.Setup(r => r.GetAreaByIdAsync(1, It.IsAny<CancellationToken>()))
|
_repoMock.Setup(r => r.GetAreaByIdAsync(1, It.IsAny<CancellationToken>()))
|
||||||
.ReturnsAsync(new Area("Building A") { Id = 1, SiteId = 1 });
|
.ReturnsAsync(new Area("Building A") { Id = 1, SiteId = 1 });
|
||||||
_repoMock.Setup(r => r.GetInstancesBySiteIdAsync(1, It.IsAny<CancellationToken>()))
|
_repoMock.Setup(r => r.GetInstancesBySiteIdShallowAsync(1, It.IsAny<CancellationToken>()))
|
||||||
.ReturnsAsync(new List<Instance>
|
.ReturnsAsync(new List<Instance>
|
||||||
{
|
{
|
||||||
new("Inst1") { Id = 1, AreaId = 1, SiteId = 1 }
|
new("Inst1") { Id = 1, AreaId = 1, SiteId = 1 }
|
||||||
@@ -94,7 +94,7 @@ public class AreaServiceTests
|
|||||||
{
|
{
|
||||||
_repoMock.Setup(r => r.GetAreaByIdAsync(1, It.IsAny<CancellationToken>()))
|
_repoMock.Setup(r => r.GetAreaByIdAsync(1, It.IsAny<CancellationToken>()))
|
||||||
.ReturnsAsync(new Area("Parent") { Id = 1, SiteId = 1 });
|
.ReturnsAsync(new Area("Parent") { Id = 1, SiteId = 1 });
|
||||||
_repoMock.Setup(r => r.GetInstancesBySiteIdAsync(1, It.IsAny<CancellationToken>()))
|
_repoMock.Setup(r => r.GetInstancesBySiteIdShallowAsync(1, It.IsAny<CancellationToken>()))
|
||||||
.ReturnsAsync(new List<Instance>());
|
.ReturnsAsync(new List<Instance>());
|
||||||
_repoMock.Setup(r => r.GetAreasBySiteIdAsync(1, It.IsAny<CancellationToken>()))
|
_repoMock.Setup(r => r.GetAreasBySiteIdAsync(1, It.IsAny<CancellationToken>()))
|
||||||
.ReturnsAsync(new List<Area>
|
.ReturnsAsync(new List<Area>
|
||||||
@@ -116,7 +116,7 @@ public class AreaServiceTests
|
|||||||
{
|
{
|
||||||
_repoMock.Setup(r => r.GetAreaByIdAsync(1, It.IsAny<CancellationToken>()))
|
_repoMock.Setup(r => r.GetAreaByIdAsync(1, It.IsAny<CancellationToken>()))
|
||||||
.ReturnsAsync(new Area("Empty") { Id = 1, SiteId = 1 });
|
.ReturnsAsync(new Area("Empty") { Id = 1, SiteId = 1 });
|
||||||
_repoMock.Setup(r => r.GetInstancesBySiteIdAsync(1, It.IsAny<CancellationToken>()))
|
_repoMock.Setup(r => r.GetInstancesBySiteIdShallowAsync(1, It.IsAny<CancellationToken>()))
|
||||||
.ReturnsAsync(new List<Instance>());
|
.ReturnsAsync(new List<Instance>());
|
||||||
_repoMock.Setup(r => r.GetAreasBySiteIdAsync(1, It.IsAny<CancellationToken>()))
|
_repoMock.Setup(r => r.GetAreasBySiteIdAsync(1, It.IsAny<CancellationToken>()))
|
||||||
.ReturnsAsync(new List<Area> { new("Empty") { Id = 1, SiteId = 1 } });
|
.ReturnsAsync(new List<Area> { new("Empty") { Id = 1, SiteId = 1 } });
|
||||||
@@ -312,7 +312,7 @@ public class AreaServiceTests
|
|||||||
new("Mid") { Id = 2, SiteId = 1, ParentAreaId = 1 },
|
new("Mid") { Id = 2, SiteId = 1, ParentAreaId = 1 },
|
||||||
new("Leaf") { Id = 3, SiteId = 1, ParentAreaId = 2 }
|
new("Leaf") { Id = 3, SiteId = 1, ParentAreaId = 2 }
|
||||||
});
|
});
|
||||||
_repoMock.Setup(r => r.GetInstancesBySiteIdAsync(1, It.IsAny<CancellationToken>()))
|
_repoMock.Setup(r => r.GetInstancesBySiteIdShallowAsync(1, It.IsAny<CancellationToken>()))
|
||||||
.ReturnsAsync(new List<Instance>
|
.ReturnsAsync(new List<Instance>
|
||||||
{
|
{
|
||||||
new("DeepInstance") { Id = 10, AreaId = 3, SiteId = 1 }
|
new("DeepInstance") { Id = 10, AreaId = 3, SiteId = 1 }
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ public class InstanceServiceTests
|
|||||||
/// <summary>Initializes the test with a mocked repository and audit service and the service under test.</summary>
|
/// <summary>Initializes the test with a mocked repository and audit service and the service under test.</summary>
|
||||||
public InstanceServiceTests()
|
public InstanceServiceTests()
|
||||||
{
|
{
|
||||||
|
_repoMock.ServeClosureFromFullGraph(); // TPL-4: SetAlarmOverride reads the analysis closure
|
||||||
_sut = new InstanceService(_repoMock.Object, _auditMock.Object);
|
_sut = new InstanceService(_repoMock.Object, _auditMock.Object);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user